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

Last change on this file since 3630 was 3630, checked in by matszpk, 3 years ago

CLRadeonExtender: Asm: Add preliminary code of AsmForInputFilter?. Fixed old stupid bug of error handling when makeSymbolSnapshot called.

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