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

Last change on this file since 4089 was 4089, checked in by matszpk, 12 months ago

CLRadeonExtender: AsmRegAlloc?: revert changes in Assembler.h. Add TODO about handling livenesses between routine's calls.

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