source: CLRX/CLRadeonExtender/trunk/CLRX/amdasm/Assembler.h @ 3897

Last change on this file since 3897 was 3897, checked in by matszpk, 16 months ago

CLRadeonExtender: AsmRegAlloc?: Avoid inserting duplicates into SSAReplaces (use to this VectorSet?).

File size: 30.7 KB
Line 
1/*
2 *  CLRadeonExtender - Unofficial OpenCL Radeon Extensions Library
3 *  Copyright (C) 2014-2018 Mateusz Szpakowski
4 *
5 *  This library is free software; you can redistribute it and/or
6 *  modify it under the terms of the GNU Lesser General Public
7 *  License as published by the Free Software Foundation; either
8 *  version 2.1 of the License, or (at your option) any later version.
9 *
10 *  This library is distributed in the hope that it will be useful,
11 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 *  Lesser General Public License for more details.
14 *
15 *  You should have received a copy of the GNU Lesser General Public
16 *  License along with this library; if not, write to the Free Software
17 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18 */
19/*! \file Assembler.h
20 * \brief an assembler for Radeon GPU's
21 */
22
23#ifndef __CLRX_ASSEMBLER_H__
24#define __CLRX_ASSEMBLER_H__
25
26#include <CLRX/Config.h>
27#include <cstdint>
28#include <string>
29#include <istream>
30#include <ostream>
31#include <iostream>
32#include <vector>
33#include <utility>
34#include <stack>
35#include <list>
36#include <unordered_set>
37#include <unordered_map>
38#include <CLRX/utils/Utilities.h>
39#include <CLRX/utils/Containers.h>
40#include <CLRX/amdasm/Commons.h>
41#include <CLRX/amdasm/AsmSource.h>
42#include <CLRX/amdasm/AsmFormats.h>
43#include <CLRX/amdasm/AsmDefs.h>
44
45/// main namespace
46namespace CLRX
47{
48
49enum: Flags
50{
51    ASM_WARNINGS = 1,   ///< enable all warnings for assembler
52    ASM_FORCE_ADD_SYMBOLS = 2,  ///< force add symbols to binary
53    ASM_ALTMACRO = 4,   ///< enable altmacro mode
54    ASM_BUGGYFPLIT = 8, ///< buggy handling of fpliterals (including fp constants)
55    ASM_MACRONOCASE = 16, /// disable case-insensitive naming (default)
56    ASM_OLDMODPARAM = 32,   ///< use old modifier parametrization (values 0 and 1 only)
57    ASM_TESTRESOLVE = (1U<<30), ///< enable resolving symbols if ASM_TESTRUN enabled
58    ASM_TESTRUN = (1U<<31), ///< only for running tests
59    ASM_ALL = FLAGS_ALL&~(ASM_TESTRUN|ASM_TESTRESOLVE|ASM_BUGGYFPLIT|ASM_MACRONOCASE|
60                    ASM_OLDMODPARAM)  ///< all flags
61};
62
63struct AsmRegVar;
64
65/// ISA (register and regvar) Usage handler
66class ISAUsageHandler
67{
68public:
69    /// stgructure that hold read position to store later
70    struct ReadPos
71    {
72        size_t readOffset;  ///< read offset
73        size_t instrStructPos;  ///< position instrStructs
74        size_t regUsagesPos;    ///< position in reg usage
75        size_t regUsages2Pos;   ///< position in regUsage2
76        size_t regVarUsagesPos;    ///< position in regVarUsage
77        uint16_t pushedArgs;    ///< pushed argds number
78        bool useRegMode;        ///< true if in usereg mode
79    };
80protected:
81    std::vector<cxbyte> instrStruct;    ///< structure of register usage
82    std::vector<AsmRegUsageInt> regUsages;  ///< register usage
83    std::vector<AsmRegUsage2Int> regUsages2;  ///< register usage (by .usereg)
84    std::vector<AsmRegVarUsageInt> regVarUsages;    ///< regvar usage
85    const std::vector<cxbyte>& content; ///< code content
86    size_t lastOffset;  ///< last offset
87    size_t readOffset;  ///< read offset
88    size_t instrStructPos;  ///< position in instr struct
89    size_t regUsagesPos;    ///< position in reg usage
90    size_t regUsages2Pos;   ///< position in reg usage 2
91    size_t regVarUsagesPos; ///< position in regvar usage
92    uint16_t pushedArgs;    ///< pushed args
93    cxbyte argPos;      ///< argument position
94    cxbyte argFlags;    ///< ???
95    cxbyte defaultInstrSize;    ///< default instruction size
96    bool isNext;        ///< is next
97    bool useRegMode;    ///< true if in usereg mode
98   
99    void skipBytesInInstrStruct();
100    /// put space to offset
101    void putSpace(size_t offset);
102   
103    /// constructor
104    explicit ISAUsageHandler(const std::vector<cxbyte>& content);
105public:
106    /// destructor
107    virtual ~ISAUsageHandler();
108    /// copy this usage handler
109    virtual ISAUsageHandler* copy() const = 0;
110   
111    /// push regvar or register usage
112    void pushUsage(const AsmRegVarUsage& rvu);
113    /// rewind to start for reading
114    void rewind();
115    /// flush last pending register usages
116    void flush();
117    /// has next regvar usage
118    bool hasNext() const
119    { return isNext; }
120    /// get next usage
121    AsmRegVarUsage nextUsage();
122   
123    /// get reading position
124    ReadPos getReadPos() const
125    {
126        return { readOffset, instrStructPos, regUsagesPos, regUsages2Pos,
127            regVarUsagesPos, pushedArgs, useRegMode };
128    }
129    /// set reading position
130    void setReadPos(const ReadPos rpos)
131    {
132        readOffset = rpos.readOffset;
133        instrStructPos = rpos.instrStructPos;
134        regUsagesPos = rpos.regUsagesPos;
135        regUsages2Pos = rpos.regUsages2Pos;
136        regVarUsagesPos = rpos.regVarUsagesPos;
137        pushedArgs = rpos.pushedArgs;
138        useRegMode = rpos.useRegMode;
139    }
140   
141    /// push regvar or register from usereg pseudo-op
142    void pushUseRegUsage(const AsmRegVarUsage& rvu);
143   
144    /// get RW flags (used by assembler)
145    virtual cxbyte getRwFlags(AsmRegField regField, uint16_t rstart,
146                      uint16_t rend) const = 0;
147    /// get reg pair (used by assembler)
148    virtual std::pair<uint16_t,uint16_t> getRegPair(AsmRegField regField,
149                    cxbyte rwFlags) const = 0;
150    /// get usage dependencies around single instruction
151    virtual void getUsageDependencies(cxuint rvusNum, const AsmRegVarUsage* rvus,
152                    cxbyte* linearDeps, cxbyte* equalToDeps) const = 0;
153};
154
155/// GCN (register and regvar) Usage handler
156class GCNUsageHandler: public ISAUsageHandler
157{
158private:
159    uint16_t archMask;
160public:
161    /// constructor
162    GCNUsageHandler(const std::vector<cxbyte>& content, uint16_t archMask);
163    /// destructor
164    ~GCNUsageHandler();
165   
166    /// copy this usage handler
167    ISAUsageHandler* copy() const;
168   
169    cxbyte getRwFlags(AsmRegField regFied, uint16_t rstart, uint16_t rend) const;
170    std::pair<uint16_t,uint16_t> getRegPair(AsmRegField regField, cxbyte rwFlags) const;
171    void getUsageDependencies(cxuint rvusNum, const AsmRegVarUsage* rvus,
172                    cxbyte* linearDeps, cxbyte* equalToDeps) const;
173};
174
175/// ISA assembler class
176class ISAAssembler: public NonCopyableAndNonMovable
177{
178protected:
179    Assembler& assembler;       ///< assembler
180   
181    /// print warning for position pointed by line pointer
182    void printWarning(const char* linePtr, const char* message);
183    /// print error for position pointed by line pointer
184    void printError(const char* linePtr, const char* message);
185    /// print warning for source position
186    void printWarning(const AsmSourcePos& sourcePos, const char* message);
187    /// print error for source position
188    void printError(const AsmSourcePos& sourcePos, const char* message);
189    /// print warning about integer out of range
190    void printWarningForRange(cxuint bits, uint64_t value, const AsmSourcePos& pos,
191                cxbyte signess = WS_BOTH);
192    void addCodeFlowEntry(cxuint sectionId, const AsmCodeFlowEntry& entry);
193    /// constructor
194    explicit ISAAssembler(Assembler& assembler);
195public:
196    /// destructor
197    virtual ~ISAAssembler();
198    /// create usage handler
199    virtual ISAUsageHandler* createUsageHandler(std::vector<cxbyte>& content) const = 0;
200   
201    /// assemble single line
202    virtual void assemble(const CString& mnemonic, const char* mnemPlace,
203              const char* linePtr, const char* lineEnd, std::vector<cxbyte>& output,
204              ISAUsageHandler* usageHandler) = 0;
205    /// resolve code with location, target and value
206    virtual bool resolveCode(const AsmSourcePos& sourcePos, cxuint targetSectionId,
207                 cxbyte* sectionData, size_t offset, AsmExprTargetType targetType,
208                 cxuint sectionId, uint64_t value) = 0;
209    /// check if name is mnemonic
210    virtual bool checkMnemonic(const CString& mnemonic) const = 0;
211    /// set allocated registers (if regs is null then reset them)
212    virtual void setAllocatedRegisters(const cxuint* regs = nullptr,
213                Flags regFlags = 0) = 0;
214    /// get allocated register numbers after assemblying
215    virtual const cxuint* getAllocatedRegisters(size_t& regTypesNum,
216                Flags& regFlags) const = 0;
217    /// get max registers number
218    virtual void getMaxRegistersNum(size_t& regTypesNum, cxuint* maxRegs) const = 0;
219    /// get registers ranges
220    virtual void getRegisterRanges(size_t& regTypesNum, cxuint* regRanges) const = 0;
221    /// fill alignment when value is not given
222    virtual void fillAlignment(size_t size, cxbyte* output) = 0;
223    /// parse register range
224    virtual bool parseRegisterRange(const char*& linePtr, cxuint& regStart,
225                        cxuint& regEnd, const AsmRegVar*& regVar) = 0;
226    /// return true if expresion of target fit to value with specified bits
227    virtual bool relocationIsFit(cxuint bits, AsmExprTargetType tgtType) = 0;
228    /// parse register type for '.reg' pseudo-op
229    virtual bool parseRegisterType(const char*& linePtr,
230                       const char* end, cxuint& type) = 0;
231    /// get size of instruction
232    virtual size_t getInstructionSize(size_t codeSize, const cxbyte* code) const = 0;
233};
234
235/// GCN arch assembler
236class GCNAssembler: public ISAAssembler
237{
238public:
239    /// register pool numbers
240    struct Regs {
241        cxuint sgprsNum;    ///< SGPRs number
242        cxuint vgprsNum;    ///< VGPRs number
243        Flags regFlags; ///< define what extra register must be included
244    };
245private:
246    friend struct GCNAsmUtils; // INTERNAL LOGIC
247    union {
248        Regs regs;
249        cxuint regTable[2];
250    };
251    uint16_t curArchMask;
252    cxbyte currentRVUIndex;
253    AsmRegVarUsage instrRVUs[6];
254   
255    void resetInstrRVUs()
256    {
257        for (AsmRegVarUsage& rvu: instrRVUs)
258            rvu.regField = ASMFIELD_NONE;
259    }
260    void setCurrentRVU(cxbyte idx)
261    { currentRVUIndex = idx; }
262   
263    void setRegVarUsage(const AsmRegVarUsage& rvu)
264    { instrRVUs[currentRVUIndex] = rvu; }
265   
266    void flushInstrRVUs(ISAUsageHandler* usageHandler)
267    {
268        for (const AsmRegVarUsage& rvu: instrRVUs)
269            if (rvu.regField != ASMFIELD_NONE)
270                usageHandler->pushUsage(rvu);
271    }
272public:
273    /// constructor
274    explicit GCNAssembler(Assembler& assembler);
275    /// destructor
276    ~GCNAssembler();
277   
278    ISAUsageHandler* createUsageHandler(std::vector<cxbyte>& content) const;
279   
280    void assemble(const CString& mnemonic, const char* mnemPlace, const char* linePtr,
281                  const char* lineEnd, std::vector<cxbyte>& output,
282                  ISAUsageHandler* usageHandler);
283    bool resolveCode(const AsmSourcePos& sourcePos, cxuint targetSectionId,
284                 cxbyte* sectionData, size_t offset, AsmExprTargetType targetType,
285                 cxuint sectionId, uint64_t value);
286    bool checkMnemonic(const CString& mnemonic) const;
287    void setAllocatedRegisters(const cxuint* regs, Flags regFlags);
288    const cxuint* getAllocatedRegisters(size_t& regTypesNum, Flags& regFlags) const;
289    void getMaxRegistersNum(size_t& regTypesNum, cxuint* maxRegs) const;
290    void getRegisterRanges(size_t& regTypesNum, cxuint* regRanges) const;
291    void fillAlignment(size_t size, cxbyte* output);
292    bool parseRegisterRange(const char*& linePtr, cxuint& regStart, cxuint& regEnd,
293                const AsmRegVar*& regVar);
294    bool relocationIsFit(cxuint bits, AsmExprTargetType tgtType);
295    bool parseRegisterType(const char*& linePtr, const char* end, cxuint& type);
296    size_t getInstructionSize(size_t codeSize, const cxbyte* code) const;
297};
298
299class AsmRegAllocator
300{
301public:
302    struct NextBlock
303    {
304        size_t block;
305        bool isCall;
306    };
307    struct SSAInfo
308    {
309        size_t ssaIdBefore; ///< SSA id before first SSA in block
310        size_t ssaIdFirst; // SSA id at first change
311        size_t ssaId;   ///< original SSA id
312        size_t ssaIdLast; ///< last SSA id in last
313        size_t ssaIdChange; ///< number of SSA id changes
314        size_t firstPos;
315        size_t lastPos;
316        bool readBeforeWrite;   ///< have read before write
317        SSAInfo(size_t _bssaId = SIZE_MAX, size_t _ssaIdF = SIZE_MAX,
318                size_t _ssaId = SIZE_MAX, size_t _ssaIdL = SIZE_MAX,
319                size_t _ssaIdChange = 0, bool _readBeforeWrite = false)
320            : ssaIdBefore(_bssaId), ssaIdFirst(_ssaIdF), ssaId(_ssaId),
321              ssaIdLast(_ssaIdL), ssaIdChange(_ssaIdChange),
322              readBeforeWrite(_readBeforeWrite)
323        { }
324    };
325    struct CodeBlock
326    {
327        size_t start, end; // place in code
328        std::vector<NextBlock> nexts; ///< nexts blocks, if empty then direct next block
329        bool haveCalls;
330        bool haveReturn;
331        bool haveEnd;
332        // key - regvar, value - SSA info for this regvar
333        std::unordered_map<AsmSingleVReg, SSAInfo> ssaInfoMap;
334        ISAUsageHandler::ReadPos usagePos;
335    };
336   
337     // first - orig ssaid, second - dest ssaid
338    typedef std::pair<size_t, size_t> SSAReplace;
339    typedef std::unordered_map<AsmSingleVReg, VectorSet<SSAReplace> > SSAReplacesMap;
340    // interference graph type
341    typedef Array<std::unordered_set<size_t> > InterGraph;
342    typedef std::unordered_map<AsmSingleVReg, std::vector<size_t> > VarIndexMap;
343    struct LinearDep
344    {
345        cxbyte align;
346        std::vector<size_t> prevVidxes;
347        std::vector<size_t> nextVidxes;
348    };
349    struct EqualToDep
350    {
351        std::vector<size_t> prevVidxes;
352        std::vector<size_t> nextVidxes;
353    };
354private:
355    Assembler& assembler;
356    std::vector<CodeBlock> codeBlocks;
357    SSAReplacesMap ssaReplacesMap;
358    size_t regTypesNum;
359   
360    VarIndexMap vregIndexMaps[MAX_REGTYPES_NUM]; // indices to igraph for 2 reg types
361    InterGraph interGraphs[MAX_REGTYPES_NUM]; // for 2 register
362    Array<cxuint> graphColorMaps[MAX_REGTYPES_NUM];
363    std::unordered_map<size_t, LinearDep> linearDepMaps[MAX_REGTYPES_NUM];
364    std::unordered_map<size_t, EqualToDep> equalToDepMaps[MAX_REGTYPES_NUM];
365    std::unordered_map<size_t, size_t> equalSetMaps[MAX_REGTYPES_NUM];
366    std::vector<std::vector<size_t> > equalSetLists[MAX_REGTYPES_NUM];
367public:
368    AsmRegAllocator(Assembler& assembler);
369   
370    void createCodeStructure(const std::vector<AsmCodeFlowEntry>& codeFlow,
371             size_t codeSize, const cxbyte* code);
372    void createSSAData(ISAUsageHandler& usageHandler);
373    void applySSAReplaces();
374    void createInterferenceGraph(ISAUsageHandler& usageHandler);
375    void colorInterferenceGraph();
376   
377    void allocateRegisters(cxuint sectionId);
378   
379    const std::vector<CodeBlock>& getCodeBlocks() const
380    { return codeBlocks; }
381    const SSAReplacesMap& getSSAReplacesMap() const
382    { return ssaReplacesMap; }
383};
384
385/// type of clause
386enum class AsmClauseType
387{
388    IF,     ///< if clause
389    ELSEIF, ///< elseif clause
390    ELSE,   ///< else clause
391    REPEAT, ///< rept clause or irp/irpc clause
392    MACRO   ///< macro clause
393};
394
395/// assembler's clause (if,else,macro,rept)
396struct AsmClause
397{
398    AsmClauseType type; ///< type of clause
399    AsmSourcePos sourcePos;   ///< position in source code
400    bool condSatisfied; ///< if conditional clause has already been satisfied
401    AsmSourcePos prevIfPos; ///< position of previous if-clause
402};
403
404/// main class of assembler
405class Assembler: public NonCopyableAndNonMovable
406{
407public:
408    /// defined symbol entry
409    typedef std::pair<CString, uint64_t> DefSym;
410    /// kernel map type
411    typedef std::unordered_map<CString, cxuint> KernelMap;
412private:
413    friend class AsmStreamInputFilter;
414    friend class AsmMacroInputFilter;
415    friend class AsmForInputFilter;
416    friend class AsmExpression;
417    friend class AsmFormatHandler;
418    friend class AsmRawCodeHandler;
419    friend class AsmAmdHandler;
420    friend class AsmAmdCL2Handler;
421    friend class AsmGalliumHandler;
422    friend class AsmROCmHandler;
423    friend class ISAAssembler;
424    friend class AsmRegAllocator;
425   
426    friend struct AsmParseUtils; // INTERNAL LOGIC
427    friend struct AsmPseudoOps; // INTERNAL LOGIC
428    friend struct AsmGalliumPseudoOps; // INTERNAL LOGIC
429    friend struct AsmAmdPseudoOps; // INTERNAL LOGIC
430    friend struct AsmAmdCL2PseudoOps; // INTERNAL LOGIC
431    friend struct AsmROCmPseudoOps; // INTERNAL LOGIC
432    friend struct GCNAsmUtils; // INTERNAL LOGIC
433
434    Array<CString> filenames;
435    BinaryFormat format;
436    GPUDeviceType deviceType;
437    uint32_t driverVersion;
438    uint32_t llvmVersion; // GalliumCompute
439    bool _64bit;    ///
440    bool newROCmBinFormat;
441    bool good;
442    bool resolvingRelocs;
443    bool doNotRemoveFromSymbolClones;
444    ISAAssembler* isaAssembler;
445    std::vector<DefSym> defSyms;
446    std::vector<CString> includeDirs;
447    std::vector<AsmSection> sections;
448    std::vector<Array<cxuint> > relSpacesSections;
449    std::unordered_set<AsmSymbolEntry*> symbolSnapshots;
450    std::unordered_set<AsmSymbolEntry*> symbolClones;
451    std::vector<AsmExpression*> unevalExpressions;
452    std::vector<AsmRelocation> relocations;
453    AsmScope globalScope;
454    AsmMacroMap macroMap;
455    std::stack<AsmScope*> scopeStack;
456    std::vector<AsmScope*> abandonedScopes;
457    AsmScope* currentScope;
458    KernelMap kernelMap;
459    std::vector<AsmKernel> kernels;
460    /// register variables
461    Flags flags;
462    uint64_t macroCount;
463    uint64_t localCount; // macro's local count
464    bool alternateMacro;
465    bool buggyFPLit;
466    bool macroCase;
467    bool oldModParam;
468   
469    cxuint inclusionLevel;
470    cxuint macroSubstLevel;
471    cxuint repetitionLevel;
472    bool lineAlreadyRead; // if line already read
473   
474    size_t lineSize;
475    const char* line;
476    bool endOfAssembly;
477    bool sectionDiffsPrepared;
478   
479    cxuint filenameIndex;
480    std::stack<AsmInputFilter*> asmInputFilters;
481    AsmInputFilter* currentInputFilter;
482   
483    std::ostream& messageStream;
484    std::ostream& printStream;
485   
486    AsmFormatHandler* formatHandler;
487   
488    std::stack<AsmClause> clauses;
489   
490    cxuint currentKernel;
491    cxuint& currentSection;
492    uint64_t& currentOutPos;
493   
494    bool withSectionDiffs() const
495    { return formatHandler!=nullptr && formatHandler->isSectionDiffsResolvable(); }
496   
497    AsmSourcePos getSourcePos(LineCol lineCol) const
498    {
499        return { currentInputFilter->getMacroSubst(), currentInputFilter->getSource(),
500            lineCol.lineNo, lineCol.colNo };
501    }
502   
503    AsmSourcePos getSourcePos(size_t pos) const
504    { return currentInputFilter->getSourcePos(pos); }
505    AsmSourcePos getSourcePos(const char* linePtr) const
506    { return getSourcePos(linePtr-line); }
507   
508    void printWarning(const AsmSourcePos& pos, const char* message);
509    void printError(const AsmSourcePos& pos, const char* message);
510   
511    void printWarning(const char* linePtr, const char* message)
512    { printWarning(getSourcePos(linePtr), message); }
513    void printError(const char* linePtr, const char* message)
514    { printError(getSourcePos(linePtr), message); }
515   
516    void printWarning(LineCol lineCol, const char* message)
517    { printWarning(getSourcePos(lineCol), message); }
518    void printError(LineCol lineCol, const char* message)
519    { printError(getSourcePos(lineCol), message); }
520   
521    LineCol translatePos(const char* linePtr) const
522    { return currentInputFilter->translatePos(linePtr-line); }
523    LineCol translatePos(size_t pos) const
524    { return currentInputFilter->translatePos(pos); }
525   
526    bool parseLiteral(uint64_t& value, const char*& linePtr);
527    bool parseLiteralNoError(uint64_t& value, const char*& linePtr);
528    bool parseString(std::string& outString, const char*& linePtr);
529   
530    enum class ParseState
531    {
532        FAILED = 0,
533        PARSED,
534        MISSING // missing element
535    };
536   
537    /** parse symbol
538     * \return state
539     */
540    ParseState parseSymbol(const char*& linePtr, AsmSymbolEntry*& entry,
541                   bool localLabel = true, bool dontCreateSymbol = false);
542    bool skipSymbol(const char*& linePtr);
543   
544    bool setSymbol(AsmSymbolEntry& symEntry, uint64_t value, cxuint sectionId);
545   
546    bool assignSymbol(const CString& symbolName, const char* symbolPlace,
547                  const char* linePtr, bool reassign = true, bool baseExpr = false);
548   
549    bool assignOutputCounter(const char* symbolPlace, uint64_t value, cxuint sectionId,
550                     cxbyte fillValue = 0);
551   
552    void parsePseudoOps(const CString& firstName, const char* stmtPlace,
553                const char* linePtr);
554   
555    /// exitm - exit macro mode
556    bool skipClauses(bool exitm = false);
557    bool putMacroContent(RefPtr<AsmMacro> macro);
558    bool putRepetitionContent(AsmRepeat& repeat);
559   
560    void initializeOutputFormat();
561   
562    bool pushClause(const char* string, AsmClauseType clauseType)
563    {
564        bool included; // to ignore
565        return pushClause(string, clauseType, true, included);
566    }
567    bool pushClause(const char* string, AsmClauseType clauseType,
568                  bool satisfied, bool& included);
569     // return false when failed (for example no clauses)
570    bool popClause(const char* string, AsmClauseType clauseType);
571   
572    // recursive function to find scope in scope
573    AsmScope* findScopeInScope(AsmScope* scope, const CString& scopeName,
574                    std::unordered_set<AsmScope*>& scopeSet);
575    // find scope by identifier
576    AsmScope* getRecurScope(const CString& scopePlace, bool ignoreLast = false,
577                    const char** lastStep = nullptr);
578    // find symbol in scopes
579    // internal recursive function to find symbol in scope
580    AsmSymbolEntry* findSymbolInScopeInt(AsmScope* scope, const CString& symName,
581                    std::unordered_set<AsmScope*>& scopeSet);
582    // scope - return scope from scoped name
583    AsmSymbolEntry* findSymbolInScope(const CString& symName, AsmScope*& scope,
584                      CString& sameSymName, bool insertMode = false);
585    // similar to map::insert, but returns pointer
586    std::pair<AsmSymbolEntry*, bool> insertSymbolInScope(const CString& symName,
587                 const AsmSymbol& symbol);
588   
589    // internal recursive function to find symbol in scope
590    AsmRegVarEntry* findRegVarInScopeInt(AsmScope* scope, const CString& rvName,
591                    std::unordered_set<AsmScope*>& scopeSet);
592    // scope - return scope from scoped name
593    AsmRegVarEntry* findRegVarInScope(const CString& rvName, AsmScope*& scope,
594                      CString& sameRvName, bool insertMode = false);
595    // similar to map::insert, but returns pointer
596    std::pair<AsmRegVarEntry*, bool> insertRegVarInScope(const CString& rvName,
597                 const AsmRegVar& regVar);
598   
599    // create scope
600    bool getScope(AsmScope* parent, const CString& scopeName, AsmScope*& scope);
601    // push new scope level
602    bool pushScope(const CString& scopeName);
603    bool popScope();
604   
605    /// returns false when includeLevel is too deep, throw error if failed a file opening
606    bool includeFile(const char* pseudoOpPlace, const std::string& filename);
607   
608    ParseState makeMacroSubstitution(const char* string);
609   
610    bool parseMacroArgValue(const char*& linePtr, std::string& outStr);
611   
612    void putData(size_t size, const cxbyte* data)
613    {
614        AsmSection& section = sections[currentSection];
615        section.content.insert(section.content.end(), data, data+size);
616        currentOutPos += size;
617    }
618   
619    cxbyte* reserveData(size_t size, cxbyte fillValue = 0);
620   
621    void goToMain(const char* pseudoOpPlace);
622    void goToKernel(const char* pseudoOpPlace, const char* kernelName);
623    void goToSection(const char* pseudoOpPlace, const char* sectionName, uint64_t align=0);
624    void goToSection(const char* pseudoOpPlace, const char* sectionName,
625                     AsmSectionType type, Flags flags, uint64_t align=0);
626    void goToSection(const char* pseudoOpPlace, cxuint sectionId, uint64_t align=0);
627   
628    void printWarningForRange(cxuint bits, uint64_t value, const AsmSourcePos& pos,
629                  cxbyte signess = WS_BOTH);
630   
631    bool isAddressableSection() const
632    {
633        return currentSection==ASMSECT_ABS ||
634                    (sections[currentSection].flags & ASMSECT_ADDRESSABLE) != 0;
635    }
636    bool isWriteableSection() const
637    {
638        return currentSection!=ASMSECT_ABS &&
639                (sections[currentSection].flags & ASMSECT_WRITEABLE) != 0;
640    }
641    bool isResolvableSection() const
642    {
643        return currentSection==ASMSECT_ABS ||
644                (sections[currentSection].flags & ASMSECT_UNRESOLVABLE) == 0;
645    }
646    bool isResolvableSection(cxuint sectionId) const
647    {
648        return sectionId==ASMSECT_ABS ||
649                (sections[sectionId].flags & ASMSECT_UNRESOLVABLE) == 0;
650    }
651   
652    // oldKernels and newKernels must be sorted
653    void handleRegionsOnKernels(const std::vector<cxuint>& newKernels,
654                const std::vector<cxuint>& oldKernels, cxuint codeSection);
655   
656    void tryToResolveSymbol(AsmSymbolEntry& symEntry);
657    void tryToResolveSymbols(AsmScope* scope);
658    void printUnresolvedSymbols(AsmScope* scope);
659   
660    bool resolveExprTarget(const AsmExpression* expr, uint64_t value, cxuint sectionId);
661   
662    void cloneSymEntryIfNeeded(AsmSymbolEntry& symEntry);
663   
664    void undefineSymbol(AsmSymbolEntry& symEntry);
665   
666protected:
667    /// helper for testing
668    bool readLine();
669public:
670    /// constructor with filename and input stream
671    /**
672     * \param filename filename
673     * \param input input stream
674     * \param flags assembler flags
675     * \param format output format type
676     * \param deviceType GPU device type
677     * \param msgStream stream for warnings and errors
678     * \param printStream stream for printing message by .print pseudo-ops
679     */
680    explicit Assembler(const CString& filename, std::istream& input, Flags flags = 0,
681              BinaryFormat format = BinaryFormat::AMD,
682              GPUDeviceType deviceType = GPUDeviceType::CAPE_VERDE,
683              std::ostream& msgStream = std::cerr, std::ostream& printStream = std::cout);
684   
685    /// constructor with filename and input stream
686    /**
687     * \param filenames filenames
688     * \param flags assembler flags
689     * \param format output format type
690     * \param deviceType GPU device type
691     * \param msgStream stream for warnings and errors
692     * \param printStream stream for printing message by .print pseudo-ops
693     */
694    explicit Assembler(const Array<CString>& filenames, Flags flags = 0,
695              BinaryFormat format = BinaryFormat::AMD,
696              GPUDeviceType deviceType = GPUDeviceType::CAPE_VERDE,
697              std::ostream& msgStream = std::cerr, std::ostream& printStream = std::cout);
698    /// destructor
699    ~Assembler();
700   
701    /// main routine to assemble code
702    bool assemble();
703   
704    /// write binary to file
705    void writeBinary(const char* filename) const;
706    /// write binary to stream
707    void writeBinary(std::ostream& outStream) const;
708    /// write binary to array
709    void writeBinary(Array<cxbyte>& array) const;
710   
711    /// get AMD driver version
712    uint32_t getDriverVersion() const
713    { return driverVersion; }
714    /// set AMD driver version
715    void setDriverVersion(uint32_t driverVersion)
716    { this->driverVersion = driverVersion; }
717   
718    /// get LLVM version
719    uint32_t getLLVMVersion() const
720    { return llvmVersion; }
721    /// set LLVM version
722    void setLLVMVersion(uint32_t llvmVersion)
723    { this->llvmVersion = llvmVersion; }
724   
725    /// get GPU device type
726    GPUDeviceType getDeviceType() const
727    { return deviceType; }
728    /// set GPU device type
729    void setDeviceType(const GPUDeviceType deviceType)
730    { this->deviceType = deviceType; }
731    /// get binary format
732    BinaryFormat getBinaryFormat() const
733    { return format; }
734    /// set binary format
735    void setBinaryFormat(BinaryFormat binFormat)
736    { format = binFormat; }
737    /// get bitness (true if 64-bit)
738    bool is64Bit() const
739    { return _64bit; }
740    /// set bitness (true if 64-bit)
741    void set64Bit(bool this64Bit)
742    {  _64bit = this64Bit; }
743    /// is new ROCm binary format
744    bool isNewROCmBinFormat() const
745    { return newROCmBinFormat; }
746    /// set new ROCm binary format
747    void setNewROCmBinFormat(bool newFmt)
748    { newROCmBinFormat = newFmt; }
749    /// get flags
750    Flags getFlags() const
751    { return flags; }
752    /// set flags
753    void setFlags(Flags flags)
754    { this->flags = flags; }
755    /// get true if altMacro enabled
756    bool isAltMacro() const
757    { return alternateMacro; }
758    /// get true if macroCase enabled
759    bool isMacroCase() const
760    { return macroCase; }
761    /// get true if oldModParam enabled (old modifier parametrization)
762    bool isOldModParam() const
763    { return oldModParam; }
764    /// get true if buggyFPLit enabled
765    bool isBuggyFPLit() const
766    { return buggyFPLit; }
767    /// get include directory list
768    const std::vector<CString>& getIncludeDirs() const
769    { return includeDirs; }
770    /// adds include directory
771    void addIncludeDir(const CString& includeDir);
772    /// get symbols map
773    const AsmSymbolMap& getSymbolMap() const
774    { return globalScope.symbolMap; }
775    /// get sections
776    const std::vector<AsmSection>& getSections() const
777    { return sections; }
778    // get first sections for rel spaces
779    const std::vector<Array<cxuint> >& getRelSpacesSections() const
780    { return relSpacesSections; }
781    /// get kernel map
782    const KernelMap& getKernelMap() const
783    { return kernelMap; }
784    /// get kernels
785    const std::vector<AsmKernel>& getKernels() const
786    { return kernels; }
787    /// get regvar map
788    const AsmRegVarMap& getRegVarMap() const
789    { return globalScope.regVarMap; }
790    /// add regvar
791    bool addRegVar(const CString& name, const AsmRegVar& var)
792    { return insertRegVarInScope(name, var).second; }
793    /// get regvar by name
794    bool getRegVar(const CString& name, const AsmRegVar*& regVar);
795   
796    /// get global scope
797    const AsmScope& getGlobalScope() const
798    { return globalScope; }
799   
800    /// returns true if symbol contains absolute value
801    bool isAbsoluteSymbol(const AsmSymbol& symbol) const;
802   
803    /// add initiali defsyms
804    void addInitialDefSym(const CString& symName, uint64_t value);
805   
806    /// get format handler
807    const AsmFormatHandler* getFormatHandler() const
808    { return formatHandler; }
809};
810
811inline void ISAAssembler::printWarning(const char* linePtr, const char* message)
812{ assembler.printWarning(linePtr, message); }
813
814inline void ISAAssembler::printError(const char* linePtr, const char* message)
815{ assembler.printError(linePtr, message); }
816
817inline void ISAAssembler::printWarningForRange(cxuint bits, uint64_t value,
818                   const AsmSourcePos& pos, cxbyte signess)
819{ assembler.printWarningForRange(bits, value, pos, signess); }
820
821inline void ISAAssembler::printWarning(const AsmSourcePos& sourcePos, const char* message)
822{ assembler.printWarning(sourcePos, message); }
823
824inline void ISAAssembler::printError(const AsmSourcePos& sourcePos, const char* message)
825{ assembler.printError(sourcePos, message); }
826
827inline void ISAAssembler::addCodeFlowEntry(cxuint sectionId, const AsmCodeFlowEntry& entry)
828{ assembler.sections[sectionId].addCodeFlowEntry(entry); }
829
830};
831
832#endif
Note: See TracBrowser for help on using the repository browser.