1 //===-- NVPTXAsmPrinter.h - NVPTX LLVM assembly writer ----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_LIB_TARGET_NVPTX_NVPTXASMPRINTER_H
16 #define LLVM_LIB_TARGET_NVPTX_NVPTXASMPRINTER_H
19 #include "NVPTXSubtarget.h"
20 #include "NVPTXTargetMachine.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/CodeGen/AsmPrinter.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DebugLoc.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/MC/MCExpr.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/PassAnalysisSupport.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetMachine.h"
50 // The ptx syntax and format is very different from that usually seem in a .s
52 // therefore we are not able to use the MCAsmStreamer interface here.
54 // We are handcrafting the output method here.
56 // A better approach is to clone the MCAsmStreamer to a MCPTXAsmStreamer
57 // (subclass of MCStreamer).
68 std::string theFileName;
69 SmallVector<unsigned, 32> lineOffset;
72 LineReader(std::string filename) {
74 fstr.open(filename.c_str());
75 theFileName = filename;
78 ~LineReader() { fstr.close(); }
80 std::string fileName() { return theFileName; }
81 std::string readLine(unsigned line);
84 class LLVM_LIBRARY_VISIBILITY NVPTXAsmPrinter : public AsmPrinter {
87 // Used to buffer the emitted string for initializing global
90 // Normally an aggregate (array, vector or structure) is emitted
91 // as a u8[]. However, if one element/field of the aggregate
92 // is a non-NULL address, then the aggregate is emitted as u32[]
95 // We first layout the aggregate in 'buffer' in bytes, except for
96 // those symbol addresses. For the i-th symbol address in the
97 //aggregate, its corresponding 4-byte or 8-byte elements in 'buffer'
98 // are filled with 0s. symbolPosInBuffer[i-1] records its position
99 // in 'buffer', and Symbols[i-1] records the Value*.
101 // Once we have this AggBuffer setup, we can choose how to print
104 unsigned numSymbols; // number of symbol addresses
107 const unsigned size; // size of the buffer in bytes
108 std::vector<unsigned char> buffer; // the buffer
109 SmallVector<unsigned, 4> symbolPosInBuffer;
110 SmallVector<const Value *, 4> Symbols;
111 // SymbolsBeforeStripping[i] is the original form of Symbols[i] before
112 // stripping pointer casts, i.e.,
113 // Symbols[i] == SymbolsBeforeStripping[i]->stripPointerCasts().
115 // We need to keep these values because AggBuffer::print decides whether to
116 // emit a "generic()" cast for Symbols[i] depending on the address space of
117 // SymbolsBeforeStripping[i].
118 SmallVector<const Value *, 4> SymbolsBeforeStripping;
125 AggBuffer(unsigned size, raw_ostream &O, NVPTXAsmPrinter &AP)
126 : size(size), buffer(size), O(O), AP(AP) {
129 EmitGeneric = AP.EmitGeneric;
132 unsigned addBytes(unsigned char *Ptr, int Num, int Bytes) {
133 assert((curpos + Num) <= size);
134 assert((curpos + Bytes) <= size);
135 for (int i = 0; i < Num; ++i) {
136 buffer[curpos] = Ptr[i];
139 for (int i = Num; i < Bytes; ++i) {
146 unsigned addZeros(int Num) {
147 assert((curpos + Num) <= size);
148 for (int i = 0; i < Num; ++i) {
155 void addSymbol(const Value *GVar, const Value *GVarBeforeStripping) {
156 symbolPosInBuffer.push_back(curpos);
157 Symbols.push_back(GVar);
158 SymbolsBeforeStripping.push_back(GVarBeforeStripping);
163 if (numSymbols == 0) {
164 // print out in bytes
165 for (unsigned i = 0; i < size; i++) {
168 O << (unsigned int) buffer[i];
171 // print out in 4-bytes or 8-bytes
172 unsigned int pos = 0;
173 unsigned int nSym = 0;
174 unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
175 unsigned int nBytes = 4;
176 if (static_cast<const NVPTXTargetMachine &>(AP.TM).is64Bit())
178 for (pos = 0; pos < size; pos += nBytes) {
181 if (pos == nextSymbolPos) {
182 const Value *v = Symbols[nSym];
183 const Value *v0 = SymbolsBeforeStripping[nSym];
184 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
185 MCSymbol *Name = AP.getSymbol(GVar);
186 PointerType *PTy = dyn_cast<PointerType>(v0->getType());
187 bool IsNonGenericPointer = false; // Is v0 a non-generic pointer?
188 if (PTy && PTy->getAddressSpace() != 0) {
189 IsNonGenericPointer = true;
191 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
193 Name->print(O, AP.MAI);
196 Name->print(O, AP.MAI);
198 } else if (const ConstantExpr *CExpr = dyn_cast<ConstantExpr>(v0)) {
200 AP.lowerConstantForGV(cast<Constant>(CExpr), false);
201 AP.printMCExpr(*Expr, O);
203 llvm_unreachable("symbol type unknown");
205 if (nSym >= numSymbols)
206 nextSymbolPos = size + 1;
208 nextSymbolPos = symbolPosInBuffer[nSym];
209 } else if (nBytes == 4)
210 O << *(unsigned int *)(&buffer[pos]);
212 O << *(unsigned long long *)(&buffer[pos]);
218 friend class AggBuffer;
220 void emitSrcInText(StringRef filename, unsigned line);
223 StringRef getPassName() const override { return "NVPTX Assembly Printer"; }
226 std::string CurrentFnName;
228 void EmitBasicBlockStart(const MachineBasicBlock &MBB) const override;
229 void EmitFunctionEntryLabel() override;
230 void EmitFunctionBodyStart() override;
231 void EmitFunctionBodyEnd() override;
232 void emitImplicitDef(const MachineInstr *MI) const override;
234 void EmitInstruction(const MachineInstr *) override;
235 void lowerToMCInst(const MachineInstr *MI, MCInst &OutMI);
236 bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp);
237 MCOperand GetSymbolRef(const MCSymbol *Symbol);
238 unsigned encodeVirtualRegister(unsigned Reg);
240 void printVecModifiedImmediate(const MachineOperand &MO, const char *Modifier,
242 void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
243 const char *Modifier = nullptr);
244 void printModuleLevelGV(const GlobalVariable *GVar, raw_ostream &O,
246 void printParamName(Function::const_arg_iterator I, int paramIndex,
248 void emitGlobals(const Module &M);
249 void emitHeader(Module &M, raw_ostream &O, const NVPTXSubtarget &STI);
250 void emitKernelFunctionDirectives(const Function &F, raw_ostream &O) const;
251 void emitVirtualRegister(unsigned int vr, raw_ostream &);
252 void emitFunctionParamList(const Function *, raw_ostream &O);
253 void emitFunctionParamList(const MachineFunction &MF, raw_ostream &O);
254 void setAndEmitFunctionVirtualRegisters(const MachineFunction &MF);
255 void printReturnValStr(const Function *, raw_ostream &O);
256 void printReturnValStr(const MachineFunction &MF, raw_ostream &O);
257 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
258 unsigned AsmVariant, const char *ExtraCode,
259 raw_ostream &) override;
260 void printOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
261 const char *Modifier = nullptr);
262 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
263 unsigned AsmVariant, const char *ExtraCode,
264 raw_ostream &) override;
266 const MCExpr *lowerConstantForGV(const Constant *CV, bool ProcessingGeneric);
267 void printMCExpr(const MCExpr &Expr, raw_ostream &OS);
270 bool doInitialization(Module &M) override;
271 bool doFinalization(Module &M) override;
274 std::string CurrentBankselLabelInBasicBlock;
278 // This is specific per MachineFunction.
279 const MachineRegisterInfo *MRI;
280 // The contents are specific for each
281 // MachineFunction. But the size of the
283 typedef DenseMap<unsigned, unsigned> VRegMap;
284 typedef DenseMap<const TargetRegisterClass *, VRegMap> VRegRCMap;
285 VRegRCMap VRegMapping;
287 // Cache the subtarget here.
288 const NVPTXSubtarget *nvptxSubtarget;
290 // Build the map between type name and ID based on module's type
292 std::map<Type *, std::string> TypeNameMap;
294 // List of variables demoted to a function scope.
295 std::map<const Function *, std::vector<const GlobalVariable *>> localDecls;
297 // To record filename to ID mapping
298 std::map<std::string, unsigned> filenameMap;
299 void recordAndEmitFilenames(Module &);
301 void emitPTXGlobalVariable(const GlobalVariable *GVar, raw_ostream &O);
302 void emitPTXAddressSpace(unsigned int AddressSpace, raw_ostream &O) const;
303 std::string getPTXFundamentalTypeStr(Type *Ty, bool = true) const;
304 void printScalarConstant(const Constant *CPV, raw_ostream &O);
305 void printFPConstant(const ConstantFP *Fp, raw_ostream &O);
306 void bufferLEByte(const Constant *CPV, int Bytes, AggBuffer *aggBuffer);
307 void bufferAggregateConstant(const Constant *CV, AggBuffer *aggBuffer);
309 void emitLinkageDirective(const GlobalValue *V, raw_ostream &O);
310 void emitDeclarations(const Module &, raw_ostream &O);
311 void emitDeclaration(const Function *, raw_ostream &O);
312 void emitDemotedVars(const Function *, raw_ostream &);
314 bool lowerImageHandleOperand(const MachineInstr *MI, unsigned OpNo,
316 void lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp);
318 bool isLoopHeaderOfNoUnroll(const MachineBasicBlock &MBB) const;
320 LineReader *reader = nullptr;
322 LineReader *getReader(const std::string &);
324 // Used to control the need to emit .generic() in the initializer of
325 // module scope variables.
326 // Although ptx supports the hybrid mode like the following,
329 // .global .u32 addr[] = {a, generic(b)}
330 // we have difficulty representing the difference in the NVVM IR.
332 // Since the address value should always be generic in CUDA C and always
333 // be specific in OpenCL, we use this simple control here.
338 NVPTXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
339 : AsmPrinter(TM, std::move(Streamer)),
340 EmitGeneric(static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() ==
343 ~NVPTXAsmPrinter() override {
347 bool runOnMachineFunction(MachineFunction &F) override {
348 nvptxSubtarget = &F.getSubtarget<NVPTXSubtarget>();
349 return AsmPrinter::runOnMachineFunction(F);
352 void getAnalysisUsage(AnalysisUsage &AU) const override {
353 AU.addRequired<MachineLoopInfo>();
354 AsmPrinter::getAnalysisUsage(AU);
357 bool ignoreLoc(const MachineInstr &);
359 std::string getVirtualRegisterName(unsigned) const;
361 DebugLoc prevDebugLoc;
362 void emitLineNumberAsDotLoc(const MachineInstr &);
365 } // end namespace llvm
367 #endif // LLVM_LIB_TARGET_NVPTX_NVPTXASMPRINTER_H