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