1 //===-- NVPTXAsmPrinter.h - NVPTX LLVM assembly writer --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains a printer that converts from our internal representation 11 // of machine-dependent LLVM code to NVPTX assembly language. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_LIB_TARGET_NVPTX_NVPTXASMPRINTER_H 16 #define LLVM_LIB_TARGET_NVPTX_NVPTXASMPRINTER_H 17 18 #include "NVPTX.h" 19 #include "NVPTXSubtarget.h" 20 #include "NVPTXTargetMachine.h" 21 #include "llvm/ADT/SmallString.h" 22 #include "llvm/ADT/StringExtras.h" 23 #include "llvm/CodeGen/AsmPrinter.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/MC/MCAsmInfo.h" 26 #include "llvm/MC/MCExpr.h" 27 #include "llvm/MC/MCSymbol.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Support/FormattedStream.h" 30 #include "llvm/Target/TargetMachine.h" 31 #include <fstream> 32 33 // The ptx syntax and format is very different from that usually seem in a .s 34 // file, 35 // therefore we are not able to use the MCAsmStreamer interface here. 36 // 37 // We are handcrafting the output method here. 38 // 39 // A better approach is to clone the MCAsmStreamer to a MCPTXAsmStreamer 40 // (subclass of MCStreamer). 41 42 namespace llvm { 43 44 class LineReader { 45 private: 46 unsigned theCurLine; 47 std::ifstream fstr; 48 char buff[512]; 49 std::string theFileName; 50 SmallVector<unsigned, 32> lineOffset; 51 public: 52 LineReader(std::string filename) { 53 theCurLine = 0; 54 fstr.open(filename.c_str()); 55 theFileName = filename; 56 } 57 std::string fileName() { return theFileName; } 58 ~LineReader() { fstr.close(); } 59 std::string readLine(unsigned line); 60 }; 61 62 class LLVM_LIBRARY_VISIBILITY NVPTXAsmPrinter : public AsmPrinter { 63 64 class AggBuffer { 65 // Used to buffer the emitted string for initializing global 66 // aggregates. 67 // 68 // Normally an aggregate (array, vector or structure) is emitted 69 // as a u8[]. However, if one element/field of the aggregate 70 // is a non-NULL address, then the aggregate is emitted as u32[] 71 // or u64[]. 72 // 73 // We first layout the aggregate in 'buffer' in bytes, except for 74 // those symbol addresses. For the i-th symbol address in the 75 //aggregate, its corresponding 4-byte or 8-byte elements in 'buffer' 76 // are filled with 0s. symbolPosInBuffer[i-1] records its position 77 // in 'buffer', and Symbols[i-1] records the Value*. 78 // 79 // Once we have this AggBuffer setup, we can choose how to print 80 // it out. 81 public: 82 unsigned numSymbols; // number of symbol addresses 83 84 private: 85 const unsigned size; // size of the buffer in bytes 86 std::vector<unsigned char> buffer; // the buffer 87 SmallVector<unsigned, 4> symbolPosInBuffer; 88 SmallVector<const Value *, 4> Symbols; 89 unsigned curpos; 90 raw_ostream &O; 91 NVPTXAsmPrinter &AP; 92 bool EmitGeneric; 93 94 public: 95 AggBuffer(unsigned _size, raw_ostream &_O, NVPTXAsmPrinter &_AP) 96 : size(_size), buffer(_size), O(_O), AP(_AP) { 97 curpos = 0; 98 numSymbols = 0; 99 EmitGeneric = AP.EmitGeneric; 100 } 101 unsigned addBytes(unsigned char *Ptr, int Num, int Bytes) { 102 assert((curpos + Num) <= size); 103 assert((curpos + Bytes) <= size); 104 for (int i = 0; i < Num; ++i) { 105 buffer[curpos] = Ptr[i]; 106 curpos++; 107 } 108 for (int i = Num; i < Bytes; ++i) { 109 buffer[curpos] = 0; 110 curpos++; 111 } 112 return curpos; 113 } 114 unsigned addZeros(int Num) { 115 assert((curpos + Num) <= size); 116 for (int i = 0; i < Num; ++i) { 117 buffer[curpos] = 0; 118 curpos++; 119 } 120 return curpos; 121 } 122 void addSymbol(const Value *GVar) { 123 symbolPosInBuffer.push_back(curpos); 124 Symbols.push_back(GVar); 125 numSymbols++; 126 } 127 void print() { 128 if (numSymbols == 0) { 129 // print out in bytes 130 for (unsigned i = 0; i < size; i++) { 131 if (i) 132 O << ", "; 133 O << (unsigned int) buffer[i]; 134 } 135 } else { 136 // print out in 4-bytes or 8-bytes 137 unsigned int pos = 0; 138 unsigned int nSym = 0; 139 unsigned int nextSymbolPos = symbolPosInBuffer[nSym]; 140 unsigned int nBytes = 4; 141 if (AP.nvptxSubtarget.is64Bit()) 142 nBytes = 8; 143 for (pos = 0; pos < size; pos += nBytes) { 144 if (pos) 145 O << ", "; 146 if (pos == nextSymbolPos) { 147 const Value *v = Symbols[nSym]; 148 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) { 149 MCSymbol *Name = AP.getSymbol(GVar); 150 PointerType *PTy = dyn_cast<PointerType>(GVar->getType()); 151 bool IsNonGenericPointer = false; 152 if (PTy && PTy->getAddressSpace() != 0) { 153 IsNonGenericPointer = true; 154 } 155 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) { 156 O << "generic("; 157 O << *Name; 158 O << ")"; 159 } else { 160 O << *Name; 161 } 162 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(v)) { 163 O << *AP.lowerConstant(Cexpr); 164 } else 165 llvm_unreachable("symbol type unknown"); 166 nSym++; 167 if (nSym >= numSymbols) 168 nextSymbolPos = size + 1; 169 else 170 nextSymbolPos = symbolPosInBuffer[nSym]; 171 } else if (nBytes == 4) 172 O << *(unsigned int *)(&buffer[pos]); 173 else 174 O << *(unsigned long long *)(&buffer[pos]); 175 } 176 } 177 } 178 }; 179 180 friend class AggBuffer; 181 182 void emitSrcInText(StringRef filename, unsigned line); 183 184 private: 185 const char *getPassName() const override { return "NVPTX Assembly Printer"; } 186 187 const Function *F; 188 std::string CurrentFnName; 189 190 void EmitFunctionEntryLabel() override; 191 void EmitFunctionBodyStart() override; 192 void EmitFunctionBodyEnd() override; 193 void emitImplicitDef(const MachineInstr *MI) const override; 194 195 void EmitInstruction(const MachineInstr *) override; 196 void lowerToMCInst(const MachineInstr *MI, MCInst &OutMI); 197 bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp); 198 MCOperand GetSymbolRef(const MCSymbol *Symbol); 199 unsigned encodeVirtualRegister(unsigned Reg); 200 201 void EmitAlignment(unsigned NumBits, const GlobalValue *GV = nullptr) const {} 202 203 void printVecModifiedImmediate(const MachineOperand &MO, const char *Modifier, 204 raw_ostream &O); 205 void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O, 206 const char *Modifier = nullptr); 207 void printImplicitDef(const MachineInstr *MI, raw_ostream &O) const; 208 void printModuleLevelGV(const GlobalVariable *GVar, raw_ostream &O, 209 bool = false); 210 void printParamName(int paramIndex, raw_ostream &O); 211 void printParamName(Function::const_arg_iterator I, int paramIndex, 212 raw_ostream &O); 213 void emitGlobals(const Module &M); 214 void emitHeader(Module &M, raw_ostream &O); 215 void emitKernelFunctionDirectives(const Function &F, raw_ostream &O) const; 216 void emitVirtualRegister(unsigned int vr, raw_ostream &); 217 void emitFunctionExternParamList(const MachineFunction &MF); 218 void emitFunctionParamList(const Function *, raw_ostream &O); 219 void emitFunctionParamList(const MachineFunction &MF, raw_ostream &O); 220 void setAndEmitFunctionVirtualRegisters(const MachineFunction &MF); 221 void emitFunctionTempData(const MachineFunction &MF, unsigned &FrameSize); 222 bool isImageType(const Type *Ty); 223 void printReturnValStr(const Function *, raw_ostream &O); 224 void printReturnValStr(const MachineFunction &MF, raw_ostream &O); 225 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 226 unsigned AsmVariant, const char *ExtraCode, 227 raw_ostream &) override; 228 void printOperand(const MachineInstr *MI, int opNum, raw_ostream &O, 229 const char *Modifier = nullptr); 230 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 231 unsigned AsmVariant, const char *ExtraCode, 232 raw_ostream &) override; 233 protected: 234 bool doInitialization(Module &M) override; 235 bool doFinalization(Module &M) override; 236 237 private: 238 std::string CurrentBankselLabelInBasicBlock; 239 240 bool GlobalsEmitted; 241 242 // This is specific per MachineFunction. 243 const MachineRegisterInfo *MRI; 244 // The contents are specific for each 245 // MachineFunction. But the size of the 246 // array is not. 247 typedef DenseMap<unsigned, unsigned> VRegMap; 248 typedef DenseMap<const TargetRegisterClass *, VRegMap> VRegRCMap; 249 VRegRCMap VRegMapping; 250 // cache the subtarget here. 251 const NVPTXSubtarget &nvptxSubtarget; 252 // Build the map between type name and ID based on module's type 253 // symbol table. 254 std::map<const Type *, std::string> TypeNameMap; 255 256 // List of variables demoted to a function scope. 257 std::map<const Function *, std::vector<const GlobalVariable *> > localDecls; 258 259 // To record filename to ID mapping 260 std::map<std::string, unsigned> filenameMap; 261 void recordAndEmitFilenames(Module &); 262 263 void emitPTXGlobalVariable(const GlobalVariable *GVar, raw_ostream &O); 264 void emitPTXAddressSpace(unsigned int AddressSpace, raw_ostream &O) const; 265 std::string getPTXFundamentalTypeStr(const Type *Ty, bool = true) const; 266 void printScalarConstant(const Constant *CPV, raw_ostream &O); 267 void printFPConstant(const ConstantFP *Fp, raw_ostream &O); 268 void bufferLEByte(const Constant *CPV, int Bytes, AggBuffer *aggBuffer); 269 void bufferAggregateConstant(const Constant *CV, AggBuffer *aggBuffer); 270 271 void printOperandProper(const MachineOperand &MO); 272 273 void emitLinkageDirective(const GlobalValue *V, raw_ostream &O); 274 void emitDeclarations(const Module &, raw_ostream &O); 275 void emitDeclaration(const Function *, raw_ostream &O); 276 277 static const char *getRegisterName(unsigned RegNo); 278 void emitDemotedVars(const Function *, raw_ostream &); 279 280 bool lowerImageHandleOperand(const MachineInstr *MI, unsigned OpNo, 281 MCOperand &MCOp); 282 void lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp); 283 284 LineReader *reader; 285 LineReader *getReader(std::string); 286 287 // Used to control the need to emit .generic() in the initializer of 288 // module scope variables. 289 // Although ptx supports the hybrid mode like the following, 290 // .global .u32 a; 291 // .global .u32 b; 292 // .global .u32 addr[] = {a, generic(b)} 293 // we have difficulty representing the difference in the NVVM IR. 294 // 295 // Since the address value should always be generic in CUDA C and always 296 // be specific in OpenCL, we use this simple control here. 297 // 298 bool EmitGeneric; 299 300 public: 301 NVPTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer) 302 : AsmPrinter(TM, Streamer), 303 nvptxSubtarget(TM.getSubtarget<NVPTXSubtarget>()) { 304 CurrentBankselLabelInBasicBlock = ""; 305 reader = nullptr; 306 EmitGeneric = (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA); 307 } 308 309 ~NVPTXAsmPrinter() { 310 if (!reader) 311 delete reader; 312 } 313 314 bool ignoreLoc(const MachineInstr &); 315 316 std::string getVirtualRegisterName(unsigned) const; 317 318 DebugLoc prevDebugLoc; 319 void emitLineNumberAsDotLoc(const MachineInstr &); 320 }; 321 } // end of namespace 322 323 #endif 324