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

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

CLRadeonExtender: Asm: First stuff to handle section differences (untested and not working).

File size: 29.9 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::vector<Array<cxuint> > relSpacesSections;
446    std::unordered_set<AsmSymbolEntry*> symbolSnapshots;
447    std::vector<AsmRelocation> relocations;
448    AsmScope globalScope;
449    AsmMacroMap macroMap;
450    std::stack<AsmScope*> scopeStack;
451    std::vector<AsmScope*> abandonedScopes;
452    AsmScope* currentScope;
453    KernelMap kernelMap;
454    std::vector<AsmKernel> kernels;
455    /// register variables
456    Flags flags;
457    uint64_t macroCount;
458    uint64_t localCount; // macro's local count
459    bool alternateMacro;
460    bool buggyFPLit;
461    bool macroCase;
462    bool oldModParam;
463   
464    cxuint inclusionLevel;
465    cxuint macroSubstLevel;
466    cxuint repetitionLevel;
467    bool lineAlreadyRead; // if line already read
468   
469    size_t lineSize;
470    const char* line;
471    bool endOfAssembly;
472    bool sectionDiffsPrepared;
473   
474    cxuint filenameIndex;
475    std::stack<AsmInputFilter*> asmInputFilters;
476    AsmInputFilter* currentInputFilter;
477   
478    std::ostream& messageStream;
479    std::ostream& printStream;
480   
481    AsmFormatHandler* formatHandler;
482   
483    std::stack<AsmClause> clauses;
484   
485    cxuint currentKernel;
486    cxuint& currentSection;
487    uint64_t& currentOutPos;
488   
489    AsmSourcePos getSourcePos(LineCol lineCol) const
490    {
491        return { currentInputFilter->getMacroSubst(), currentInputFilter->getSource(),
492            lineCol.lineNo, lineCol.colNo };
493    }
494   
495    AsmSourcePos getSourcePos(size_t pos) const
496    { return currentInputFilter->getSourcePos(pos); }
497    AsmSourcePos getSourcePos(const char* linePtr) const
498    { return getSourcePos(linePtr-line); }
499   
500    void printWarning(const AsmSourcePos& pos, const char* message);
501    void printError(const AsmSourcePos& pos, const char* message);
502   
503    void printWarning(const char* linePtr, const char* message)
504    { printWarning(getSourcePos(linePtr), message); }
505    void printError(const char* linePtr, const char* message)
506    { printError(getSourcePos(linePtr), message); }
507   
508    void printWarning(LineCol lineCol, const char* message)
509    { printWarning(getSourcePos(lineCol), message); }
510    void printError(LineCol lineCol, const char* message)
511    { printError(getSourcePos(lineCol), message); }
512   
513    LineCol translatePos(const char* linePtr) const
514    { return currentInputFilter->translatePos(linePtr-line); }
515    LineCol translatePos(size_t pos) const
516    { return currentInputFilter->translatePos(pos); }
517   
518    bool parseLiteral(uint64_t& value, const char*& linePtr);
519    bool parseLiteralNoError(uint64_t& value, const char*& linePtr);
520    bool parseString(std::string& outString, const char*& linePtr);
521   
522    enum class ParseState
523    {
524        FAILED = 0,
525        PARSED,
526        MISSING // missing element
527    };
528   
529    /** parse symbol
530     * \return state
531     */
532    ParseState parseSymbol(const char*& linePtr, AsmSymbolEntry*& entry,
533                   bool localLabel = true, bool dontCreateSymbol = false);
534    bool skipSymbol(const char*& linePtr);
535   
536    bool setSymbol(AsmSymbolEntry& symEntry, uint64_t value, cxuint sectionId);
537   
538    bool assignSymbol(const CString& symbolName, const char* symbolPlace,
539                  const char* linePtr, bool reassign = true, bool baseExpr = false);
540   
541    bool assignOutputCounter(const char* symbolPlace, uint64_t value, cxuint sectionId,
542                     cxbyte fillValue = 0);
543   
544    void parsePseudoOps(const CString& firstName, const char* stmtPlace,
545                const char* linePtr);
546   
547    /// exitm - exit macro mode
548    bool skipClauses(bool exitm = false);
549    bool putMacroContent(RefPtr<AsmMacro> macro);
550    bool putRepetitionContent(AsmRepeat& repeat);
551   
552    void initializeOutputFormat();
553   
554    bool pushClause(const char* string, AsmClauseType clauseType)
555    {
556        bool included; // to ignore
557        return pushClause(string, clauseType, true, included);
558    }
559    bool pushClause(const char* string, AsmClauseType clauseType,
560                  bool satisfied, bool& included);
561     // return false when failed (for example no clauses)
562    bool popClause(const char* string, AsmClauseType clauseType);
563   
564    // recursive function to find scope in scope
565    AsmScope* findScopeInScope(AsmScope* scope, const CString& scopeName,
566                    std::unordered_set<AsmScope*>& scopeSet);
567    // find scope by identifier
568    AsmScope* getRecurScope(const CString& scopePlace, bool ignoreLast = false,
569                    const char** lastStep = nullptr);
570    // find symbol in scopes
571    // internal recursive function to find symbol in scope
572    AsmSymbolEntry* findSymbolInScopeInt(AsmScope* scope, const CString& symName,
573                    std::unordered_set<AsmScope*>& scopeSet);
574    // scope - return scope from scoped name
575    AsmSymbolEntry* findSymbolInScope(const CString& symName, AsmScope*& scope,
576                      CString& sameSymName, bool insertMode = false);
577    // similar to map::insert, but returns pointer
578    std::pair<AsmSymbolEntry*, bool> insertSymbolInScope(const CString& symName,
579                 const AsmSymbol& symbol);
580   
581    // internal recursive function to find symbol in scope
582    AsmRegVarEntry* findRegVarInScopeInt(AsmScope* scope, const CString& rvName,
583                    std::unordered_set<AsmScope*>& scopeSet);
584    // scope - return scope from scoped name
585    AsmRegVarEntry* findRegVarInScope(const CString& rvName, AsmScope*& scope,
586                      CString& sameRvName, bool insertMode = false);
587    // similar to map::insert, but returns pointer
588    std::pair<AsmRegVarEntry*, bool> insertRegVarInScope(const CString& rvName,
589                 const AsmRegVar& regVar);
590   
591    // create scope
592    bool getScope(AsmScope* parent, const CString& scopeName, AsmScope*& scope);
593    // push new scope level
594    bool pushScope(const CString& scopeName);
595    bool popScope();
596   
597    /// returns false when includeLevel is too deep, throw error if failed a file opening
598    bool includeFile(const char* pseudoOpPlace, const std::string& filename);
599   
600    ParseState makeMacroSubstitution(const char* string);
601   
602    bool parseMacroArgValue(const char*& linePtr, std::string& outStr);
603   
604    void putData(size_t size, const cxbyte* data)
605    {
606        AsmSection& section = sections[currentSection];
607        section.content.insert(section.content.end(), data, data+size);
608        currentOutPos += size;
609    }
610   
611    cxbyte* reserveData(size_t size, cxbyte fillValue = 0);
612   
613    void goToMain(const char* pseudoOpPlace);
614    void goToKernel(const char* pseudoOpPlace, const char* kernelName);
615    void goToSection(const char* pseudoOpPlace, const char* sectionName, uint64_t align=0);
616    void goToSection(const char* pseudoOpPlace, const char* sectionName,
617                     AsmSectionType type, Flags flags, uint64_t align=0);
618    void goToSection(const char* pseudoOpPlace, cxuint sectionId, uint64_t align=0);
619   
620    void printWarningForRange(cxuint bits, uint64_t value, const AsmSourcePos& pos,
621                  cxbyte signess = WS_BOTH);
622   
623    bool isAddressableSection() const
624    {
625        return currentSection==ASMSECT_ABS ||
626                    (sections[currentSection].flags & ASMSECT_ADDRESSABLE) != 0;
627    }
628    bool isWriteableSection() const
629    {
630        return currentSection!=ASMSECT_ABS &&
631                (sections[currentSection].flags & ASMSECT_WRITEABLE) != 0;
632    }
633    bool isResolvableSection() const
634    {
635        return currentSection==ASMSECT_ABS ||
636                (sections[currentSection].flags & ASMSECT_UNRESOLVABLE) == 0;
637    }
638    bool isResolvableSection(cxuint sectionId) const
639    {
640        return sectionId==ASMSECT_ABS ||
641                (sections[sectionId].flags & ASMSECT_UNRESOLVABLE) == 0;
642    }
643   
644    // oldKernels and newKernels must be sorted
645    void handleRegionsOnKernels(const std::vector<cxuint>& newKernels,
646                const std::vector<cxuint>& oldKernels, cxuint codeSection);
647   
648    void tryToResolveSymbols(AsmScope* scope);
649    void printUnresolvedSymbols(AsmScope* scope);
650   
651protected:
652    /// helper for testing
653    bool readLine();
654public:
655    /// constructor with filename and input stream
656    /**
657     * \param filename filename
658     * \param input input stream
659     * \param flags assembler flags
660     * \param format output format type
661     * \param deviceType GPU device type
662     * \param msgStream stream for warnings and errors
663     * \param printStream stream for printing message by .print pseudo-ops
664     */
665    explicit Assembler(const CString& filename, std::istream& input, Flags flags = 0,
666              BinaryFormat format = BinaryFormat::AMD,
667              GPUDeviceType deviceType = GPUDeviceType::CAPE_VERDE,
668              std::ostream& msgStream = std::cerr, std::ostream& printStream = std::cout);
669   
670    /// constructor with filename and input stream
671    /**
672     * \param filenames filenames
673     * \param flags assembler flags
674     * \param format output format type
675     * \param deviceType GPU device type
676     * \param msgStream stream for warnings and errors
677     * \param printStream stream for printing message by .print pseudo-ops
678     */
679    explicit Assembler(const Array<CString>& filenames, Flags flags = 0,
680              BinaryFormat format = BinaryFormat::AMD,
681              GPUDeviceType deviceType = GPUDeviceType::CAPE_VERDE,
682              std::ostream& msgStream = std::cerr, std::ostream& printStream = std::cout);
683    /// destructor
684    ~Assembler();
685   
686    /// main routine to assemble code
687    bool assemble();
688   
689    /// write binary to file
690    void writeBinary(const char* filename) const;
691    /// write binary to stream
692    void writeBinary(std::ostream& outStream) const;
693    /// write binary to array
694    void writeBinary(Array<cxbyte>& array) const;
695   
696    /// get AMD driver version
697    uint32_t getDriverVersion() const
698    { return driverVersion; }
699    /// set AMD driver version
700    void setDriverVersion(uint32_t driverVersion)
701    { this->driverVersion = driverVersion; }
702   
703    /// get LLVM version
704    uint32_t getLLVMVersion() const
705    { return llvmVersion; }
706    /// set LLVM version
707    void setLLVMVersion(uint32_t llvmVersion)
708    { this->llvmVersion = llvmVersion; }
709   
710    /// get GPU device type
711    GPUDeviceType getDeviceType() const
712    { return deviceType; }
713    /// set GPU device type
714    void setDeviceType(const GPUDeviceType deviceType)
715    { this->deviceType = deviceType; }
716    /// get binary format
717    BinaryFormat getBinaryFormat() const
718    { return format; }
719    /// set binary format
720    void setBinaryFormat(BinaryFormat binFormat)
721    { format = binFormat; }
722    /// get bitness (true if 64-bit)
723    bool is64Bit() const
724    { return _64bit; }
725    /// set bitness (true if 64-bit)
726    void set64Bit(bool this64Bit)
727    {  _64bit = this64Bit; }
728    /// get flags
729    Flags getFlags() const
730    { return flags; }
731    /// set flags
732    void setFlags(Flags flags)
733    { this->flags = flags; }
734    /// get true if altMacro enabled
735    bool isAltMacro() const
736    { return alternateMacro; }
737    /// get true if macroCase enabled
738    bool isMacroCase() const
739    { return macroCase; }
740    /// get true if oldModParam enabled (old modifier parametrization)
741    bool isOldModParam() const
742    { return oldModParam; }
743    /// get true if buggyFPLit enabled
744    bool isBuggyFPLit() const
745    { return buggyFPLit; }
746    /// get include directory list
747    const std::vector<CString>& getIncludeDirs() const
748    { return includeDirs; }
749    /// adds include directory
750    void addIncludeDir(const CString& includeDir);
751    /// get symbols map
752    const AsmSymbolMap& getSymbolMap() const
753    { return globalScope.symbolMap; }
754    /// get sections
755    const std::vector<AsmSection>& getSections() const
756    { return sections; }
757    // get first sections for rel spaces
758    const std::vector<Array<cxuint> >& getRelSpacesSections() const
759    { return relSpacesSections; }
760    /// get kernel map
761    const KernelMap& getKernelMap() const
762    { return kernelMap; }
763    /// get kernels
764    const std::vector<AsmKernel>& getKernels() const
765    { return kernels; }
766    /// get regvar map
767    const AsmRegVarMap& getRegVarMap() const
768    { return globalScope.regVarMap; }
769    /// add regvar
770    bool addRegVar(const CString& name, const AsmRegVar& var)
771    { return insertRegVarInScope(name, var).second; }
772    /// get regvar by name
773    bool getRegVar(const CString& name, const AsmRegVar*& regVar);
774   
775    /// get global scope
776    const AsmScope& getGlobalScope() const
777    { return globalScope; }
778   
779    /// returns true if symbol contains absolute value
780    bool isAbsoluteSymbol(const AsmSymbol& symbol) const;
781   
782    /// add initiali defsyms
783    void addInitialDefSym(const CString& symName, uint64_t value);
784   
785    /// get format handler
786    const AsmFormatHandler* getFormatHandler() const
787    { return formatHandler; }
788};
789
790inline void ISAAssembler::printWarning(const char* linePtr, const char* message)
791{ assembler.printWarning(linePtr, message); }
792
793inline void ISAAssembler::printError(const char* linePtr, const char* message)
794{ assembler.printError(linePtr, message); }
795
796inline void ISAAssembler::printWarningForRange(cxuint bits, uint64_t value,
797                   const AsmSourcePos& pos, cxbyte signess)
798{ assembler.printWarningForRange(bits, value, pos, signess); }
799
800inline void ISAAssembler::printWarning(const AsmSourcePos& sourcePos, const char* message)
801{ assembler.printWarning(sourcePos, message); }
802
803inline void ISAAssembler::printError(const AsmSourcePos& sourcePos, const char* message)
804{ assembler.printError(sourcePos, message); }
805
806inline void ISAAssembler::addCodeFlowEntry(cxuint sectionId, const AsmCodeFlowEntry& entry)
807{ assembler.sections[sectionId].addCodeFlowEntry(entry); }
808
809};
810
811#endif
Note: See TracBrowser for help on using the repository browser.