blob: d3357cace24576a2d2813397699b700b9b9b345f [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
15#include "NVPTX.h"
16#include "NVPTXInstrInfo.h"
17#include "NVPTXTargetMachine.h"
18#include "NVPTXRegisterInfo.h"
19#include "NVPTXAsmPrinter.h"
20#include "MCTargetDesc/NVPTXMCAsmInfo.h"
21#include "NVPTXNumRegisters.h"
22#include "../lib/CodeGen/AsmPrinter/DwarfDebug.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/GlobalVariable.h"
25#include "llvm/Function.h"
26#include "llvm/Module.h"
27#include "llvm/CodeGen/Analysis.h"
28#include "llvm/CodeGen/MachineRegisterInfo.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineModuleInfo.h"
31#include "llvm/MC/MCStreamer.h"
32#include "llvm/MC/MCSymbol.h"
33#include "llvm/Target/Mangler.h"
34#include "llvm/Target/TargetLoweringObjectFile.h"
35#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/FormattedStream.h"
38#include "llvm/DerivedTypes.h"
39#include "NVPTXUtilities.h"
40#include "llvm/Support/TimeValue.h"
41#include <sstream>
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Analysis/DebugInfo.h"
44#include "llvm/Analysis/ConstantFolding.h"
45#include "llvm/Support/Path.h"
46#include "llvm/Assembly/Writer.h"
47#include "cl_common_defines.h"
48
49
50using namespace llvm;
51
52
53#include "NVPTXGenAsmWriter.inc"
54
55bool RegAllocNilUsed = true;
56
57#define DEPOTNAME "__local_depot"
58
59static cl::opt<bool>
60EmitLineNumbers("nvptx-emit-line-numbers",
61 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
62 cl::init(true));
63
64namespace llvm {
65bool InterleaveSrcInPtx = false;
66}
67
68static cl::opt<bool, true>InterleaveSrc("nvptx-emit-src",
69 cl::ZeroOrMore,
70 cl::desc("NVPTX Specific: Emit source line in ptx file"),
71 cl::location(llvm::InterleaveSrcInPtx));
72
73
74
75
76// @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
77// cannot just link to the existing version.
78/// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
79///
80using namespace nvptx;
81const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
82 MCContext &Ctx = AP.OutContext;
83
84 if (CV->isNullValue() || isa<UndefValue>(CV))
85 return MCConstantExpr::Create(0, Ctx);
86
87 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
88 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
89
90 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
91 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
92
93 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
94 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
95
96 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
97 if (CE == 0)
98 llvm_unreachable("Unknown constant value to lower!");
99
100
101 switch (CE->getOpcode()) {
102 default:
103 // If the code isn't optimized, there may be outstanding folding
104 // opportunities. Attempt to fold the expression using TargetData as a
105 // last resort before giving up.
106 if (Constant *C =
107 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
108 if (C != CE)
109 return LowerConstant(C, AP);
110
111 // Otherwise report the problem to the user.
112 {
113 std::string S;
114 raw_string_ostream OS(S);
115 OS << "Unsupported expression in static initializer: ";
116 WriteAsOperand(OS, CE, /*PrintType=*/false,
117 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
118 report_fatal_error(OS.str());
119 }
120 case Instruction::GetElementPtr: {
121 const TargetData &TD = *AP.TM.getTargetData();
122 // Generate a symbolic expression for the byte address
123 const Constant *PtrVal = CE->getOperand(0);
124 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
125 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
126
127 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
128 if (Offset == 0)
129 return Base;
130
131 // Truncate/sext the offset to the pointer size.
132 if (TD.getPointerSizeInBits() != 64) {
133 int SExtAmount = 64-TD.getPointerSizeInBits();
134 Offset = (Offset << SExtAmount) >> SExtAmount;
135 }
136
137 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
138 Ctx);
139 }
140
141 case Instruction::Trunc:
142 // We emit the value and depend on the assembler to truncate the generated
143 // expression properly. This is important for differences between
144 // blockaddress labels. Since the two labels are in the same function, it
145 // is reasonable to treat their delta as a 32-bit value.
146 // FALL THROUGH.
147 case Instruction::BitCast:
148 return LowerConstant(CE->getOperand(0), AP);
149
150 case Instruction::IntToPtr: {
151 const TargetData &TD = *AP.TM.getTargetData();
152 // Handle casts to pointers by changing them into casts to the appropriate
153 // integer type. This promotes constant folding and simplifies this code.
154 Constant *Op = CE->getOperand(0);
155 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
156 false/*ZExt*/);
157 return LowerConstant(Op, AP);
158 }
159
160 case Instruction::PtrToInt: {
161 const TargetData &TD = *AP.TM.getTargetData();
162 // Support only foldable casts to/from pointers that can be eliminated by
163 // changing the pointer to the appropriately sized integer type.
164 Constant *Op = CE->getOperand(0);
165 Type *Ty = CE->getType();
166
167 const MCExpr *OpExpr = LowerConstant(Op, AP);
168
169 // We can emit the pointer value into this slot if the slot is an
170 // integer slot equal to the size of the pointer.
171 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
172 return OpExpr;
173
174 // Otherwise the pointer is smaller than the resultant integer, mask off
175 // the high bits so we are sure to get a proper truncation if the input is
176 // a constant expr.
177 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
178 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
179 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
180 }
181
182 // The MC library also has a right-shift operator, but it isn't consistently
183 // signed or unsigned between different targets.
184 case Instruction::Add:
185 case Instruction::Sub:
186 case Instruction::Mul:
187 case Instruction::SDiv:
188 case Instruction::SRem:
189 case Instruction::Shl:
190 case Instruction::And:
191 case Instruction::Or:
192 case Instruction::Xor: {
193 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
194 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
195 switch (CE->getOpcode()) {
196 default: llvm_unreachable("Unknown binary operator constant cast expr");
197 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
198 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
199 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
200 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
201 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
202 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
203 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
204 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
205 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
206 }
207 }
208 }
209}
210
211
212void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI)
213{
214 if (!EmitLineNumbers)
215 return;
216 if (ignoreLoc(MI))
217 return;
218
219 DebugLoc curLoc = MI.getDebugLoc();
220
221 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
222 return;
223
224 if (prevDebugLoc == curLoc)
225 return;
226
227 prevDebugLoc = curLoc;
228
229 if (curLoc.isUnknown())
230 return;
231
232
233 const MachineFunction *MF = MI.getParent()->getParent();
234 //const TargetMachine &TM = MF->getTarget();
235
236 const LLVMContext &ctx = MF->getFunction()->getContext();
237 DIScope Scope(curLoc.getScope(ctx));
238
239 if (!Scope.Verify())
240 return;
241
242 StringRef fileName(Scope.getFilename());
243 StringRef dirName(Scope.getDirectory());
244 SmallString<128> FullPathName = dirName;
245 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
246 sys::path::append(FullPathName, fileName);
247 fileName = FullPathName.str();
248 }
249
250 if (filenameMap.find(fileName.str()) == filenameMap.end())
251 return;
252
253
254 // Emit the line from the source file.
255 if (llvm::InterleaveSrcInPtx)
256 this->emitSrcInText(fileName.str(), curLoc.getLine());
257
258 std::stringstream temp;
259 temp << "\t.loc " << filenameMap[fileName.str()]
260 << " " << curLoc.getLine() << " " << curLoc.getCol();
261 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
262}
263
264void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
265 SmallString<128> Str;
266 raw_svector_ostream OS(Str);
267 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
268 emitLineNumberAsDotLoc(*MI);
269 printInstruction(MI, OS);
270 OutStreamer.EmitRawText(OS.str());
271}
272
273void NVPTXAsmPrinter::printReturnValStr(const Function *F,
274 raw_ostream &O)
275{
276 const TargetData *TD = TM.getTargetData();
277 const TargetLowering *TLI = TM.getTargetLowering();
278
279 Type *Ty = F->getReturnType();
280
281 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
282
283 if (Ty->getTypeID() == Type::VoidTyID)
284 return;
285
286 O << " (";
287
288 if (isABI) {
289 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
290 unsigned size = 0;
291 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
292 size = ITy->getBitWidth();
293 if (size < 32) size = 32;
294 } else {
295 assert(Ty->isFloatingPointTy() &&
296 "Floating point type expected here");
297 size = Ty->getPrimitiveSizeInBits();
298 }
299
300 O << ".param .b" << size << " func_retval0";
301 }
302 else if (isa<PointerType>(Ty)) {
303 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
304 << " func_retval0";
305 } else {
306 if ((Ty->getTypeID() == Type::StructTyID) ||
307 isa<VectorType>(Ty)) {
308 SmallVector<EVT, 16> vtparts;
309 ComputeValueVTs(*TLI, Ty, vtparts);
310 unsigned totalsz = 0;
311 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
312 unsigned elems = 1;
313 EVT elemtype = vtparts[i];
314 if (vtparts[i].isVector()) {
315 elems = vtparts[i].getVectorNumElements();
316 elemtype = vtparts[i].getVectorElementType();
317 }
318 for (unsigned j=0, je=elems; j!=je; ++j) {
319 unsigned sz = elemtype.getSizeInBits();
320 if (elemtype.isInteger() && (sz < 8)) sz = 8;
321 totalsz += sz/8;
322 }
323 }
324 unsigned retAlignment = 0;
325 if (!llvm::getAlign(*F, 0, retAlignment))
326 retAlignment = TD->getABITypeAlignment(Ty);
327 O << ".param .align "
328 << retAlignment
329 << " .b8 func_retval0["
330 << totalsz << "]";
331 } else
332 assert(false &&
333 "Unknown return type");
334 }
335 } else {
336 SmallVector<EVT, 16> vtparts;
337 ComputeValueVTs(*TLI, Ty, vtparts);
338 unsigned idx = 0;
339 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
340 unsigned elems = 1;
341 EVT elemtype = vtparts[i];
342 if (vtparts[i].isVector()) {
343 elems = vtparts[i].getVectorNumElements();
344 elemtype = vtparts[i].getVectorElementType();
345 }
346
347 for (unsigned j=0, je=elems; j!=je; ++j) {
348 unsigned sz = elemtype.getSizeInBits();
349 if (elemtype.isInteger() && (sz < 32)) sz = 32;
350 O << ".reg .b" << sz << " func_retval" << idx;
351 if (j<je-1) O << ", ";
352 ++idx;
353 }
354 if (i < e-1)
355 O << ", ";
356 }
357 }
358 O << ") ";
359 return;
360}
361
362void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
363 raw_ostream &O) {
364 const Function *F = MF.getFunction();
365 printReturnValStr(F, O);
366}
367
368void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
369 SmallString<128> Str;
370 raw_svector_ostream O(Str);
371
372 // Set up
373 MRI = &MF->getRegInfo();
374 F = MF->getFunction();
375 emitLinkageDirective(F,O);
376 if (llvm::isKernelFunction(*F))
377 O << ".entry ";
378 else {
379 O << ".func ";
380 printReturnValStr(*MF, O);
381 }
382
383 O << *CurrentFnSym;
384
385 emitFunctionParamList(*MF, O);
386
387 if (llvm::isKernelFunction(*F))
388 emitKernelFunctionDirectives(*F, O);
389
390 OutStreamer.EmitRawText(O.str());
391
392 prevDebugLoc = DebugLoc();
393}
394
395void NVPTXAsmPrinter::EmitFunctionBodyStart() {
396 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
397 unsigned numRegClasses = TRI.getNumRegClasses();
398 VRidGlobal2LocalMap = new std::map<unsigned, unsigned>[numRegClasses+1];
399 OutStreamer.EmitRawText(StringRef("{\n"));
400 setAndEmitFunctionVirtualRegisters(*MF);
401
402 SmallString<128> Str;
403 raw_svector_ostream O(Str);
404 emitDemotedVars(MF->getFunction(), O);
405 OutStreamer.EmitRawText(O.str());
406}
407
408void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
409 OutStreamer.EmitRawText(StringRef("}\n"));
410 delete []VRidGlobal2LocalMap;
411}
412
413
414void
415NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function& F,
416 raw_ostream &O) const {
417 // If the NVVM IR has some of reqntid* specified, then output
418 // the reqntid directive, and set the unspecified ones to 1.
419 // If none of reqntid* is specified, don't output reqntid directive.
420 unsigned reqntidx, reqntidy, reqntidz;
421 bool specified = false;
422 if (llvm::getReqNTIDx(F, reqntidx) == false) reqntidx = 1;
423 else specified = true;
424 if (llvm::getReqNTIDy(F, reqntidy) == false) reqntidy = 1;
425 else specified = true;
426 if (llvm::getReqNTIDz(F, reqntidz) == false) reqntidz = 1;
427 else specified = true;
428
429 if (specified)
430 O << ".reqntid " << reqntidx << ", "
431 << reqntidy << ", " << reqntidz << "\n";
432
433 // If the NVVM IR has some of maxntid* specified, then output
434 // the maxntid directive, and set the unspecified ones to 1.
435 // If none of maxntid* is specified, don't output maxntid directive.
436 unsigned maxntidx, maxntidy, maxntidz;
437 specified = false;
438 if (llvm::getMaxNTIDx(F, maxntidx) == false) maxntidx = 1;
439 else specified = true;
440 if (llvm::getMaxNTIDy(F, maxntidy) == false) maxntidy = 1;
441 else specified = true;
442 if (llvm::getMaxNTIDz(F, maxntidz) == false) maxntidz = 1;
443 else specified = true;
444
445 if (specified)
446 O << ".maxntid " << maxntidx << ", "
447 << maxntidy << ", " << maxntidz << "\n";
448
449 unsigned mincta;
450 if (llvm::getMinCTASm(F, mincta))
451 O << ".minnctapersm " << mincta << "\n";
452}
453
454void
455NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
456 raw_ostream &O) {
457 const TargetRegisterClass * RC = MRI->getRegClass(vr);
458 unsigned id = RC->getID();
459
460 std::map<unsigned, unsigned> &regmap = VRidGlobal2LocalMap[id];
461 unsigned mapped_vr = regmap[vr];
462
463 if (!isVec) {
464 O << getNVPTXRegClassStr(RC) << mapped_vr;
465 return;
466 }
467 // Vector virtual register
468 if (getNVPTXVectorSize(RC) == 4)
469 O << "{"
470 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
471 << getNVPTXRegClassStr(RC) << mapped_vr << "_1, "
472 << getNVPTXRegClassStr(RC) << mapped_vr << "_2, "
473 << getNVPTXRegClassStr(RC) << mapped_vr << "_3"
474 << "}";
475 else if (getNVPTXVectorSize(RC) == 2)
476 O << "{"
477 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
478 << getNVPTXRegClassStr(RC) << mapped_vr << "_1"
479 << "}";
480 else
Craig Topper63663612012-05-24 07:02:50 +0000481 llvm_unreachable("Unsupported vector size");
Justin Holewinski49683f32012-05-04 20:18:50 +0000482}
483
484void
485NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
486 raw_ostream &O) {
487 getVirtualRegisterName(vr, isVec, O);
488}
489
490void NVPTXAsmPrinter::printVecModifiedImmediate(const MachineOperand &MO,
491 const char *Modifier,
492 raw_ostream &O) {
Craig Topper6fcf1292012-05-24 04:22:05 +0000493 static const char vecelem[] = {'0', '1', '2', '3', '0', '1', '2', '3'};
Justin Holewinski49683f32012-05-04 20:18:50 +0000494 int Imm = (int)MO.getImm();
495 if(0 == strcmp(Modifier, "vecelem"))
496 O << "_" << vecelem[Imm];
497 else if(0 == strcmp(Modifier, "vecv4comm1")) {
498 if((Imm < 0) || (Imm > 3))
499 O << "//";
500 }
501 else if(0 == strcmp(Modifier, "vecv4comm2")) {
502 if((Imm < 4) || (Imm > 7))
503 O << "//";
504 }
505 else if(0 == strcmp(Modifier, "vecv4pos")) {
506 if(Imm < 0) Imm = 0;
507 O << "_" << vecelem[Imm%4];
508 }
509 else if(0 == strcmp(Modifier, "vecv2comm1")) {
510 if((Imm < 0) || (Imm > 1))
511 O << "//";
512 }
513 else if(0 == strcmp(Modifier, "vecv2comm2")) {
514 if((Imm < 2) || (Imm > 3))
515 O << "//";
516 }
517 else if(0 == strcmp(Modifier, "vecv2pos")) {
518 if(Imm < 0) Imm = 0;
519 O << "_" << vecelem[Imm%2];
520 }
521 else
Craig Topper63663612012-05-24 07:02:50 +0000522 llvm_unreachable("Unknown Modifier on immediate operand");
Justin Holewinski49683f32012-05-04 20:18:50 +0000523}
524
525void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
526 raw_ostream &O, const char *Modifier) {
527 const MachineOperand &MO = MI->getOperand(opNum);
528 switch (MO.getType()) {
529 case MachineOperand::MO_Register:
530 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
531 if (MO.getReg() == NVPTX::VRDepot)
532 O << DEPOTNAME << getFunctionNumber();
533 else
534 O << getRegisterName(MO.getReg());
535 } else {
536 if (!Modifier)
537 emitVirtualRegister(MO.getReg(), false, O);
538 else {
539 if (strcmp(Modifier, "vecfull") == 0)
540 emitVirtualRegister(MO.getReg(), true, O);
541 else
Craig Topper63663612012-05-24 07:02:50 +0000542 llvm_unreachable(
Justin Holewinski49683f32012-05-04 20:18:50 +0000543 "Don't know how to handle the modifier on virtual register.");
544 }
545 }
546 return;
547
548 case MachineOperand::MO_Immediate:
549 if (!Modifier)
550 O << MO.getImm();
551 else if (strstr(Modifier, "vec") == Modifier)
552 printVecModifiedImmediate(MO, Modifier, O);
553 else
Craig Topper63663612012-05-24 07:02:50 +0000554 llvm_unreachable("Don't know how to handle modifier on immediate operand");
Justin Holewinski49683f32012-05-04 20:18:50 +0000555 return;
556
557 case MachineOperand::MO_FPImmediate:
558 printFPConstant(MO.getFPImm(), O);
559 break;
560
561 case MachineOperand::MO_GlobalAddress:
562 O << *Mang->getSymbol(MO.getGlobal());
563 break;
564
565 case MachineOperand::MO_ExternalSymbol: {
566 const char * symbname = MO.getSymbolName();
567 if (strstr(symbname, ".PARAM") == symbname) {
568 unsigned index;
569 sscanf(symbname+6, "%u[];", &index);
570 printParamName(index, O);
571 }
572 else if (strstr(symbname, ".HLPPARAM") == symbname) {
573 unsigned index;
574 sscanf(symbname+9, "%u[];", &index);
575 O << *CurrentFnSym << "_param_" << index << "_offset";
576 }
577 else
578 O << symbname;
579 break;
580 }
581
582 case MachineOperand::MO_MachineBasicBlock:
583 O << *MO.getMBB()->getSymbol();
584 return;
585
586 default:
Craig Topper63663612012-05-24 07:02:50 +0000587 llvm_unreachable("Operand type not supported.");
Justin Holewinski49683f32012-05-04 20:18:50 +0000588 }
589}
590
591void NVPTXAsmPrinter::
592printImplicitDef(const MachineInstr *MI, raw_ostream &O) const {
593#ifndef __OPTIMIZE__
594 O << "\t// Implicit def :";
595 //printOperand(MI, 0);
596 O << "\n";
597#endif
598}
599
600void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
601 raw_ostream &O, const char *Modifier) {
602 printOperand(MI, opNum, O);
603
604 if (Modifier && !strcmp(Modifier, "add")) {
605 O << ", ";
606 printOperand(MI, opNum+1, O);
607 } else {
608 if (MI->getOperand(opNum+1).isImm() &&
609 MI->getOperand(opNum+1).getImm() == 0)
610 return; // don't print ',0' or '+0'
611 O << "+";
612 printOperand(MI, opNum+1, O);
613 }
614}
615
616void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
617 raw_ostream &O, const char *Modifier)
618{
619 if (Modifier) {
620 const MachineOperand &MO = MI->getOperand(opNum);
621 int Imm = (int)MO.getImm();
622 if (!strcmp(Modifier, "volatile")) {
623 if (Imm)
624 O << ".volatile";
625 } else if (!strcmp(Modifier, "addsp")) {
626 switch (Imm) {
627 case NVPTX::PTXLdStInstCode::GLOBAL: O << ".global"; break;
628 case NVPTX::PTXLdStInstCode::SHARED: O << ".shared"; break;
629 case NVPTX::PTXLdStInstCode::LOCAL: O << ".local"; break;
630 case NVPTX::PTXLdStInstCode::PARAM: O << ".param"; break;
631 case NVPTX::PTXLdStInstCode::CONSTANT: O << ".const"; break;
632 case NVPTX::PTXLdStInstCode::GENERIC:
633 if (!nvptxSubtarget.hasGenericLdSt())
634 O << ".global";
635 break;
636 default:
637 assert("wrong value");
638 }
639 }
640 else if (!strcmp(Modifier, "sign")) {
641 if (Imm==NVPTX::PTXLdStInstCode::Signed)
642 O << "s";
643 else if (Imm==NVPTX::PTXLdStInstCode::Unsigned)
644 O << "u";
645 else
646 O << "f";
647 }
648 else if (!strcmp(Modifier, "vec")) {
649 if (Imm==NVPTX::PTXLdStInstCode::V2)
650 O << ".v2";
651 else if (Imm==NVPTX::PTXLdStInstCode::V4)
652 O << ".v4";
653 }
654 else
655 assert("unknown modifier");
656 }
657 else
658 assert("unknown modifier");
659}
660
661void NVPTXAsmPrinter::emitDeclaration (const Function *F, raw_ostream &O) {
662
663 emitLinkageDirective(F,O);
664 if (llvm::isKernelFunction(*F))
665 O << ".entry ";
666 else
667 O << ".func ";
668 printReturnValStr(F, O);
669 O << *CurrentFnSym << "\n";
670 emitFunctionParamList(F, O);
671 O << ";\n";
672}
673
674static bool usedInGlobalVarDef(const Constant *C)
675{
676 if (!C)
677 return false;
678
679 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
680 if (GV->getName().str() == "llvm.used")
681 return false;
682 return true;
683 }
684
685 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
686 ui!=ue; ++ui) {
687 const Constant *C = dyn_cast<Constant>(*ui);
688 if (usedInGlobalVarDef(C))
689 return true;
690 }
691 return false;
692}
693
694static bool usedInOneFunc(const User *U, Function const *&oneFunc)
695{
696 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
697 if (othergv->getName().str() == "llvm.used")
698 return true;
699 }
700
701 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
702 if (instr->getParent() && instr->getParent()->getParent()) {
703 const Function *curFunc = instr->getParent()->getParent();
704 if (oneFunc && (curFunc != oneFunc))
705 return false;
706 oneFunc = curFunc;
707 return true;
708 }
709 else
710 return false;
711 }
712
713 if (const MDNode *md = dyn_cast<MDNode>(U))
714 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
715 (md->getName().str() == "llvm.dbg.sp")))
716 return true;
717
718
719 for (User::const_use_iterator ui=U->use_begin(), ue=U->use_end();
720 ui!=ue; ++ui) {
721 if (usedInOneFunc(*ui, oneFunc) == false)
722 return false;
723 }
724 return true;
725}
726
727/* Find out if a global variable can be demoted to local scope.
728 * Currently, this is valid for CUDA shared variables, which have local
729 * scope and global lifetime. So the conditions to check are :
730 * 1. Is the global variable in shared address space?
731 * 2. Does it have internal linkage?
732 * 3. Is the global variable referenced only in one function?
733 */
734static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
735 if (gv->hasInternalLinkage() == false)
736 return false;
737 const PointerType *Pty = gv->getType();
738 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
739 return false;
740
741 const Function *oneFunc = 0;
742
743 bool flag = usedInOneFunc(gv, oneFunc);
744 if (flag == false)
745 return false;
746 if (!oneFunc)
747 return false;
748 f = oneFunc;
749 return true;
750}
751
752static bool useFuncSeen(const Constant *C,
753 llvm::DenseMap<const Function *, bool> &seenMap) {
754 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
755 ui!=ue; ++ui) {
756 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
757 if (useFuncSeen(cu, seenMap))
758 return true;
759 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
760 const BasicBlock *bb = I->getParent();
761 if (!bb) continue;
762 const Function *caller = bb->getParent();
763 if (!caller) continue;
764 if (seenMap.find(caller) != seenMap.end())
765 return true;
766 }
767 }
768 return false;
769}
770
771void NVPTXAsmPrinter::emitDeclarations (Module &M, raw_ostream &O) {
772 llvm::DenseMap<const Function *, bool> seenMap;
773 for (Module::const_iterator FI=M.begin(), FE=M.end();
774 FI!=FE; ++FI) {
775 const Function *F = FI;
776
777 if (F->isDeclaration()) {
778 if (F->use_empty())
779 continue;
780 if (F->getIntrinsicID())
781 continue;
782 CurrentFnSym = Mang->getSymbol(F);
783 emitDeclaration(F, O);
784 continue;
785 }
786 for (Value::const_use_iterator iter=F->use_begin(),
787 iterEnd=F->use_end(); iter!=iterEnd; ++iter) {
788 if (const Constant *C = dyn_cast<Constant>(*iter)) {
789 if (usedInGlobalVarDef(C)) {
790 // The use is in the initialization of a global variable
791 // that is a function pointer, so print a declaration
792 // for the original function
793 CurrentFnSym = Mang->getSymbol(F);
794 emitDeclaration(F, O);
795 break;
796 }
797 // Emit a declaration of this function if the function that
798 // uses this constant expr has already been seen.
799 if (useFuncSeen(C, seenMap)) {
800 CurrentFnSym = Mang->getSymbol(F);
801 emitDeclaration(F, O);
802 break;
803 }
804 }
805
806 if (!isa<Instruction>(*iter)) continue;
807 const Instruction *instr = cast<Instruction>(*iter);
808 const BasicBlock *bb = instr->getParent();
809 if (!bb) continue;
810 const Function *caller = bb->getParent();
811 if (!caller) continue;
812
813 // If a caller has already been seen, then the caller is
814 // appearing in the module before the callee. so print out
815 // a declaration for the callee.
816 if (seenMap.find(caller) != seenMap.end()) {
817 CurrentFnSym = Mang->getSymbol(F);
818 emitDeclaration(F, O);
819 break;
820 }
821 }
822 seenMap[F] = true;
823 }
824}
825
826void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
827 DebugInfoFinder DbgFinder;
828 DbgFinder.processModule(M);
829
830 unsigned i=1;
831 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
832 E = DbgFinder.compile_unit_end(); I != E; ++I) {
833 DICompileUnit DIUnit(*I);
834 StringRef Filename(DIUnit.getFilename());
835 StringRef Dirname(DIUnit.getDirectory());
836 SmallString<128> FullPathName = Dirname;
837 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
838 sys::path::append(FullPathName, Filename);
839 Filename = FullPathName.str();
840 }
841 if (filenameMap.find(Filename.str()) != filenameMap.end())
842 continue;
843 filenameMap[Filename.str()] = i;
844 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
845 ++i;
846 }
847
848 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
849 E = DbgFinder.subprogram_end(); I != E; ++I) {
850 DISubprogram SP(*I);
851 StringRef Filename(SP.getFilename());
852 StringRef Dirname(SP.getDirectory());
853 SmallString<128> FullPathName = Dirname;
854 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
855 sys::path::append(FullPathName, Filename);
856 Filename = FullPathName.str();
857 }
858 if (filenameMap.find(Filename.str()) != filenameMap.end())
859 continue;
860 filenameMap[Filename.str()] = i;
861 ++i;
862 }
863}
864
865bool NVPTXAsmPrinter::doInitialization (Module &M) {
866
867 SmallString<128> Str1;
868 raw_svector_ostream OS1(Str1);
869
870 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
871 MMI->AnalyzeModule(M);
872
873 // We need to call the parent's one explicitly.
874 //bool Result = AsmPrinter::doInitialization(M);
875
876 // Initialize TargetLoweringObjectFile.
877 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
878 .Initialize(OutContext, TM);
879
880 Mang = new Mangler(OutContext, *TM.getTargetData());
881
882 // Emit header before any dwarf directives are emitted below.
883 emitHeader(M, OS1);
884 OutStreamer.EmitRawText(OS1.str());
885
886
887 // Already commented out
888 //bool Result = AsmPrinter::doInitialization(M);
889
890
891 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
892 recordAndEmitFilenames(M);
893
894 SmallString<128> Str2;
895 raw_svector_ostream OS2(Str2);
896
897 emitDeclarations(M, OS2);
898
899 // Print out module-level global variables here.
900 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
901 I != E; ++I)
902 printModuleLevelGV(I, OS2);
903
904 OS2 << '\n';
905
906 OutStreamer.EmitRawText(OS2.str());
907 return false; // success
908}
909
910void NVPTXAsmPrinter::emitHeader (Module &M, raw_ostream &O) {
911 O << "//\n";
912 O << "// Generated by LLVM NVPTX Back-End\n";
913 O << "//\n";
914 O << "\n";
915
916 O << ".version 3.0\n";
917
918 O << ".target ";
919 O << nvptxSubtarget.getTargetName();
920
921 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
922 O << ", texmode_independent";
923 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
924 if (!nvptxSubtarget.hasDouble())
925 O << ", map_f64_to_f32";
926 }
927
928 if (MAI->doesSupportDebugInformation())
929 O << ", debug";
930
931 O << "\n";
932
933 O << ".address_size ";
934 if (nvptxSubtarget.is64Bit())
935 O << "64";
936 else
937 O << "32";
938 O << "\n";
939
940 O << "\n";
941}
942
943bool NVPTXAsmPrinter::doFinalization(Module &M) {
944 // XXX Temproarily remove global variables so that doFinalization() will not
945 // emit them again (global variables are emitted at beginning).
946
947 Module::GlobalListType &global_list = M.getGlobalList();
948 int i, n = global_list.size();
949 GlobalVariable **gv_array = new GlobalVariable* [n];
950
951 // first, back-up GlobalVariable in gv_array
952 i = 0;
953 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
954 I != E; ++I)
955 gv_array[i++] = &*I;
956
957 // second, empty global_list
958 while (!global_list.empty())
959 global_list.remove(global_list.begin());
960
961 // call doFinalization
962 bool ret = AsmPrinter::doFinalization(M);
963
964 // now we restore global variables
965 for (i = 0; i < n; i ++)
966 global_list.insert(global_list.end(), gv_array[i]);
967
968 delete[] gv_array;
969 return ret;
970
971
972 //bool Result = AsmPrinter::doFinalization(M);
973 // Instead of calling the parents doFinalization, we may
974 // clone parents doFinalization and customize here.
975 // Currently, we if NVISA out the EmitGlobals() in
976 // parent's doFinalization, which is too intrusive.
977 //
978 // Same for the doInitialization.
979 //return Result;
980}
981
982// This function emits appropriate linkage directives for
983// functions and global variables.
984//
985// extern function declaration -> .extern
986// extern function definition -> .visible
987// external global variable with init -> .visible
988// external without init -> .extern
989// appending -> not allowed, assert.
990
991void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue* V, raw_ostream &O)
992{
993 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
994 if (V->hasExternalLinkage()) {
995 if (isa<GlobalVariable>(V)) {
996 const GlobalVariable *GVar = cast<GlobalVariable>(V);
997 if (GVar) {
998 if (GVar->hasInitializer())
999 O << ".visible ";
1000 else
1001 O << ".extern ";
1002 }
1003 } else if (V->isDeclaration())
1004 O << ".extern ";
1005 else
1006 O << ".visible ";
1007 } else if (V->hasAppendingLinkage()) {
1008 std::string msg;
1009 msg.append("Error: ");
1010 msg.append("Symbol ");
1011 if (V->hasName())
1012 msg.append(V->getName().str());
1013 msg.append("has unsupported appending linkage type");
1014 llvm_unreachable(msg.c_str());
1015 }
1016 }
1017}
1018
1019
1020void NVPTXAsmPrinter::printModuleLevelGV(GlobalVariable* GVar, raw_ostream &O,
1021 bool processDemoted) {
1022
1023 // Skip meta data
1024 if (GVar->hasSection()) {
1025 if (GVar->getSection() == "llvm.metadata")
1026 return;
1027 }
1028
1029 const TargetData *TD = TM.getTargetData();
1030
1031 // GlobalVariables are always constant pointers themselves.
1032 const PointerType *PTy = GVar->getType();
1033 Type *ETy = PTy->getElementType();
1034
1035 if (GVar->hasExternalLinkage()) {
1036 if (GVar->hasInitializer())
1037 O << ".visible ";
1038 else
1039 O << ".extern ";
1040 }
1041
1042 if (llvm::isTexture(*GVar)) {
1043 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1044 return;
1045 }
1046
1047 if (llvm::isSurface(*GVar)) {
1048 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1049 return;
1050 }
1051
1052 if (GVar->isDeclaration()) {
1053 // (extern) declarations, no definition or initializer
1054 // Currently the only known declaration is for an automatic __local
1055 // (.shared) promoted to global.
1056 emitPTXGlobalVariable(GVar, O);
1057 O << ";\n";
1058 return;
1059 }
1060
1061 if (llvm::isSampler(*GVar)) {
1062 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1063
1064 Constant *Initializer = NULL;
1065 if (GVar->hasInitializer())
1066 Initializer = GVar->getInitializer();
1067 ConstantInt *CI = NULL;
1068 if (Initializer)
1069 CI = dyn_cast<ConstantInt>(Initializer);
1070 if (CI) {
1071 unsigned sample=CI->getZExtValue();
1072
1073 O << " = { ";
1074
1075 for (int i =0, addr=((sample & __CLK_ADDRESS_MASK ) >>
1076 __CLK_ADDRESS_BASE) ; i < 3 ; i++) {
1077 O << "addr_mode_" << i << " = ";
1078 switch (addr) {
1079 case 0: O << "wrap"; break;
1080 case 1: O << "clamp_to_border"; break;
1081 case 2: O << "clamp_to_edge"; break;
1082 case 3: O << "wrap"; break;
1083 case 4: O << "mirror"; break;
1084 }
1085 O <<", ";
1086 }
1087 O << "filter_mode = ";
1088 switch (( sample & __CLK_FILTER_MASK ) >> __CLK_FILTER_BASE ) {
1089 case 0: O << "nearest"; break;
1090 case 1: O << "linear"; break;
1091 case 2: assert ( 0 && "Anisotropic filtering is not supported");
1092 default: O << "nearest"; break;
1093 }
1094 if (!(( sample &__CLK_NORMALIZED_MASK ) >> __CLK_NORMALIZED_BASE)) {
1095 O << ", force_unnormalized_coords = 1";
1096 }
1097 O << " }";
1098 }
1099
1100 O << ";\n";
1101 return;
1102 }
1103
1104 if (GVar->hasPrivateLinkage()) {
1105
1106 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1107 return;
1108
1109 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1110 if (!strncmp(GVar->getName().data(), "filename", 8))
1111 return;
1112 if (GVar->use_empty())
1113 return;
1114 }
1115
1116 const Function *demotedFunc = 0;
1117 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1118 O << "// " << GVar->getName().str() << " has been demoted\n";
1119 if (localDecls.find(demotedFunc) != localDecls.end())
1120 localDecls[demotedFunc].push_back(GVar);
1121 else {
1122 std::vector<GlobalVariable *> temp;
1123 temp.push_back(GVar);
1124 localDecls[demotedFunc] = temp;
1125 }
1126 return;
1127 }
1128
1129 O << ".";
1130 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1131 if (GVar->getAlignment() == 0)
1132 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1133 else
1134 O << " .align " << GVar->getAlignment();
1135
1136
1137 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1138 O << " .";
1139 O << getPTXFundamentalTypeStr(ETy, false);
1140 O << " ";
1141 O << *Mang->getSymbol(GVar);
1142
1143 // Ptx allows variable initilization only for constant and global state
1144 // spaces.
1145 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1146 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1147 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1148 && GVar->hasInitializer()) {
1149 Constant *Initializer = GVar->getInitializer();
1150 if (!Initializer->isNullValue()) {
1151 O << " = " ;
1152 printScalarConstant(Initializer, O);
1153 }
1154 }
1155 } else {
1156 unsigned int ElementSize =0;
1157
1158 // Although PTX has direct support for struct type and array type and
1159 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1160 // targets that support these high level field accesses. Structs, arrays
1161 // and vectors are lowered into arrays of bytes.
1162 switch (ETy->getTypeID()) {
1163 case Type::StructTyID:
1164 case Type::ArrayTyID:
1165 case Type::VectorTyID:
1166 ElementSize = TD->getTypeStoreSize(ETy);
1167 // Ptx allows variable initilization only for constant and
1168 // global state spaces.
1169 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1170 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1171 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1172 && GVar->hasInitializer()) {
1173 Constant *Initializer = GVar->getInitializer();
1174 if (!isa<UndefValue>(Initializer) &&
1175 !Initializer->isNullValue()) {
1176 AggBuffer aggBuffer(ElementSize, O, *this);
1177 bufferAggregateConstant(Initializer, &aggBuffer);
1178 if (aggBuffer.numSymbols) {
1179 if (nvptxSubtarget.is64Bit()) {
1180 O << " .u64 " << *Mang->getSymbol(GVar) <<"[" ;
1181 O << ElementSize/8;
1182 }
1183 else {
1184 O << " .u32 " << *Mang->getSymbol(GVar) <<"[" ;
1185 O << ElementSize/4;
1186 }
1187 O << "]";
1188 }
1189 else {
1190 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1191 O << ElementSize;
1192 O << "]";
1193 }
1194 O << " = {" ;
1195 aggBuffer.print();
1196 O << "}";
1197 }
1198 else {
1199 O << " .b8 " << *Mang->getSymbol(GVar) ;
1200 if (ElementSize) {
1201 O <<"[" ;
1202 O << ElementSize;
1203 O << "]";
1204 }
1205 }
1206 }
1207 else {
1208 O << " .b8 " << *Mang->getSymbol(GVar);
1209 if (ElementSize) {
1210 O <<"[" ;
1211 O << ElementSize;
1212 O << "]";
1213 }
1214 }
1215 break;
1216 default:
1217 assert( 0 && "type not supported yet");
1218 }
1219
1220 }
1221 O << ";\n";
1222}
1223
1224void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1225 if (localDecls.find(f) == localDecls.end())
1226 return;
1227
1228 std::vector<GlobalVariable *> &gvars = localDecls[f];
1229
1230 for (unsigned i=0, e=gvars.size(); i!=e; ++i) {
1231 O << "\t// demoted variable\n\t";
1232 printModuleLevelGV(gvars[i], O, true);
1233 }
1234}
1235
1236void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1237 raw_ostream &O) const {
1238 switch (AddressSpace) {
1239 case llvm::ADDRESS_SPACE_LOCAL:
1240 O << "local" ;
1241 break;
1242 case llvm::ADDRESS_SPACE_GLOBAL:
1243 O << "global" ;
1244 break;
1245 case llvm::ADDRESS_SPACE_CONST:
1246 // This logic should be consistent with that in
1247 // getCodeAddrSpace() (NVPTXISelDATToDAT.cpp)
1248 if (nvptxSubtarget.hasGenericLdSt())
1249 O << "global" ;
1250 else
1251 O << "const" ;
1252 break;
1253 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1254 O << "const" ;
1255 break;
1256 case llvm::ADDRESS_SPACE_SHARED:
1257 O << "shared" ;
1258 break;
1259 default:
Craig Topper63663612012-05-24 07:02:50 +00001260 llvm_unreachable("unexpected address space");
Justin Holewinski49683f32012-05-04 20:18:50 +00001261 }
1262}
1263
1264std::string NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty,
1265 bool useB4PTR) const {
1266 switch (Ty->getTypeID()) {
1267 default:
1268 llvm_unreachable("unexpected type");
1269 break;
1270 case Type::IntegerTyID: {
1271 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1272 if (NumBits == 1)
1273 return "pred";
1274 else if (NumBits <= 64) {
1275 std::string name = "u";
1276 return name + utostr(NumBits);
1277 } else {
1278 llvm_unreachable("Integer too large");
1279 break;
1280 }
1281 break;
1282 }
1283 case Type::FloatTyID:
1284 return "f32";
1285 case Type::DoubleTyID:
1286 return "f64";
1287 case Type::PointerTyID:
1288 if (nvptxSubtarget.is64Bit())
1289 if (useB4PTR) return "b64";
1290 else return "u64";
1291 else
1292 if (useB4PTR) return "b32";
1293 else return "u32";
1294 }
1295 llvm_unreachable("unexpected type");
1296 return NULL;
1297}
1298
1299void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable* GVar,
1300 raw_ostream &O) {
1301
1302 const TargetData *TD = TM.getTargetData();
1303
1304 // GlobalVariables are always constant pointers themselves.
1305 const PointerType *PTy = GVar->getType();
1306 Type *ETy = PTy->getElementType();
1307
1308 O << ".";
1309 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1310 if (GVar->getAlignment() == 0)
1311 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1312 else
1313 O << " .align " << GVar->getAlignment();
1314
1315 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1316 O << " .";
1317 O << getPTXFundamentalTypeStr(ETy);
1318 O << " ";
1319 O << *Mang->getSymbol(GVar);
1320 return;
1321 }
1322
1323 int64_t ElementSize =0;
1324
1325 // Although PTX has direct support for struct type and array type and LLVM IR
1326 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1327 // support these high level field accesses. Structs and arrays are lowered
1328 // into arrays of bytes.
1329 switch (ETy->getTypeID()) {
1330 case Type::StructTyID:
1331 case Type::ArrayTyID:
1332 case Type::VectorTyID:
1333 ElementSize = TD->getTypeStoreSize(ETy);
1334 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1335 if (ElementSize) {
1336 O << itostr(ElementSize) ;
1337 }
1338 O << "]";
1339 break;
1340 default:
1341 assert( 0 && "type not supported yet");
1342 }
1343 return ;
1344}
1345
1346
1347static unsigned int
1348getOpenCLAlignment(const TargetData *TD,
1349 Type *Ty) {
1350 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1351 return TD->getPrefTypeAlignment(Ty);
1352
1353 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1354 if (ATy)
1355 return getOpenCLAlignment(TD, ATy->getElementType());
1356
1357 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1358 if (VTy) {
1359 Type *ETy = VTy->getElementType();
1360 unsigned int numE = VTy->getNumElements();
1361 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1362 if (numE == 3)
1363 return 4*alignE;
1364 else
1365 return numE*alignE;
1366 }
1367
1368 const StructType *STy = dyn_cast<StructType>(Ty);
1369 if (STy) {
1370 unsigned int alignStruct = 1;
1371 // Go through each element of the struct and find the
1372 // largest alignment.
1373 for (unsigned i=0, e=STy->getNumElements(); i != e; i++) {
1374 Type *ETy = STy->getElementType(i);
1375 unsigned int align = getOpenCLAlignment(TD, ETy);
1376 if (align > alignStruct)
1377 alignStruct = align;
1378 }
1379 return alignStruct;
1380 }
1381
1382 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1383 if (FTy)
1384 return TD->getPointerPrefAlignment();
1385 return TD->getPrefTypeAlignment(Ty);
1386}
1387
1388void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1389 int paramIndex, raw_ostream &O) {
1390 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1391 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1392 O << *CurrentFnSym << "_param_" << paramIndex;
1393 else {
1394 std::string argName = I->getName();
1395 const char *p = argName.c_str();
1396 while (*p) {
1397 if (*p == '.')
1398 O << "_";
1399 else
1400 O << *p;
1401 p++;
1402 }
1403 }
1404}
1405
1406void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1407 Function::const_arg_iterator I, E;
1408 int i = 0;
1409
1410 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1411 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1412 O << *CurrentFnSym << "_param_" << paramIndex;
1413 return;
1414 }
1415
1416 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1417 if (i==paramIndex) {
1418 printParamName(I, paramIndex, O);
1419 return;
1420 }
1421 }
1422 llvm_unreachable("paramIndex out of bound");
1423}
1424
1425void NVPTXAsmPrinter::emitFunctionParamList(const Function *F,
1426 raw_ostream &O) {
1427 const TargetData *TD = TM.getTargetData();
1428 const AttrListPtr &PAL = F->getAttributes();
1429 const TargetLowering *TLI = TM.getTargetLowering();
1430 Function::const_arg_iterator I, E;
1431 unsigned paramIndex = 0;
1432 bool first = true;
1433 bool isKernelFunc = llvm::isKernelFunction(*F);
1434 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1435 MVT thePointerTy = TLI->getPointerTy();
1436
1437 O << "(\n";
1438
1439 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1440 const Type *Ty = I->getType();
1441
1442 if (!first)
1443 O << ",\n";
1444
1445 first = false;
1446
1447 // Handle image/sampler parameters
1448 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1449 if (llvm::isImage(*I)) {
1450 std::string sname = I->getName();
1451 if (llvm::isImageWriteOnly(*I))
1452 O << "\t.param .surfref " << *CurrentFnSym << "_param_" << paramIndex;
1453 else // Default image is read_only
1454 O << "\t.param .texref " << *CurrentFnSym << "_param_" << paramIndex;
1455 }
1456 else // Should be llvm::isSampler(*I)
1457 O << "\t.param .samplerref " << *CurrentFnSym << "_param_"
1458 << paramIndex;
1459 continue;
1460 }
1461
1462 if (PAL.paramHasAttr(paramIndex+1, Attribute::ByVal) == false) {
1463 // 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
1720 const TargetData *TD = TM.getTargetData();
1721
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) {
1849 const TargetData *TD = TM.getTargetData();
1850 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}