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