blob: c46094569e92bbaa46e1da8b9df856a691497c00 [file] [log] [blame]
Justin Holewinski49683f32012-05-04 20:18:50 +00001//===-- NVPTXAsmPrinter.cpp - 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
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000015#include "NVPTXAsmPrinter.h"
Justin Holewinski49683f32012-05-04 20:18:50 +000016#include "NVPTX.h"
17#include "NVPTXInstrInfo.h"
18#include "NVPTXTargetMachine.h"
19#include "NVPTXRegisterInfo.h"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000020#include "NVPTXUtilities.h"
Justin Holewinski49683f32012-05-04 20:18:50 +000021#include "MCTargetDesc/NVPTXMCAsmInfo.h"
22#include "NVPTXNumRegisters.h"
Justin Holewinski49683f32012-05-04 20:18:50 +000023#include "llvm/ADT/StringExtras.h"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000024#include "llvm/DebugInfo.h"
Justin Holewinski49683f32012-05-04 20:18:50 +000025#include "llvm/Function.h"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000026#include "llvm/GlobalVariable.h"
Justin Holewinski49683f32012-05-04 20:18:50 +000027#include "llvm/Module.h"
28#include "llvm/CodeGen/Analysis.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineModuleInfo.h"
32#include "llvm/MC/MCStreamer.h"
33#include "llvm/MC/MCSymbol.h"
34#include "llvm/Target/Mangler.h"
35#include "llvm/Target/TargetLoweringObjectFile.h"
36#include "llvm/Support/TargetRegistry.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/FormattedStream.h"
39#include "llvm/DerivedTypes.h"
Justin Holewinski49683f32012-05-04 20:18:50 +000040#include "llvm/Support/TimeValue.h"
Justin Holewinski49683f32012-05-04 20:18:50 +000041#include "llvm/Support/CommandLine.h"
Justin Holewinski49683f32012-05-04 20:18:50 +000042#include "llvm/Analysis/ConstantFolding.h"
43#include "llvm/Support/Path.h"
44#include "llvm/Assembly/Writer.h"
45#include "cl_common_defines.h"
Bill Wendling0bcbd1d2012-06-28 00:05:13 +000046#include <sstream>
Justin Holewinski49683f32012-05-04 20:18:50 +000047using namespace llvm;
48
49
50#include "NVPTXGenAsmWriter.inc"
51
52bool RegAllocNilUsed = true;
53
54#define DEPOTNAME "__local_depot"
55
56static cl::opt<bool>
57EmitLineNumbers("nvptx-emit-line-numbers",
58 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
59 cl::init(true));
60
61namespace llvm {
62bool InterleaveSrcInPtx = false;
63}
64
65static cl::opt<bool, true>InterleaveSrc("nvptx-emit-src",
66 cl::ZeroOrMore,
67 cl::desc("NVPTX Specific: Emit source line in ptx file"),
68 cl::location(llvm::InterleaveSrcInPtx));
69
70
71
72
73// @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
74// cannot just link to the existing version.
75/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
76///
77using namespace nvptx;
78const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
79 MCContext &Ctx = AP.OutContext;
80
81 if (CV->isNullValue() || isa<UndefValue>(CV))
82 return MCConstantExpr::Create(0, Ctx);
83
84 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
85 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
86
87 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
88 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
89
90 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
91 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
92
93 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
94 if (CE == 0)
95 llvm_unreachable("Unknown constant value to lower!");
96
97
98 switch (CE->getOpcode()) {
99 default:
100 // If the code isn't optimized, there may be outstanding folding
Micah Villmow3574eca2012-10-08 16:38:25 +0000101 // opportunities. Attempt to fold the expression using DataLayout as a
Justin Holewinski49683f32012-05-04 20:18:50 +0000102 // last resort before giving up.
103 if (Constant *C =
Micah Villmow3574eca2012-10-08 16:38:25 +0000104 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
Justin Holewinski49683f32012-05-04 20:18:50 +0000105 if (C != CE)
106 return LowerConstant(C, AP);
107
108 // Otherwise report the problem to the user.
109 {
110 std::string S;
111 raw_string_ostream OS(S);
112 OS << "Unsupported expression in static initializer: ";
113 WriteAsOperand(OS, CE, /*PrintType=*/false,
114 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
115 report_fatal_error(OS.str());
116 }
117 case Instruction::GetElementPtr: {
Micah Villmow3574eca2012-10-08 16:38:25 +0000118 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinski49683f32012-05-04 20:18:50 +0000119 // Generate a symbolic expression for the byte address
120 const Constant *PtrVal = CE->getOperand(0);
121 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
122 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
123
124 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
125 if (Offset == 0)
126 return Base;
127
128 // Truncate/sext the offset to the pointer size.
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000129 unsigned AS = PtrVal->getType()->isPointerTy() ?
130 cast<PointerType>(PtrVal->getType())->getAddressSpace() : 0;
131 if (TD.getPointerSizeInBits(AS) != 64) {
132 int SExtAmount = 64-TD.getPointerSizeInBits(AS);
Justin Holewinski49683f32012-05-04 20:18:50 +0000133 Offset = (Offset << SExtAmount) >> SExtAmount;
134 }
135
136 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
137 Ctx);
138 }
139
140 case Instruction::Trunc:
141 // We emit the value and depend on the assembler to truncate the generated
142 // expression properly. This is important for differences between
143 // blockaddress labels. Since the two labels are in the same function, it
144 // is reasonable to treat their delta as a 32-bit value.
145 // FALL THROUGH.
146 case Instruction::BitCast:
147 return LowerConstant(CE->getOperand(0), AP);
148
149 case Instruction::IntToPtr: {
Micah Villmow3574eca2012-10-08 16:38:25 +0000150 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinski49683f32012-05-04 20:18:50 +0000151 // Handle casts to pointers by changing them into casts to the appropriate
152 // integer type. This promotes constant folding and simplifies this code.
153 Constant *Op = CE->getOperand(0);
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000154 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
Justin Holewinski49683f32012-05-04 20:18:50 +0000155 false/*ZExt*/);
156 return LowerConstant(Op, AP);
157 }
158
159 case Instruction::PtrToInt: {
Micah Villmow3574eca2012-10-08 16:38:25 +0000160 const DataLayout &TD = *AP.TM.getDataLayout();
Justin Holewinski49683f32012-05-04 20:18:50 +0000161 // Support only foldable casts to/from pointers that can be eliminated by
162 // changing the pointer to the appropriately sized integer type.
163 Constant *Op = CE->getOperand(0);
164 Type *Ty = CE->getType();
165
166 const MCExpr *OpExpr = LowerConstant(Op, AP);
167
168 // We can emit the pointer value into this slot if the slot is an
169 // integer slot equal to the size of the pointer.
170 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
171 return OpExpr;
172
173 // Otherwise the pointer is smaller than the resultant integer, mask off
174 // the high bits so we are sure to get a proper truncation if the input is
175 // a constant expr.
176 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
177 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
178 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
179 }
180
181 // The MC library also has a right-shift operator, but it isn't consistently
182 // signed or unsigned between different targets.
183 case Instruction::Add:
184 case Instruction::Sub:
185 case Instruction::Mul:
186 case Instruction::SDiv:
187 case Instruction::SRem:
188 case Instruction::Shl:
189 case Instruction::And:
190 case Instruction::Or:
191 case Instruction::Xor: {
192 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
193 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
194 switch (CE->getOpcode()) {
195 default: llvm_unreachable("Unknown binary operator constant cast expr");
196 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
197 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
198 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
199 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
200 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
201 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
202 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
203 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
204 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
205 }
206 }
207 }
208}
209
210
211void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI)
212{
213 if (!EmitLineNumbers)
214 return;
215 if (ignoreLoc(MI))
216 return;
217
218 DebugLoc curLoc = MI.getDebugLoc();
219
220 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
221 return;
222
223 if (prevDebugLoc == curLoc)
224 return;
225
226 prevDebugLoc = curLoc;
227
228 if (curLoc.isUnknown())
229 return;
230
231
232 const MachineFunction *MF = MI.getParent()->getParent();
233 //const TargetMachine &TM = MF->getTarget();
234
235 const LLVMContext &ctx = MF->getFunction()->getContext();
236 DIScope Scope(curLoc.getScope(ctx));
237
238 if (!Scope.Verify())
239 return;
240
241 StringRef fileName(Scope.getFilename());
242 StringRef dirName(Scope.getDirectory());
243 SmallString<128> FullPathName = dirName;
244 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
245 sys::path::append(FullPathName, fileName);
246 fileName = FullPathName.str();
247 }
248
249 if (filenameMap.find(fileName.str()) == filenameMap.end())
250 return;
251
252
253 // Emit the line from the source file.
254 if (llvm::InterleaveSrcInPtx)
255 this->emitSrcInText(fileName.str(), curLoc.getLine());
256
257 std::stringstream temp;
258 temp << "\t.loc " << filenameMap[fileName.str()]
259 << " " << curLoc.getLine() << " " << curLoc.getCol();
260 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
261}
262
263void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
264 SmallString<128> Str;
265 raw_svector_ostream OS(Str);
266 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
267 emitLineNumberAsDotLoc(*MI);
268 printInstruction(MI, OS);
269 OutStreamer.EmitRawText(OS.str());
270}
271
272void NVPTXAsmPrinter::printReturnValStr(const Function *F,
273 raw_ostream &O)
274{
Micah Villmow3574eca2012-10-08 16:38:25 +0000275 const DataLayout *TD = TM.getDataLayout();
Justin Holewinski49683f32012-05-04 20:18:50 +0000276 const TargetLowering *TLI = TM.getTargetLowering();
277
278 Type *Ty = F->getReturnType();
279
280 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
281
282 if (Ty->getTypeID() == Type::VoidTyID)
283 return;
284
285 O << " (";
286
287 if (isABI) {
288 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
289 unsigned size = 0;
290 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
291 size = ITy->getBitWidth();
292 if (size < 32) size = 32;
293 } else {
294 assert(Ty->isFloatingPointTy() &&
295 "Floating point type expected here");
296 size = Ty->getPrimitiveSizeInBits();
297 }
298
299 O << ".param .b" << size << " func_retval0";
300 }
301 else if (isa<PointerType>(Ty)) {
302 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
303 << " func_retval0";
304 } else {
305 if ((Ty->getTypeID() == Type::StructTyID) ||
306 isa<VectorType>(Ty)) {
307 SmallVector<EVT, 16> vtparts;
308 ComputeValueVTs(*TLI, Ty, vtparts);
309 unsigned totalsz = 0;
310 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
311 unsigned elems = 1;
312 EVT elemtype = vtparts[i];
313 if (vtparts[i].isVector()) {
314 elems = vtparts[i].getVectorNumElements();
315 elemtype = vtparts[i].getVectorElementType();
316 }
317 for (unsigned j=0, je=elems; j!=je; ++j) {
318 unsigned sz = elemtype.getSizeInBits();
319 if (elemtype.isInteger() && (sz < 8)) sz = 8;
320 totalsz += sz/8;
321 }
322 }
323 unsigned retAlignment = 0;
324 if (!llvm::getAlign(*F, 0, retAlignment))
325 retAlignment = TD->getABITypeAlignment(Ty);
326 O << ".param .align "
327 << retAlignment
328 << " .b8 func_retval0["
329 << totalsz << "]";
330 } else
331 assert(false &&
332 "Unknown return type");
333 }
334 } else {
335 SmallVector<EVT, 16> vtparts;
336 ComputeValueVTs(*TLI, Ty, vtparts);
337 unsigned idx = 0;
338 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
339 unsigned elems = 1;
340 EVT elemtype = vtparts[i];
341 if (vtparts[i].isVector()) {
342 elems = vtparts[i].getVectorNumElements();
343 elemtype = vtparts[i].getVectorElementType();
344 }
345
346 for (unsigned j=0, je=elems; j!=je; ++j) {
347 unsigned sz = elemtype.getSizeInBits();
348 if (elemtype.isInteger() && (sz < 32)) sz = 32;
349 O << ".reg .b" << sz << " func_retval" << idx;
350 if (j<je-1) O << ", ";
351 ++idx;
352 }
353 if (i < e-1)
354 O << ", ";
355 }
356 }
357 O << ") ";
358 return;
359}
360
361void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
362 raw_ostream &O) {
363 const Function *F = MF.getFunction();
364 printReturnValStr(F, O);
365}
366
367void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
368 SmallString<128> Str;
369 raw_svector_ostream O(Str);
370
371 // Set up
372 MRI = &MF->getRegInfo();
373 F = MF->getFunction();
374 emitLinkageDirective(F,O);
375 if (llvm::isKernelFunction(*F))
376 O << ".entry ";
377 else {
378 O << ".func ";
379 printReturnValStr(*MF, O);
380 }
381
382 O << *CurrentFnSym;
383
384 emitFunctionParamList(*MF, O);
385
386 if (llvm::isKernelFunction(*F))
387 emitKernelFunctionDirectives(*F, O);
388
389 OutStreamer.EmitRawText(O.str());
390
391 prevDebugLoc = DebugLoc();
392}
393
394void NVPTXAsmPrinter::EmitFunctionBodyStart() {
395 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
396 unsigned numRegClasses = TRI.getNumRegClasses();
397 VRidGlobal2LocalMap = new std::map<unsigned, unsigned>[numRegClasses+1];
398 OutStreamer.EmitRawText(StringRef("{\n"));
399 setAndEmitFunctionVirtualRegisters(*MF);
400
401 SmallString<128> Str;
402 raw_svector_ostream O(Str);
403 emitDemotedVars(MF->getFunction(), O);
404 OutStreamer.EmitRawText(O.str());
405}
406
407void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
408 OutStreamer.EmitRawText(StringRef("}\n"));
409 delete []VRidGlobal2LocalMap;
410}
411
412
413void
414NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function& F,
415 raw_ostream &O) const {
416 // If the NVVM IR has some of reqntid* specified, then output
417 // the reqntid directive, and set the unspecified ones to 1.
418 // If none of reqntid* is specified, don't output reqntid directive.
419 unsigned reqntidx, reqntidy, reqntidz;
420 bool specified = false;
421 if (llvm::getReqNTIDx(F, reqntidx) == false) reqntidx = 1;
422 else specified = true;
423 if (llvm::getReqNTIDy(F, reqntidy) == false) reqntidy = 1;
424 else specified = true;
425 if (llvm::getReqNTIDz(F, reqntidz) == false) reqntidz = 1;
426 else specified = true;
427
428 if (specified)
429 O << ".reqntid " << reqntidx << ", "
430 << reqntidy << ", " << reqntidz << "\n";
431
432 // If the NVVM IR has some of maxntid* specified, then output
433 // the maxntid directive, and set the unspecified ones to 1.
434 // If none of maxntid* is specified, don't output maxntid directive.
435 unsigned maxntidx, maxntidy, maxntidz;
436 specified = false;
437 if (llvm::getMaxNTIDx(F, maxntidx) == false) maxntidx = 1;
438 else specified = true;
439 if (llvm::getMaxNTIDy(F, maxntidy) == false) maxntidy = 1;
440 else specified = true;
441 if (llvm::getMaxNTIDz(F, maxntidz) == false) maxntidz = 1;
442 else specified = true;
443
444 if (specified)
445 O << ".maxntid " << maxntidx << ", "
446 << maxntidy << ", " << maxntidz << "\n";
447
448 unsigned mincta;
449 if (llvm::getMinCTASm(F, mincta))
450 O << ".minnctapersm " << mincta << "\n";
451}
452
453void
454NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
455 raw_ostream &O) {
456 const TargetRegisterClass * RC = MRI->getRegClass(vr);
457 unsigned id = RC->getID();
458
459 std::map<unsigned, unsigned> &regmap = VRidGlobal2LocalMap[id];
460 unsigned mapped_vr = regmap[vr];
461
462 if (!isVec) {
463 O << getNVPTXRegClassStr(RC) << mapped_vr;
464 return;
465 }
466 // Vector virtual register
467 if (getNVPTXVectorSize(RC) == 4)
468 O << "{"
469 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
470 << getNVPTXRegClassStr(RC) << mapped_vr << "_1, "
471 << getNVPTXRegClassStr(RC) << mapped_vr << "_2, "
472 << getNVPTXRegClassStr(RC) << mapped_vr << "_3"
473 << "}";
474 else if (getNVPTXVectorSize(RC) == 2)
475 O << "{"
476 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
477 << getNVPTXRegClassStr(RC) << mapped_vr << "_1"
478 << "}";
479 else
Craig Topper63663612012-05-24 07:02:50 +0000480 llvm_unreachable("Unsupported vector size");
Justin Holewinski49683f32012-05-04 20:18:50 +0000481}
482
483void
484NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
485 raw_ostream &O) {
486 getVirtualRegisterName(vr, isVec, O);
487}
488
489void NVPTXAsmPrinter::printVecModifiedImmediate(const MachineOperand &MO,
490 const char *Modifier,
491 raw_ostream &O) {
Craig Topper6fcf1292012-05-24 04:22:05 +0000492 static const char vecelem[] = {'0', '1', '2', '3', '0', '1', '2', '3'};
Justin Holewinski49683f32012-05-04 20:18:50 +0000493 int Imm = (int)MO.getImm();
494 if(0 == strcmp(Modifier, "vecelem"))
495 O << "_" << vecelem[Imm];
496 else if(0 == strcmp(Modifier, "vecv4comm1")) {
497 if((Imm < 0) || (Imm > 3))
498 O << "//";
499 }
500 else if(0 == strcmp(Modifier, "vecv4comm2")) {
501 if((Imm < 4) || (Imm > 7))
502 O << "//";
503 }
504 else if(0 == strcmp(Modifier, "vecv4pos")) {
505 if(Imm < 0) Imm = 0;
506 O << "_" << vecelem[Imm%4];
507 }
508 else if(0 == strcmp(Modifier, "vecv2comm1")) {
509 if((Imm < 0) || (Imm > 1))
510 O << "//";
511 }
512 else if(0 == strcmp(Modifier, "vecv2comm2")) {
513 if((Imm < 2) || (Imm > 3))
514 O << "//";
515 }
516 else if(0 == strcmp(Modifier, "vecv2pos")) {
517 if(Imm < 0) Imm = 0;
518 O << "_" << vecelem[Imm%2];
519 }
520 else
Craig Topper63663612012-05-24 07:02:50 +0000521 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinski49683f32012-05-04 20:18:50 +0000522}
523
524void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
525 raw_ostream &O, const char *Modifier) {
526 const MachineOperand &MO = MI->getOperand(opNum);
527 switch (MO.getType()) {
528 case MachineOperand::MO_Register:
529 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
530 if (MO.getReg() == NVPTX::VRDepot)
531 O << DEPOTNAME << getFunctionNumber();
532 else
533 O << getRegisterName(MO.getReg());
534 } else {
535 if (!Modifier)
536 emitVirtualRegister(MO.getReg(), false, O);
537 else {
538 if (strcmp(Modifier, "vecfull") == 0)
539 emitVirtualRegister(MO.getReg(), true, O);
540 else
Craig Topper63663612012-05-24 07:02:50 +0000541 llvm_unreachable(
Justin Holewinski49683f32012-05-04 20:18:50 +0000542 "Don't know how to handle the modifier on virtual register.");
543 }
544 }
545 return;
546
547 case MachineOperand::MO_Immediate:
548 if (!Modifier)
549 O << MO.getImm();
550 else if (strstr(Modifier, "vec") == Modifier)
551 printVecModifiedImmediate(MO, Modifier, O);
552 else
Craig Topper63663612012-05-24 07:02:50 +0000553 llvm_unreachable("Don't know how to handle modifier on immediate operand");
Justin Holewinski49683f32012-05-04 20:18:50 +0000554 return;
555
556 case MachineOperand::MO_FPImmediate:
557 printFPConstant(MO.getFPImm(), O);
558 break;
559
560 case MachineOperand::MO_GlobalAddress:
561 O << *Mang->getSymbol(MO.getGlobal());
562 break;
563
564 case MachineOperand::MO_ExternalSymbol: {
565 const char * symbname = MO.getSymbolName();
566 if (strstr(symbname, ".PARAM") == symbname) {
567 unsigned index;
568 sscanf(symbname+6, "%u[];", &index);
569 printParamName(index, O);
570 }
571 else if (strstr(symbname, ".HLPPARAM") == symbname) {
572 unsigned index;
573 sscanf(symbname+9, "%u[];", &index);
574 O << *CurrentFnSym << "_param_" << index << "_offset";
575 }
576 else
577 O << symbname;
578 break;
579 }
580
581 case MachineOperand::MO_MachineBasicBlock:
582 O << *MO.getMBB()->getSymbol();
583 return;
584
585 default:
Craig Topper63663612012-05-24 07:02:50 +0000586 llvm_unreachable("Operand type not supported.");
Justin Holewinski49683f32012-05-04 20:18:50 +0000587 }
588}
589
590void NVPTXAsmPrinter::
591printImplicitDef(const MachineInstr *MI, raw_ostream &O) const {
592#ifndef __OPTIMIZE__
593 O << "\t// Implicit def :";
594 //printOperand(MI, 0);
595 O << "\n";
596#endif
597}
598
599void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
600 raw_ostream &O, const char *Modifier) {
601 printOperand(MI, opNum, O);
602
603 if (Modifier && !strcmp(Modifier, "add")) {
604 O << ", ";
605 printOperand(MI, opNum+1, O);
606 } else {
607 if (MI->getOperand(opNum+1).isImm() &&
608 MI->getOperand(opNum+1).getImm() == 0)
609 return; // don't print ',0' or '+0'
610 O << "+";
611 printOperand(MI, opNum+1, O);
612 }
613}
614
615void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
616 raw_ostream &O, const char *Modifier)
617{
618 if (Modifier) {
619 const MachineOperand &MO = MI->getOperand(opNum);
620 int Imm = (int)MO.getImm();
621 if (!strcmp(Modifier, "volatile")) {
622 if (Imm)
623 O << ".volatile";
624 } else if (!strcmp(Modifier, "addsp")) {
625 switch (Imm) {
626 case NVPTX::PTXLdStInstCode::GLOBAL: O << ".global"; break;
627 case NVPTX::PTXLdStInstCode::SHARED: O << ".shared"; break;
628 case NVPTX::PTXLdStInstCode::LOCAL: O << ".local"; break;
629 case NVPTX::PTXLdStInstCode::PARAM: O << ".param"; break;
630 case NVPTX::PTXLdStInstCode::CONSTANT: O << ".const"; break;
631 case NVPTX::PTXLdStInstCode::GENERIC:
632 if (!nvptxSubtarget.hasGenericLdSt())
633 O << ".global";
634 break;
635 default:
636 assert("wrong value");
637 }
638 }
639 else if (!strcmp(Modifier, "sign")) {
640 if (Imm==NVPTX::PTXLdStInstCode::Signed)
641 O << "s";
642 else if (Imm==NVPTX::PTXLdStInstCode::Unsigned)
643 O << "u";
644 else
645 O << "f";
646 }
647 else if (!strcmp(Modifier, "vec")) {
648 if (Imm==NVPTX::PTXLdStInstCode::V2)
649 O << ".v2";
650 else if (Imm==NVPTX::PTXLdStInstCode::V4)
651 O << ".v4";
652 }
653 else
654 assert("unknown modifier");
655 }
656 else
657 assert("unknown modifier");
658}
659
660void NVPTXAsmPrinter::emitDeclaration (const Function *F, raw_ostream &O) {
661
662 emitLinkageDirective(F,O);
663 if (llvm::isKernelFunction(*F))
664 O << ".entry ";
665 else
666 O << ".func ";
667 printReturnValStr(F, O);
668 O << *CurrentFnSym << "\n";
669 emitFunctionParamList(F, O);
670 O << ";\n";
671}
672
673static bool usedInGlobalVarDef(const Constant *C)
674{
675 if (!C)
676 return false;
677
678 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
679 if (GV->getName().str() == "llvm.used")
680 return false;
681 return true;
682 }
683
684 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
685 ui!=ue; ++ui) {
686 const Constant *C = dyn_cast<Constant>(*ui);
687 if (usedInGlobalVarDef(C))
688 return true;
689 }
690 return false;
691}
692
693static bool usedInOneFunc(const User *U, Function const *&oneFunc)
694{
695 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
696 if (othergv->getName().str() == "llvm.used")
697 return true;
698 }
699
700 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
701 if (instr->getParent() && instr->getParent()->getParent()) {
702 const Function *curFunc = instr->getParent()->getParent();
703 if (oneFunc && (curFunc != oneFunc))
704 return false;
705 oneFunc = curFunc;
706 return true;
707 }
708 else
709 return false;
710 }
711
712 if (const MDNode *md = dyn_cast<MDNode>(U))
713 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
714 (md->getName().str() == "llvm.dbg.sp")))
715 return true;
716
717
718 for (User::const_use_iterator ui=U->use_begin(), ue=U->use_end();
719 ui!=ue; ++ui) {
720 if (usedInOneFunc(*ui, oneFunc) == false)
721 return false;
722 }
723 return true;
724}
725
726/* Find out if a global variable can be demoted to local scope.
727 * Currently, this is valid for CUDA shared variables, which have local
728 * scope and global lifetime. So the conditions to check are :
729 * 1. Is the global variable in shared address space?
730 * 2. Does it have internal linkage?
731 * 3. Is the global variable referenced only in one function?
732 */
733static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
734 if (gv->hasInternalLinkage() == false)
735 return false;
736 const PointerType *Pty = gv->getType();
737 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
738 return false;
739
740 const Function *oneFunc = 0;
741
742 bool flag = usedInOneFunc(gv, oneFunc);
743 if (flag == false)
744 return false;
745 if (!oneFunc)
746 return false;
747 f = oneFunc;
748 return true;
749}
750
751static bool useFuncSeen(const Constant *C,
752 llvm::DenseMap<const Function *, bool> &seenMap) {
753 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
754 ui!=ue; ++ui) {
755 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
756 if (useFuncSeen(cu, seenMap))
757 return true;
758 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
759 const BasicBlock *bb = I->getParent();
760 if (!bb) continue;
761 const Function *caller = bb->getParent();
762 if (!caller) continue;
763 if (seenMap.find(caller) != seenMap.end())
764 return true;
765 }
766 }
767 return false;
768}
769
770void NVPTXAsmPrinter::emitDeclarations (Module &M, raw_ostream &O) {
771 llvm::DenseMap<const Function *, bool> seenMap;
772 for (Module::const_iterator FI=M.begin(), FE=M.end();
773 FI!=FE; ++FI) {
774 const Function *F = FI;
775
776 if (F->isDeclaration()) {
777 if (F->use_empty())
778 continue;
779 if (F->getIntrinsicID())
780 continue;
781 CurrentFnSym = Mang->getSymbol(F);
782 emitDeclaration(F, O);
783 continue;
784 }
785 for (Value::const_use_iterator iter=F->use_begin(),
786 iterEnd=F->use_end(); iter!=iterEnd; ++iter) {
787 if (const Constant *C = dyn_cast<Constant>(*iter)) {
788 if (usedInGlobalVarDef(C)) {
789 // The use is in the initialization of a global variable
790 // that is a function pointer, so print a declaration
791 // for the original function
792 CurrentFnSym = Mang->getSymbol(F);
793 emitDeclaration(F, O);
794 break;
795 }
796 // Emit a declaration of this function if the function that
797 // uses this constant expr has already been seen.
798 if (useFuncSeen(C, seenMap)) {
799 CurrentFnSym = Mang->getSymbol(F);
800 emitDeclaration(F, O);
801 break;
802 }
803 }
804
805 if (!isa<Instruction>(*iter)) continue;
806 const Instruction *instr = cast<Instruction>(*iter);
807 const BasicBlock *bb = instr->getParent();
808 if (!bb) continue;
809 const Function *caller = bb->getParent();
810 if (!caller) continue;
811
812 // If a caller has already been seen, then the caller is
813 // appearing in the module before the callee. so print out
814 // a declaration for the callee.
815 if (seenMap.find(caller) != seenMap.end()) {
816 CurrentFnSym = Mang->getSymbol(F);
817 emitDeclaration(F, O);
818 break;
819 }
820 }
821 seenMap[F] = true;
822 }
823}
824
825void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
826 DebugInfoFinder DbgFinder;
827 DbgFinder.processModule(M);
828
829 unsigned i=1;
830 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
831 E = DbgFinder.compile_unit_end(); I != E; ++I) {
832 DICompileUnit DIUnit(*I);
833 StringRef Filename(DIUnit.getFilename());
834 StringRef Dirname(DIUnit.getDirectory());
835 SmallString<128> FullPathName = Dirname;
836 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
837 sys::path::append(FullPathName, Filename);
838 Filename = FullPathName.str();
839 }
840 if (filenameMap.find(Filename.str()) != filenameMap.end())
841 continue;
842 filenameMap[Filename.str()] = i;
843 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
844 ++i;
845 }
846
847 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
848 E = DbgFinder.subprogram_end(); I != E; ++I) {
849 DISubprogram SP(*I);
850 StringRef Filename(SP.getFilename());
851 StringRef Dirname(SP.getDirectory());
852 SmallString<128> FullPathName = Dirname;
853 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
854 sys::path::append(FullPathName, Filename);
855 Filename = FullPathName.str();
856 }
857 if (filenameMap.find(Filename.str()) != filenameMap.end())
858 continue;
859 filenameMap[Filename.str()] = i;
860 ++i;
861 }
862}
863
864bool NVPTXAsmPrinter::doInitialization (Module &M) {
865
866 SmallString<128> Str1;
867 raw_svector_ostream OS1(Str1);
868
869 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
870 MMI->AnalyzeModule(M);
871
872 // We need to call the parent's one explicitly.
873 //bool Result = AsmPrinter::doInitialization(M);
874
875 // Initialize TargetLoweringObjectFile.
876 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
877 .Initialize(OutContext, TM);
878
Micah Villmow3574eca2012-10-08 16:38:25 +0000879 Mang = new Mangler(OutContext, *TM.getDataLayout());
Justin Holewinski49683f32012-05-04 20:18:50 +0000880
881 // Emit header before any dwarf directives are emitted below.
882 emitHeader(M, OS1);
883 OutStreamer.EmitRawText(OS1.str());
884
885
886 // Already commented out
887 //bool Result = AsmPrinter::doInitialization(M);
888
889
890 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
891 recordAndEmitFilenames(M);
892
893 SmallString<128> Str2;
894 raw_svector_ostream OS2(Str2);
895
896 emitDeclarations(M, OS2);
897
898 // Print out module-level global variables here.
899 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
900 I != E; ++I)
901 printModuleLevelGV(I, OS2);
902
903 OS2 << '\n';
904
905 OutStreamer.EmitRawText(OS2.str());
906 return false; // success
907}
908
909void NVPTXAsmPrinter::emitHeader (Module &M, raw_ostream &O) {
910 O << "//\n";
911 O << "// Generated by LLVM NVPTX Back-End\n";
912 O << "//\n";
913 O << "\n";
914
915 O << ".version 3.0\n";
916
917 O << ".target ";
918 O << nvptxSubtarget.getTargetName();
919
920 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
921 O << ", texmode_independent";
922 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
923 if (!nvptxSubtarget.hasDouble())
924 O << ", map_f64_to_f32";
925 }
926
927 if (MAI->doesSupportDebugInformation())
928 O << ", debug";
929
930 O << "\n";
931
932 O << ".address_size ";
933 if (nvptxSubtarget.is64Bit())
934 O << "64";
935 else
936 O << "32";
937 O << "\n";
938
939 O << "\n";
940}
941
942bool NVPTXAsmPrinter::doFinalization(Module &M) {
943 // XXX Temproarily remove global variables so that doFinalization() will not
944 // emit them again (global variables are emitted at beginning).
945
946 Module::GlobalListType &global_list = M.getGlobalList();
947 int i, n = global_list.size();
948 GlobalVariable **gv_array = new GlobalVariable* [n];
949
950 // first, back-up GlobalVariable in gv_array
951 i = 0;
952 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
953 I != E; ++I)
954 gv_array[i++] = &*I;
955
956 // second, empty global_list
957 while (!global_list.empty())
958 global_list.remove(global_list.begin());
959
960 // call doFinalization
961 bool ret = AsmPrinter::doFinalization(M);
962
963 // now we restore global variables
964 for (i = 0; i < n; i ++)
965 global_list.insert(global_list.end(), gv_array[i]);
966
967 delete[] gv_array;
968 return ret;
969
970
971 //bool Result = AsmPrinter::doFinalization(M);
972 // Instead of calling the parents doFinalization, we may
973 // clone parents doFinalization and customize here.
974 // Currently, we if NVISA out the EmitGlobals() in
975 // parent's doFinalization, which is too intrusive.
976 //
977 // Same for the doInitialization.
978 //return Result;
979}
980
981// This function emits appropriate linkage directives for
982// functions and global variables.
983//
984// extern function declaration -> .extern
985// extern function definition -> .visible
986// external global variable with init -> .visible
987// external without init -> .extern
988// appending -> not allowed, assert.
989
990void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue* V, raw_ostream &O)
991{
992 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
993 if (V->hasExternalLinkage()) {
994 if (isa<GlobalVariable>(V)) {
995 const GlobalVariable *GVar = cast<GlobalVariable>(V);
996 if (GVar) {
997 if (GVar->hasInitializer())
998 O << ".visible ";
999 else
1000 O << ".extern ";
1001 }
1002 } else if (V->isDeclaration())
1003 O << ".extern ";
1004 else
1005 O << ".visible ";
1006 } else if (V->hasAppendingLinkage()) {
1007 std::string msg;
1008 msg.append("Error: ");
1009 msg.append("Symbol ");
1010 if (V->hasName())
1011 msg.append(V->getName().str());
1012 msg.append("has unsupported appending linkage type");
1013 llvm_unreachable(msg.c_str());
1014 }
1015 }
1016}
1017
1018
1019void NVPTXAsmPrinter::printModuleLevelGV(GlobalVariable* GVar, raw_ostream &O,
1020 bool processDemoted) {
1021
1022 // Skip meta data
1023 if (GVar->hasSection()) {
1024 if (GVar->getSection() == "llvm.metadata")
1025 return;
1026 }
1027
Micah Villmow3574eca2012-10-08 16:38:25 +00001028 const DataLayout *TD = TM.getDataLayout();
Justin Holewinski49683f32012-05-04 20:18:50 +00001029
1030 // GlobalVariables are always constant pointers themselves.
1031 const PointerType *PTy = GVar->getType();
1032 Type *ETy = PTy->getElementType();
1033
1034 if (GVar->hasExternalLinkage()) {
1035 if (GVar->hasInitializer())
1036 O << ".visible ";
1037 else
1038 O << ".extern ";
1039 }
1040
1041 if (llvm::isTexture(*GVar)) {
1042 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1043 return;
1044 }
1045
1046 if (llvm::isSurface(*GVar)) {
1047 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1048 return;
1049 }
1050
1051 if (GVar->isDeclaration()) {
1052 // (extern) declarations, no definition or initializer
1053 // Currently the only known declaration is for an automatic __local
1054 // (.shared) promoted to global.
1055 emitPTXGlobalVariable(GVar, O);
1056 O << ";\n";
1057 return;
1058 }
1059
1060 if (llvm::isSampler(*GVar)) {
1061 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1062
1063 Constant *Initializer = NULL;
1064 if (GVar->hasInitializer())
1065 Initializer = GVar->getInitializer();
1066 ConstantInt *CI = NULL;
1067 if (Initializer)
1068 CI = dyn_cast<ConstantInt>(Initializer);
1069 if (CI) {
1070 unsigned sample=CI->getZExtValue();
1071
1072 O << " = { ";
1073
1074 for (int i =0, addr=((sample & __CLK_ADDRESS_MASK ) >>
1075 __CLK_ADDRESS_BASE) ; i < 3 ; i++) {
1076 O << "addr_mode_" << i << " = ";
1077 switch (addr) {
1078 case 0: O << "wrap"; break;
1079 case 1: O << "clamp_to_border"; break;
1080 case 2: O << "clamp_to_edge"; break;
1081 case 3: O << "wrap"; break;
1082 case 4: O << "mirror"; break;
1083 }
1084 O <<", ";
1085 }
1086 O << "filter_mode = ";
1087 switch (( sample & __CLK_FILTER_MASK ) >> __CLK_FILTER_BASE ) {
1088 case 0: O << "nearest"; break;
1089 case 1: O << "linear"; break;
1090 case 2: assert ( 0 && "Anisotropic filtering is not supported");
1091 default: O << "nearest"; break;
1092 }
1093 if (!(( sample &__CLK_NORMALIZED_MASK ) >> __CLK_NORMALIZED_BASE)) {
1094 O << ", force_unnormalized_coords = 1";
1095 }
1096 O << " }";
1097 }
1098
1099 O << ";\n";
1100 return;
1101 }
1102
1103 if (GVar->hasPrivateLinkage()) {
1104
1105 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1106 return;
1107
1108 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1109 if (!strncmp(GVar->getName().data(), "filename", 8))
1110 return;
1111 if (GVar->use_empty())
1112 return;
1113 }
1114
1115 const Function *demotedFunc = 0;
1116 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1117 O << "// " << GVar->getName().str() << " has been demoted\n";
1118 if (localDecls.find(demotedFunc) != localDecls.end())
1119 localDecls[demotedFunc].push_back(GVar);
1120 else {
1121 std::vector<GlobalVariable *> temp;
1122 temp.push_back(GVar);
1123 localDecls[demotedFunc] = temp;
1124 }
1125 return;
1126 }
1127
1128 O << ".";
1129 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1130 if (GVar->getAlignment() == 0)
1131 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1132 else
1133 O << " .align " << GVar->getAlignment();
1134
1135
1136 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1137 O << " .";
1138 O << getPTXFundamentalTypeStr(ETy, false);
1139 O << " ";
1140 O << *Mang->getSymbol(GVar);
1141
1142 // Ptx allows variable initilization only for constant and global state
1143 // spaces.
1144 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1145 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1146 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1147 && GVar->hasInitializer()) {
1148 Constant *Initializer = GVar->getInitializer();
1149 if (!Initializer->isNullValue()) {
1150 O << " = " ;
1151 printScalarConstant(Initializer, O);
1152 }
1153 }
1154 } else {
1155 unsigned int ElementSize =0;
1156
1157 // Although PTX has direct support for struct type and array type and
1158 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1159 // targets that support these high level field accesses. Structs, arrays
1160 // and vectors are lowered into arrays of bytes.
1161 switch (ETy->getTypeID()) {
1162 case Type::StructTyID:
1163 case Type::ArrayTyID:
1164 case Type::VectorTyID:
1165 ElementSize = TD->getTypeStoreSize(ETy);
1166 // Ptx allows variable initilization only for constant and
1167 // global state spaces.
1168 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1169 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1170 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1171 && GVar->hasInitializer()) {
1172 Constant *Initializer = GVar->getInitializer();
1173 if (!isa<UndefValue>(Initializer) &&
1174 !Initializer->isNullValue()) {
1175 AggBuffer aggBuffer(ElementSize, O, *this);
1176 bufferAggregateConstant(Initializer, &aggBuffer);
1177 if (aggBuffer.numSymbols) {
1178 if (nvptxSubtarget.is64Bit()) {
1179 O << " .u64 " << *Mang->getSymbol(GVar) <<"[" ;
1180 O << ElementSize/8;
1181 }
1182 else {
1183 O << " .u32 " << *Mang->getSymbol(GVar) <<"[" ;
1184 O << ElementSize/4;
1185 }
1186 O << "]";
1187 }
1188 else {
1189 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1190 O << ElementSize;
1191 O << "]";
1192 }
1193 O << " = {" ;
1194 aggBuffer.print();
1195 O << "}";
1196 }
1197 else {
1198 O << " .b8 " << *Mang->getSymbol(GVar) ;
1199 if (ElementSize) {
1200 O <<"[" ;
1201 O << ElementSize;
1202 O << "]";
1203 }
1204 }
1205 }
1206 else {
1207 O << " .b8 " << *Mang->getSymbol(GVar);
1208 if (ElementSize) {
1209 O <<"[" ;
1210 O << ElementSize;
1211 O << "]";
1212 }
1213 }
1214 break;
1215 default:
1216 assert( 0 && "type not supported yet");
1217 }
1218
1219 }
1220 O << ";\n";
1221}
1222
1223void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1224 if (localDecls.find(f) == localDecls.end())
1225 return;
1226
1227 std::vector<GlobalVariable *> &gvars = localDecls[f];
1228
1229 for (unsigned i=0, e=gvars.size(); i!=e; ++i) {
1230 O << "\t// demoted variable\n\t";
1231 printModuleLevelGV(gvars[i], O, true);
1232 }
1233}
1234
1235void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1236 raw_ostream &O) const {
1237 switch (AddressSpace) {
1238 case llvm::ADDRESS_SPACE_LOCAL:
1239 O << "local" ;
1240 break;
1241 case llvm::ADDRESS_SPACE_GLOBAL:
1242 O << "global" ;
1243 break;
1244 case llvm::ADDRESS_SPACE_CONST:
1245 // This logic should be consistent with that in
1246 // getCodeAddrSpace() (NVPTXISelDATToDAT.cpp)
1247 if (nvptxSubtarget.hasGenericLdSt())
1248 O << "global" ;
1249 else
1250 O << "const" ;
1251 break;
1252 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1253 O << "const" ;
1254 break;
1255 case llvm::ADDRESS_SPACE_SHARED:
1256 O << "shared" ;
1257 break;
1258 default:
Craig Topper63663612012-05-24 07:02:50 +00001259 llvm_unreachable("unexpected address space");
Justin Holewinski49683f32012-05-04 20:18:50 +00001260 }
1261}
1262
1263std::string NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty,
1264 bool useB4PTR) const {
1265 switch (Ty->getTypeID()) {
1266 default:
1267 llvm_unreachable("unexpected type");
1268 break;
1269 case Type::IntegerTyID: {
1270 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1271 if (NumBits == 1)
1272 return "pred";
1273 else if (NumBits <= 64) {
1274 std::string name = "u";
1275 return name + utostr(NumBits);
1276 } else {
1277 llvm_unreachable("Integer too large");
1278 break;
1279 }
1280 break;
1281 }
1282 case Type::FloatTyID:
1283 return "f32";
1284 case Type::DoubleTyID:
1285 return "f64";
1286 case Type::PointerTyID:
1287 if (nvptxSubtarget.is64Bit())
1288 if (useB4PTR) return "b64";
1289 else return "u64";
1290 else
1291 if (useB4PTR) return "b32";
1292 else return "u32";
1293 }
1294 llvm_unreachable("unexpected type");
1295 return NULL;
1296}
1297
1298void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable* GVar,
1299 raw_ostream &O) {
1300
Micah Villmow3574eca2012-10-08 16:38:25 +00001301 const DataLayout *TD = TM.getDataLayout();
Justin Holewinski49683f32012-05-04 20:18:50 +00001302
1303 // GlobalVariables are always constant pointers themselves.
1304 const PointerType *PTy = GVar->getType();
1305 Type *ETy = PTy->getElementType();
1306
1307 O << ".";
1308 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1309 if (GVar->getAlignment() == 0)
1310 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1311 else
1312 O << " .align " << GVar->getAlignment();
1313
1314 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1315 O << " .";
1316 O << getPTXFundamentalTypeStr(ETy);
1317 O << " ";
1318 O << *Mang->getSymbol(GVar);
1319 return;
1320 }
1321
1322 int64_t ElementSize =0;
1323
1324 // Although PTX has direct support for struct type and array type and LLVM IR
1325 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1326 // support these high level field accesses. Structs and arrays are lowered
1327 // into arrays of bytes.
1328 switch (ETy->getTypeID()) {
1329 case Type::StructTyID:
1330 case Type::ArrayTyID:
1331 case Type::VectorTyID:
1332 ElementSize = TD->getTypeStoreSize(ETy);
1333 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1334 if (ElementSize) {
1335 O << itostr(ElementSize) ;
1336 }
1337 O << "]";
1338 break;
1339 default:
1340 assert( 0 && "type not supported yet");
1341 }
1342 return ;
1343}
1344
1345
1346static unsigned int
Micah Villmow3574eca2012-10-08 16:38:25 +00001347getOpenCLAlignment(const DataLayout *TD,
Justin Holewinski49683f32012-05-04 20:18:50 +00001348 Type *Ty) {
1349 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1350 return TD->getPrefTypeAlignment(Ty);
1351
1352 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1353 if (ATy)
1354 return getOpenCLAlignment(TD, ATy->getElementType());
1355
1356 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1357 if (VTy) {
1358 Type *ETy = VTy->getElementType();
1359 unsigned int numE = VTy->getNumElements();
1360 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1361 if (numE == 3)
1362 return 4*alignE;
1363 else
1364 return numE*alignE;
1365 }
1366
1367 const StructType *STy = dyn_cast<StructType>(Ty);
1368 if (STy) {
1369 unsigned int alignStruct = 1;
1370 // Go through each element of the struct and find the
1371 // largest alignment.
1372 for (unsigned i=0, e=STy->getNumElements(); i != e; i++) {
1373 Type *ETy = STy->getElementType(i);
1374 unsigned int align = getOpenCLAlignment(TD, ETy);
1375 if (align > alignStruct)
1376 alignStruct = align;
1377 }
1378 return alignStruct;
1379 }
1380
1381 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1382 if (FTy)
Micah Villmow2c39b152012-10-15 16:24:29 +00001383 return TD->getPointerPrefAlignment(0);
Justin Holewinski49683f32012-05-04 20:18:50 +00001384 return TD->getPrefTypeAlignment(Ty);
1385}
1386
1387void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1388 int paramIndex, raw_ostream &O) {
1389 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1390 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1391 O << *CurrentFnSym << "_param_" << paramIndex;
1392 else {
1393 std::string argName = I->getName();
1394 const char *p = argName.c_str();
1395 while (*p) {
1396 if (*p == '.')
1397 O << "_";
1398 else
1399 O << *p;
1400 p++;
1401 }
1402 }
1403}
1404
1405void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1406 Function::const_arg_iterator I, E;
1407 int i = 0;
1408
1409 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1410 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1411 O << *CurrentFnSym << "_param_" << paramIndex;
1412 return;
1413 }
1414
1415 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1416 if (i==paramIndex) {
1417 printParamName(I, paramIndex, O);
1418 return;
1419 }
1420 }
1421 llvm_unreachable("paramIndex out of bound");
1422}
1423
1424void NVPTXAsmPrinter::emitFunctionParamList(const Function *F,
1425 raw_ostream &O) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001426 const DataLayout *TD = TM.getDataLayout();
Justin Holewinski49683f32012-05-04 20:18:50 +00001427 const AttrListPtr &PAL = F->getAttributes();
1428 const TargetLowering *TLI = TM.getTargetLowering();
1429 Function::const_arg_iterator I, E;
1430 unsigned paramIndex = 0;
1431 bool first = true;
1432 bool isKernelFunc = llvm::isKernelFunction(*F);
1433 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1434 MVT thePointerTy = TLI->getPointerTy();
1435
1436 O << "(\n";
1437
1438 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1439 const Type *Ty = I->getType();
1440
1441 if (!first)
1442 O << ",\n";
1443
1444 first = false;
1445
1446 // Handle image/sampler parameters
1447 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1448 if (llvm::isImage(*I)) {
1449 std::string sname = I->getName();
1450 if (llvm::isImageWriteOnly(*I))
1451 O << "\t.param .surfref " << *CurrentFnSym << "_param_" << paramIndex;
1452 else // Default image is read_only
1453 O << "\t.param .texref " << *CurrentFnSym << "_param_" << paramIndex;
1454 }
1455 else // Should be llvm::isSampler(*I)
1456 O << "\t.param .samplerref " << *CurrentFnSym << "_param_"
1457 << paramIndex;
1458 continue;
1459 }
1460
Bill Wendling67658342012-10-09 07:45:08 +00001461 if (PAL.getParamAttributes(paramIndex+1).
1462 hasAttribute(Attributes::ByVal) == false) {
Justin Holewinski49683f32012-05-04 20:18:50 +00001463 // Just a scalar
1464 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1465 if (isKernelFunc) {
1466 if (PTy) {
1467 // Special handling for pointer arguments to kernel
1468 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1469
1470 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1471 Type *ETy = PTy->getElementType();
1472 int addrSpace = PTy->getAddressSpace();
1473 switch(addrSpace) {
1474 default:
1475 O << ".ptr ";
1476 break;
1477 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1478 O << ".ptr .const ";
1479 break;
1480 case llvm::ADDRESS_SPACE_SHARED:
1481 O << ".ptr .shared ";
1482 break;
1483 case llvm::ADDRESS_SPACE_GLOBAL:
1484 case llvm::ADDRESS_SPACE_CONST:
1485 O << ".ptr .global ";
1486 break;
1487 }
1488 O << ".align " << (int)getOpenCLAlignment(TD, ETy) << " ";
1489 }
1490 printParamName(I, paramIndex, O);
1491 continue;
1492 }
1493
1494 // non-pointer scalar to kernel func
1495 O << "\t.param ."
1496 << getPTXFundamentalTypeStr(Ty) << " ";
1497 printParamName(I, paramIndex, O);
1498 continue;
1499 }
1500 // Non-kernel function, just print .param .b<size> for ABI
1501 // and .reg .b<size> for non ABY
1502 unsigned sz = 0;
1503 if (isa<IntegerType>(Ty)) {
1504 sz = cast<IntegerType>(Ty)->getBitWidth();
1505 if (sz < 32) sz = 32;
1506 }
1507 else if (isa<PointerType>(Ty))
1508 sz = thePointerTy.getSizeInBits();
1509 else
1510 sz = Ty->getPrimitiveSizeInBits();
1511 if (isABI)
1512 O << "\t.param .b" << sz << " ";
1513 else
1514 O << "\t.reg .b" << sz << " ";
1515 printParamName(I, paramIndex, O);
1516 continue;
1517 }
1518
1519 // param has byVal attribute. So should be a pointer
1520 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1521 assert(PTy &&
1522 "Param with byval attribute should be a pointer type");
1523 Type *ETy = PTy->getElementType();
1524
1525 if (isABI || isKernelFunc) {
1526 // Just print .param .b8 .align <a> .param[size];
1527 // <a> = PAL.getparamalignment
1528 // size = typeallocsize of element type
1529 unsigned align = PAL.getParamAlignment(paramIndex+1);
1530 unsigned sz = TD->getTypeAllocSize(ETy);
1531 O << "\t.param .align " << align
1532 << " .b8 ";
1533 printParamName(I, paramIndex, O);
1534 O << "[" << sz << "]";
1535 continue;
1536 } else {
1537 // Split the ETy into constituent parts and
1538 // print .param .b<size> <name> for each part.
1539 // Further, if a part is vector, print the above for
1540 // each vector element.
1541 SmallVector<EVT, 16> vtparts;
1542 ComputeValueVTs(*TLI, ETy, vtparts);
1543 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
1544 unsigned elems = 1;
1545 EVT elemtype = vtparts[i];
1546 if (vtparts[i].isVector()) {
1547 elems = vtparts[i].getVectorNumElements();
1548 elemtype = vtparts[i].getVectorElementType();
1549 }
1550
1551 for (unsigned j=0,je=elems; j!=je; ++j) {
1552 unsigned sz = elemtype.getSizeInBits();
1553 if (elemtype.isInteger() && (sz < 32)) sz = 32;
1554 O << "\t.reg .b" << sz << " ";
1555 printParamName(I, paramIndex, O);
1556 if (j<je-1) O << ",\n";
1557 ++paramIndex;
1558 }
1559 if (i<e-1)
1560 O << ",\n";
1561 }
1562 --paramIndex;
1563 continue;
1564 }
1565 }
1566
1567 O << "\n)\n";
1568}
1569
1570void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1571 raw_ostream &O) {
1572 const Function *F = MF.getFunction();
1573 emitFunctionParamList(F, O);
1574}
1575
1576
1577void NVPTXAsmPrinter::
1578setAndEmitFunctionVirtualRegisters(const MachineFunction &MF) {
1579 SmallString<128> Str;
1580 raw_svector_ostream O(Str);
1581
1582 // Map the global virtual register number to a register class specific
1583 // virtual register number starting from 1 with that class.
1584 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1585 //unsigned numRegClasses = TRI->getNumRegClasses();
1586
1587 // Emit the Fake Stack Object
1588 const MachineFrameInfo *MFI = MF.getFrameInfo();
1589 int NumBytes = (int) MFI->getStackSize();
1590 if (NumBytes) {
1591 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t"
1592 << DEPOTNAME
1593 << getFunctionNumber() << "[" << NumBytes << "];\n";
1594 if (nvptxSubtarget.is64Bit()) {
1595 O << "\t.reg .b64 \t%SP;\n";
1596 O << "\t.reg .b64 \t%SPL;\n";
1597 }
1598 else {
1599 O << "\t.reg .b32 \t%SP;\n";
1600 O << "\t.reg .b32 \t%SPL;\n";
1601 }
1602 }
1603
1604 // Go through all virtual registers to establish the mapping between the
1605 // global virtual
1606 // register number and the per class virtual register number.
1607 // We use the per class virtual register number in the ptx output.
1608 unsigned int numVRs = MRI->getNumVirtRegs();
1609 for (unsigned i=0; i< numVRs; i++) {
1610 unsigned int vr = TRI->index2VirtReg(i);
1611 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1612 std::map<unsigned, unsigned> &regmap = VRidGlobal2LocalMap[RC->getID()];
1613 int n = regmap.size();
1614 regmap.insert(std::make_pair(vr, n+1));
1615 }
1616
1617 // Emit register declarations
1618 // @TODO: Extract out the real register usage
1619 O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1620 O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1621 O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1622 O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1623 O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1624 O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1625 O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1626
1627 // Emit declaration of the virtual registers or 'physical' registers for
1628 // each register class
1629 //for (unsigned i=0; i< numRegClasses; i++) {
1630 // std::map<unsigned, unsigned> &regmap = VRidGlobal2LocalMap[i];
1631 // const TargetRegisterClass *RC = TRI->getRegClass(i);
1632 // std::string rcname = getNVPTXRegClassName(RC);
1633 // std::string rcStr = getNVPTXRegClassStr(RC);
1634 // //int n = regmap.size();
1635 // if (!isNVPTXVectorRegClass(RC)) {
1636 // O << "\t.reg " << rcname << " \t" << rcStr << "<"
1637 // << NVPTXNumRegisters << ">;\n";
1638 // }
1639
1640 // Only declare those registers that may be used. And do not emit vector
1641 // registers as
1642 // they are all elementized to scalar registers.
1643 //if (n && !isNVPTXVectorRegClass(RC)) {
1644 // if (RegAllocNilUsed) {
1645 // O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1646 // << ">;\n";
1647 // }
1648 // else {
1649 // O << "\t.reg " << rcname << " \t" << StrToUpper(rcStr)
1650 // << "<" << 32 << ">;\n";
1651 // }
1652 //}
1653 //}
1654
1655 OutStreamer.EmitRawText(O.str());
1656}
1657
1658
1659void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1660 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1661 bool ignored;
1662 unsigned int numHex;
1663 const char *lead;
1664
1665 if (Fp->getType()->getTypeID()==Type::FloatTyID) {
1666 numHex = 8;
1667 lead = "0f";
1668 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1669 &ignored);
1670 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1671 numHex = 16;
1672 lead = "0d";
1673 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1674 &ignored);
1675 } else
1676 llvm_unreachable("unsupported fp type");
1677
1678 APInt API = APF.bitcastToAPInt();
1679 std::string hexstr(utohexstr(API.getZExtValue()));
1680 O << lead;
1681 if (hexstr.length() < numHex)
1682 O << std::string(numHex - hexstr.length(), '0');
1683 O << utohexstr(API.getZExtValue());
1684}
1685
1686void NVPTXAsmPrinter::printScalarConstant(Constant *CPV, raw_ostream &O) {
1687 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1688 O << CI->getValue();
1689 return;
1690 }
1691 if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1692 printFPConstant(CFP, O);
1693 return;
1694 }
1695 if (isa<ConstantPointerNull>(CPV)) {
1696 O << "0";
1697 return;
1698 }
1699 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1700 O << *Mang->getSymbol(GVar);
1701 return;
1702 }
1703 if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1704 Value *v = Cexpr->stripPointerCasts();
1705 if (GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1706 O << *Mang->getSymbol(GVar);
1707 return;
1708 } else {
1709 O << *LowerConstant(CPV, *this);
1710 return;
1711 }
1712 }
1713 llvm_unreachable("Not scalar type found in printScalarConstant()");
1714}
1715
1716
1717void NVPTXAsmPrinter::bufferLEByte(Constant *CPV, int Bytes,
1718 AggBuffer *aggBuffer) {
1719
Micah Villmow3574eca2012-10-08 16:38:25 +00001720 const DataLayout *TD = TM.getDataLayout();
Justin Holewinski49683f32012-05-04 20:18:50 +00001721
1722 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1723 int s = TD->getTypeAllocSize(CPV->getType());
1724 if (s<Bytes)
1725 s = Bytes;
1726 aggBuffer->addZeros(s);
1727 return;
1728 }
1729
1730 unsigned char *ptr;
1731 switch (CPV->getType()->getTypeID()) {
1732
1733 case Type::IntegerTyID: {
1734 const Type *ETy = CPV->getType();
1735 if ( ETy == Type::getInt8Ty(CPV->getContext()) ){
1736 unsigned char c =
1737 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1738 ptr = &c;
1739 aggBuffer->addBytes(ptr, 1, Bytes);
1740 } else if ( ETy == Type::getInt16Ty(CPV->getContext()) ) {
1741 short int16 =
1742 (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1743 ptr = (unsigned char*)&int16;
1744 aggBuffer->addBytes(ptr, 2, Bytes);
1745 } else if ( ETy == Type::getInt32Ty(CPV->getContext()) ) {
1746 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1747 int int32 =(int)(constInt->getZExtValue());
1748 ptr = (unsigned char*)&int32;
1749 aggBuffer->addBytes(ptr, 4, Bytes);
1750 break;
Craig Topper63663612012-05-24 07:02:50 +00001751 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
Justin Holewinski49683f32012-05-04 20:18:50 +00001752 if (ConstantInt *constInt =
1753 dyn_cast<ConstantInt>(ConstantFoldConstantExpression(
1754 Cexpr, TD))) {
1755 int int32 =(int)(constInt->getZExtValue());
1756 ptr = (unsigned char*)&int32;
1757 aggBuffer->addBytes(ptr, 4, Bytes);
1758 break;
1759 }
1760 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1761 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1762 aggBuffer->addSymbol(v);
1763 aggBuffer->addZeros(4);
1764 break;
1765 }
1766 }
Craig Topper63663612012-05-24 07:02:50 +00001767 llvm_unreachable("unsupported integer const type");
Justin Holewinski49683f32012-05-04 20:18:50 +00001768 } else if (ETy == Type::getInt64Ty(CPV->getContext()) ) {
1769 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1770 long long int64 =(long long)(constInt->getZExtValue());
1771 ptr = (unsigned char*)&int64;
1772 aggBuffer->addBytes(ptr, 8, Bytes);
1773 break;
Craig Topper63663612012-05-24 07:02:50 +00001774 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
Justin Holewinski49683f32012-05-04 20:18:50 +00001775 if (ConstantInt *constInt = dyn_cast<ConstantInt>(
1776 ConstantFoldConstantExpression(Cexpr, TD))) {
1777 long long int64 =(long long)(constInt->getZExtValue());
1778 ptr = (unsigned char*)&int64;
1779 aggBuffer->addBytes(ptr, 8, Bytes);
1780 break;
1781 }
1782 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1783 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1784 aggBuffer->addSymbol(v);
1785 aggBuffer->addZeros(8);
1786 break;
1787 }
1788 }
1789 llvm_unreachable("unsupported integer const type");
Craig Topper63663612012-05-24 07:02:50 +00001790 } else
Justin Holewinski49683f32012-05-04 20:18:50 +00001791 llvm_unreachable("unsupported integer const type");
1792 break;
1793 }
1794 case Type::FloatTyID:
1795 case Type::DoubleTyID: {
1796 ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1797 const Type* Ty = CFP->getType();
1798 if (Ty == Type::getFloatTy(CPV->getContext())) {
1799 float float32 = (float)CFP->getValueAPF().convertToFloat();
1800 ptr = (unsigned char*)&float32;
1801 aggBuffer->addBytes(ptr, 4, Bytes);
1802 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1803 double float64 = CFP->getValueAPF().convertToDouble();
1804 ptr = (unsigned char*)&float64;
1805 aggBuffer->addBytes(ptr, 8, Bytes);
1806 }
1807 else {
1808 llvm_unreachable("unsupported fp const type");
1809 }
1810 break;
1811 }
1812 case Type::PointerTyID: {
1813 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1814 aggBuffer->addSymbol(GVar);
1815 }
1816 else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1817 Value *v = Cexpr->stripPointerCasts();
1818 aggBuffer->addSymbol(v);
1819 }
1820 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1821 aggBuffer->addZeros(s);
1822 break;
1823 }
1824
1825 case Type::ArrayTyID:
1826 case Type::VectorTyID:
1827 case Type::StructTyID: {
1828 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1829 isa<ConstantStruct>(CPV)) {
1830 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1831 bufferAggregateConstant(CPV, aggBuffer);
1832 if ( Bytes > ElementSize )
1833 aggBuffer->addZeros(Bytes-ElementSize);
1834 }
1835 else if (isa<ConstantAggregateZero>(CPV))
1836 aggBuffer->addZeros(Bytes);
1837 else
1838 llvm_unreachable("Unexpected Constant type");
1839 break;
1840 }
1841
1842 default:
1843 llvm_unreachable("unsupported type");
1844 }
1845}
1846
1847void NVPTXAsmPrinter::bufferAggregateConstant(Constant *CPV,
1848 AggBuffer *aggBuffer) {
Micah Villmow3574eca2012-10-08 16:38:25 +00001849 const DataLayout *TD = TM.getDataLayout();
Justin Holewinski49683f32012-05-04 20:18:50 +00001850 int Bytes;
1851
1852 // Old constants
1853 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1854 if (CPV->getNumOperands())
1855 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1856 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1857 return;
1858 }
1859
1860 if (const ConstantDataSequential *CDS =
1861 dyn_cast<ConstantDataSequential>(CPV)) {
1862 if (CDS->getNumElements())
1863 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1864 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1865 aggBuffer);
1866 return;
1867 }
1868
1869
1870 if (isa<ConstantStruct>(CPV)) {
1871 if (CPV->getNumOperands()) {
1872 StructType *ST = cast<StructType>(CPV->getType());
1873 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1874 if ( i == (e - 1))
1875 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1876 TD->getTypeAllocSize(ST)
1877 - TD->getStructLayout(ST)->getElementOffset(i);
1878 else
1879 Bytes = TD->getStructLayout(ST)->getElementOffset(i+1) -
1880 TD->getStructLayout(ST)->getElementOffset(i);
1881 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes,
1882 aggBuffer);
1883 }
1884 }
1885 return;
1886 }
Craig Topper63663612012-05-24 07:02:50 +00001887 llvm_unreachable("unsupported constant type in printAggregateConstant()");
Justin Holewinski49683f32012-05-04 20:18:50 +00001888}
1889
1890// buildTypeNameMap - Run through symbol table looking for type names.
1891//
1892
1893
1894bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1895
1896 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1897
1898 if (PI != TypeNameMap.end() &&
1899 (!PI->second.compare("struct._image1d_t") ||
1900 !PI->second.compare("struct._image2d_t") ||
1901 !PI->second.compare("struct._image3d_t")))
1902 return true;
1903
1904 return false;
1905}
1906
1907/// PrintAsmOperand - Print out an operand for an inline asm expression.
1908///
1909bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1910 unsigned AsmVariant,
1911 const char *ExtraCode,
1912 raw_ostream &O) {
1913 if (ExtraCode && ExtraCode[0]) {
1914 if (ExtraCode[1] != 0) return true; // Unknown modifier.
1915
1916 switch (ExtraCode[0]) {
Jack Carter0518fca2012-06-26 13:49:27 +00001917 default:
1918 // See if this is a generic print operand
1919 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
Justin Holewinski49683f32012-05-04 20:18:50 +00001920 case 'r':
1921 break;
1922 }
1923 }
1924
1925 printOperand(MI, OpNo, O);
1926
1927 return false;
1928}
1929
1930bool NVPTXAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1931 unsigned OpNo,
1932 unsigned AsmVariant,
1933 const char *ExtraCode,
1934 raw_ostream &O) {
1935 if (ExtraCode && ExtraCode[0])
1936 return true; // Unknown modifier
1937
1938 O << '[';
1939 printMemOperand(MI, OpNo, O);
1940 O << ']';
1941
1942 return false;
1943}
1944
1945bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI)
1946{
1947 switch(MI.getOpcode()) {
1948 default:
1949 return false;
1950 case NVPTX::CallArgBeginInst: case NVPTX::CallArgEndInst0:
1951 case NVPTX::CallArgEndInst1: case NVPTX::CallArgF32:
1952 case NVPTX::CallArgF64: case NVPTX::CallArgI16:
1953 case NVPTX::CallArgI32: case NVPTX::CallArgI32imm:
1954 case NVPTX::CallArgI64: case NVPTX::CallArgI8:
1955 case NVPTX::CallArgParam: case NVPTX::CallVoidInst:
1956 case NVPTX::CallVoidInstReg: case NVPTX::Callseq_End:
1957 case NVPTX::CallVoidInstReg64:
1958 case NVPTX::DeclareParamInst: case NVPTX::DeclareRetMemInst:
1959 case NVPTX::DeclareRetRegInst: case NVPTX::DeclareRetScalarInst:
1960 case NVPTX::DeclareScalarParamInst: case NVPTX::DeclareScalarRegInst:
1961 case NVPTX::StoreParamF32: case NVPTX::StoreParamF64:
1962 case NVPTX::StoreParamI16: case NVPTX::StoreParamI32:
1963 case NVPTX::StoreParamI64: case NVPTX::StoreParamI8:
1964 case NVPTX::StoreParamS32I8: case NVPTX::StoreParamU32I8:
1965 case NVPTX::StoreParamS32I16: case NVPTX::StoreParamU32I16:
1966 case NVPTX::StoreParamScalar2F32: case NVPTX::StoreParamScalar2F64:
1967 case NVPTX::StoreParamScalar2I16: case NVPTX::StoreParamScalar2I32:
1968 case NVPTX::StoreParamScalar2I64: case NVPTX::StoreParamScalar2I8:
1969 case NVPTX::StoreParamScalar4F32: case NVPTX::StoreParamScalar4I16:
1970 case NVPTX::StoreParamScalar4I32: case NVPTX::StoreParamScalar4I8:
1971 case NVPTX::StoreParamV2F32: case NVPTX::StoreParamV2F64:
1972 case NVPTX::StoreParamV2I16: case NVPTX::StoreParamV2I32:
1973 case NVPTX::StoreParamV2I64: case NVPTX::StoreParamV2I8:
1974 case NVPTX::StoreParamV4F32: case NVPTX::StoreParamV4I16:
1975 case NVPTX::StoreParamV4I32: case NVPTX::StoreParamV4I8:
1976 case NVPTX::StoreRetvalF32: case NVPTX::StoreRetvalF64:
1977 case NVPTX::StoreRetvalI16: case NVPTX::StoreRetvalI32:
1978 case NVPTX::StoreRetvalI64: case NVPTX::StoreRetvalI8:
1979 case NVPTX::StoreRetvalScalar2F32: case NVPTX::StoreRetvalScalar2F64:
1980 case NVPTX::StoreRetvalScalar2I16: case NVPTX::StoreRetvalScalar2I32:
1981 case NVPTX::StoreRetvalScalar2I64: case NVPTX::StoreRetvalScalar2I8:
1982 case NVPTX::StoreRetvalScalar4F32: case NVPTX::StoreRetvalScalar4I16:
1983 case NVPTX::StoreRetvalScalar4I32: case NVPTX::StoreRetvalScalar4I8:
1984 case NVPTX::StoreRetvalV2F32: case NVPTX::StoreRetvalV2F64:
1985 case NVPTX::StoreRetvalV2I16: case NVPTX::StoreRetvalV2I32:
1986 case NVPTX::StoreRetvalV2I64: case NVPTX::StoreRetvalV2I8:
1987 case NVPTX::StoreRetvalV4F32: case NVPTX::StoreRetvalV4I16:
1988 case NVPTX::StoreRetvalV4I32: case NVPTX::StoreRetvalV4I8:
1989 case NVPTX::LastCallArgF32: case NVPTX::LastCallArgF64:
1990 case NVPTX::LastCallArgI16: case NVPTX::LastCallArgI32:
1991 case NVPTX::LastCallArgI32imm: case NVPTX::LastCallArgI64:
1992 case NVPTX::LastCallArgI8: case NVPTX::LastCallArgParam:
1993 case NVPTX::LoadParamMemF32: case NVPTX::LoadParamMemF64:
1994 case NVPTX::LoadParamMemI16: case NVPTX::LoadParamMemI32:
1995 case NVPTX::LoadParamMemI64: case NVPTX::LoadParamMemI8:
1996 case NVPTX::LoadParamRegF32: case NVPTX::LoadParamRegF64:
1997 case NVPTX::LoadParamRegI16: case NVPTX::LoadParamRegI32:
1998 case NVPTX::LoadParamRegI64: case NVPTX::LoadParamRegI8:
1999 case NVPTX::LoadParamScalar2F32: case NVPTX::LoadParamScalar2F64:
2000 case NVPTX::LoadParamScalar2I16: case NVPTX::LoadParamScalar2I32:
2001 case NVPTX::LoadParamScalar2I64: case NVPTX::LoadParamScalar2I8:
2002 case NVPTX::LoadParamScalar4F32: case NVPTX::LoadParamScalar4I16:
2003 case NVPTX::LoadParamScalar4I32: case NVPTX::LoadParamScalar4I8:
2004 case NVPTX::LoadParamV2F32: case NVPTX::LoadParamV2F64:
2005 case NVPTX::LoadParamV2I16: case NVPTX::LoadParamV2I32:
2006 case NVPTX::LoadParamV2I64: case NVPTX::LoadParamV2I8:
2007 case NVPTX::LoadParamV4F32: case NVPTX::LoadParamV4I16:
2008 case NVPTX::LoadParamV4I32: case NVPTX::LoadParamV4I8:
2009 case NVPTX::PrototypeInst: case NVPTX::DBG_VALUE:
2010 return true;
2011 }
2012 return false;
2013}
2014
2015// Force static initialization.
2016extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2017 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2018 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2019}
2020
2021
2022void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2023 std::stringstream temp;
2024 LineReader * reader = this->getReader(filename.str());
2025 temp << "\n//";
2026 temp << filename.str();
2027 temp << ":";
2028 temp << line;
2029 temp << " ";
2030 temp << reader->readLine(line);
2031 temp << "\n";
2032 this->OutStreamer.EmitRawText(Twine(temp.str()));
2033}
2034
2035
2036LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2037 if (reader == NULL) {
2038 reader = new LineReader(filename);
2039 }
2040
2041 if (reader->fileName() != filename) {
2042 delete reader;
2043 reader = new LineReader(filename);
2044 }
2045
2046 return reader;
2047}
2048
2049
2050std::string
2051LineReader::readLine(unsigned lineNum) {
2052 if (lineNum < theCurLine) {
2053 theCurLine = 0;
2054 fstr.seekg(0,std::ios::beg);
2055 }
2056 while (theCurLine < lineNum) {
2057 fstr.getline(buff,500);
2058 theCurLine++;
2059 }
2060 return buff;
2061}
2062
2063// Force static initialization.
2064extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2065 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2066 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2067}