LLVM  9.0.0svn
NVPTXAsmPrinter.cpp
Go to the documentation of this file.
1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a printer that converts from our internal representation
10 // of machine-dependent LLVM code to NVPTX assembly language.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "NVPTXAsmPrinter.h"
19 #include "NVPTX.h"
20 #include "NVPTXMCExpr.h"
22 #include "NVPTXRegisterInfo.h"
23 #include "NVPTXSubtarget.h"
24 #include "NVPTXTargetMachine.h"
25 #include "NVPTXUtilities.h"
26 #include "cl_common_defines.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/ADT/Triple.h"
36 #include "llvm/ADT/Twine.h"
38 #include "llvm/CodeGen/Analysis.h"
50 #include "llvm/IR/Attributes.h"
51 #include "llvm/IR/BasicBlock.h"
52 #include "llvm/IR/Constant.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DebugInfo.h"
57 #include "llvm/IR/DebugLoc.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GlobalValue.h"
61 #include "llvm/IR/GlobalVariable.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/LLVMContext.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/Operator.h"
66 #include "llvm/IR/Type.h"
67 #include "llvm/IR/User.h"
68 #include "llvm/MC/MCExpr.h"
69 #include "llvm/MC/MCInst.h"
70 #include "llvm/MC/MCInstrDesc.h"
71 #include "llvm/MC/MCStreamer.h"
72 #include "llvm/MC/MCSymbol.h"
73 #include "llvm/Support/Casting.h"
77 #include "llvm/Support/Path.h"
83 #include <cassert>
84 #include <cstdint>
85 #include <cstring>
86 #include <new>
87 #include <string>
88 #include <utility>
89 #include <vector>
90 
91 using namespace llvm;
92 
93 #define DEPOTNAME "__local_depot"
94 
95 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
96 /// depends.
97 static void
100  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
101  Globals.insert(GV);
102  else {
103  if (const User *U = dyn_cast<User>(V)) {
104  for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
105  DiscoverDependentGlobals(U->getOperand(i), Globals);
106  }
107  }
108  }
109 }
110 
111 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
112 /// instances to be emitted, but only after any dependents have been added
113 /// first.s
114 static void
119  // Have we already visited this one?
120  if (Visited.count(GV))
121  return;
122 
123  // Do we have a circular dependency?
124  if (!Visiting.insert(GV).second)
125  report_fatal_error("Circular dependency found in global variable set");
126 
127  // Make sure we visit all dependents first
129  for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
130  DiscoverDependentGlobals(GV->getOperand(i), Others);
131 
133  E = Others.end();
134  I != E; ++I)
135  VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
136 
137  // Now we can visit ourself
138  Order.push_back(GV);
139  Visited.insert(GV);
140  Visiting.erase(GV);
141 }
142 
143 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
144  MCInst Inst;
145  lowerToMCInst(MI, Inst);
146  EmitToStreamer(*OutStreamer, Inst);
147 }
148 
149 // Handle symbol backtracking for targets that do not support image handles
150 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
151  unsigned OpNo, MCOperand &MCOp) {
152  const MachineOperand &MO = MI->getOperand(OpNo);
153  const MCInstrDesc &MCID = MI->getDesc();
154 
155  if (MCID.TSFlags & NVPTXII::IsTexFlag) {
156  // This is a texture fetch, so operand 4 is a texref and operand 5 is
157  // a samplerref
158  if (OpNo == 4 && MO.isImm()) {
159  lowerImageHandleSymbol(MO.getImm(), MCOp);
160  return true;
161  }
162  if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
163  lowerImageHandleSymbol(MO.getImm(), MCOp);
164  return true;
165  }
166 
167  return false;
168  } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
169  unsigned VecSize =
170  1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
171 
172  // For a surface load of vector size N, the Nth operand will be the surfref
173  if (OpNo == VecSize && MO.isImm()) {
174  lowerImageHandleSymbol(MO.getImm(), MCOp);
175  return true;
176  }
177 
178  return false;
179  } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
180  // This is a surface store, so operand 0 is a surfref
181  if (OpNo == 0 && MO.isImm()) {
182  lowerImageHandleSymbol(MO.getImm(), MCOp);
183  return true;
184  }
185 
186  return false;
187  } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
188  // This is a query, so operand 1 is a surfref/texref
189  if (OpNo == 1 && MO.isImm()) {
190  lowerImageHandleSymbol(MO.getImm(), MCOp);
191  return true;
192  }
193 
194  return false;
195  }
196 
197  return false;
198 }
199 
200 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
201  // Ewwww
202  LLVMTargetMachine &TM = const_cast<LLVMTargetMachine&>(MF->getTarget());
203  NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
205  const char *Sym = MFI->getImageHandleSymbol(Index);
206  std::string *SymNamePtr =
207  nvTM.getManagedStrPool()->getManagedString(Sym);
208  MCOp = GetSymbolRef(OutContext.getOrCreateSymbol(StringRef(*SymNamePtr)));
209 }
210 
211 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
212  OutMI.setOpcode(MI->getOpcode());
213  // Special: Do not mangle symbol operand of CALL_PROTOTYPE
214  if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
215  const MachineOperand &MO = MI->getOperand(0);
216  OutMI.addOperand(GetSymbolRef(
218  return;
219  }
220 
221  const NVPTXSubtarget &STI = MI->getMF()->getSubtarget<NVPTXSubtarget>();
222  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
223  const MachineOperand &MO = MI->getOperand(i);
224 
225  MCOperand MCOp;
226  if (!STI.hasImageHandles()) {
227  if (lowerImageHandleOperand(MI, i, MCOp)) {
228  OutMI.addOperand(MCOp);
229  continue;
230  }
231  }
232 
233  if (lowerOperand(MO, MCOp))
234  OutMI.addOperand(MCOp);
235  }
236 }
237 
238 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
239  MCOperand &MCOp) {
240  switch (MO.getType()) {
241  default: llvm_unreachable("unknown operand type");
243  MCOp = MCOperand::createReg(encodeVirtualRegister(MO.getReg()));
244  break;
246  MCOp = MCOperand::createImm(MO.getImm());
247  break;
250  MO.getMBB()->getSymbol(), OutContext));
251  break;
254  break;
256  MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
257  break;
259  const ConstantFP *Cnt = MO.getFPImm();
260  const APFloat &Val = Cnt->getValueAPF();
261 
262  switch (Cnt->getType()->getTypeID()) {
263  default: report_fatal_error("Unsupported FP type"); break;
264  case Type::HalfTyID:
265  MCOp = MCOperand::createExpr(
267  break;
268  case Type::FloatTyID:
269  MCOp = MCOperand::createExpr(
271  break;
272  case Type::DoubleTyID:
273  MCOp = MCOperand::createExpr(
275  break;
276  }
277  break;
278  }
279  }
280  return true;
281 }
282 
283 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
285  const TargetRegisterClass *RC = MRI->getRegClass(Reg);
286 
287  DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
288  unsigned RegNum = RegMap[Reg];
289 
290  // Encode the register class in the upper 4 bits
291  // Must be kept in sync with NVPTXInstPrinter::printRegName
292  unsigned Ret = 0;
293  if (RC == &NVPTX::Int1RegsRegClass) {
294  Ret = (1 << 28);
295  } else if (RC == &NVPTX::Int16RegsRegClass) {
296  Ret = (2 << 28);
297  } else if (RC == &NVPTX::Int32RegsRegClass) {
298  Ret = (3 << 28);
299  } else if (RC == &NVPTX::Int64RegsRegClass) {
300  Ret = (4 << 28);
301  } else if (RC == &NVPTX::Float32RegsRegClass) {
302  Ret = (5 << 28);
303  } else if (RC == &NVPTX::Float64RegsRegClass) {
304  Ret = (6 << 28);
305  } else if (RC == &NVPTX::Float16RegsRegClass) {
306  Ret = (7 << 28);
307  } else if (RC == &NVPTX::Float16x2RegsRegClass) {
308  Ret = (8 << 28);
309  } else {
310  report_fatal_error("Bad register class");
311  }
312 
313  // Insert the vreg number
314  Ret |= (RegNum & 0x0FFFFFFF);
315  return Ret;
316  } else {
317  // Some special-use registers are actually physical registers.
318  // Encode this as the register class ID of 0 and the real register ID.
319  return Reg & 0x0FFFFFFF;
320  }
321 }
322 
324  const MCExpr *Expr;
326  OutContext);
327  return MCOperand::createExpr(Expr);
328 }
329 
330 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
331  const DataLayout &DL = getDataLayout();
332  const NVPTXSubtarget &STI = TM.getSubtarget<NVPTXSubtarget>(*F);
333  const TargetLowering *TLI = STI.getTargetLowering();
334 
335  Type *Ty = F->getReturnType();
336 
337  bool isABI = (STI.getSmVersion() >= 20);
338 
339  if (Ty->getTypeID() == Type::VoidTyID)
340  return;
341 
342  O << " (";
343 
344  if (isABI) {
345  if (Ty->isFloatingPointTy() || (Ty->isIntegerTy() && !Ty->isIntegerTy(128))) {
346  unsigned size = 0;
347  if (auto *ITy = dyn_cast<IntegerType>(Ty)) {
348  size = ITy->getBitWidth();
349  } else {
350  assert(Ty->isFloatingPointTy() && "Floating point type expected here");
351  size = Ty->getPrimitiveSizeInBits();
352  }
353  // PTX ABI requires all scalar return values to be at least 32
354  // bits in size. fp16 normally uses .b16 as its storage type in
355  // PTX, so its size must be adjusted here, too.
356  if (size < 32)
357  size = 32;
358 
359  O << ".param .b" << size << " func_retval0";
360  } else if (isa<PointerType>(Ty)) {
361  O << ".param .b" << TLI->getPointerTy(DL).getSizeInBits()
362  << " func_retval0";
363  } else if (Ty->isAggregateType() || Ty->isVectorTy() || Ty->isIntegerTy(128)) {
364  unsigned totalsz = DL.getTypeAllocSize(Ty);
365  unsigned retAlignment = 0;
366  if (!getAlign(*F, 0, retAlignment))
367  retAlignment = DL.getABITypeAlignment(Ty);
368  O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
369  << "]";
370  } else
371  llvm_unreachable("Unknown return type");
372  } else {
373  SmallVector<EVT, 16> vtparts;
374  ComputeValueVTs(*TLI, DL, Ty, vtparts);
375  unsigned idx = 0;
376  for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
377  unsigned elems = 1;
378  EVT elemtype = vtparts[i];
379  if (vtparts[i].isVector()) {
380  elems = vtparts[i].getVectorNumElements();
381  elemtype = vtparts[i].getVectorElementType();
382  }
383 
384  for (unsigned j = 0, je = elems; j != je; ++j) {
385  unsigned sz = elemtype.getSizeInBits();
386  if (elemtype.isInteger() && (sz < 32))
387  sz = 32;
388  O << ".reg .b" << sz << " func_retval" << idx;
389  if (j < je - 1)
390  O << ", ";
391  ++idx;
392  }
393  if (i < e - 1)
394  O << ", ";
395  }
396  }
397  O << ") ";
398 }
399 
400 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
401  raw_ostream &O) {
402  const Function &F = MF.getFunction();
403  printReturnValStr(&F, O);
404 }
405 
406 // Return true if MBB is the header of a loop marked with
407 // llvm.loop.unroll.disable.
408 // TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
409 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
410  const MachineBasicBlock &MBB) const {
411  MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
412  // We insert .pragma "nounroll" only to the loop header.
413  if (!LI.isLoopHeader(&MBB))
414  return false;
415 
416  // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
417  // we iterate through each back edge of the loop with header MBB, and check
418  // whether its metadata contains llvm.loop.unroll.disable.
419  for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
420  const MachineBasicBlock *PMBB = *I;
421  if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
422  // Edges from other loops to MBB are not back edges.
423  continue;
424  }
425  if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
426  if (MDNode *LoopID =
427  PBB->getTerminator()->getMetadata(LLVMContext::MD_loop)) {
428  if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
429  return true;
430  }
431  }
432  }
433  return false;
434 }
435 
436 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
438  if (isLoopHeaderOfNoUnroll(MBB))
439  OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
440 }
441 
442 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
443  SmallString<128> Str;
444  raw_svector_ostream O(Str);
445 
446  if (!GlobalsEmitted) {
447  emitGlobals(*MF->getFunction().getParent());
448  GlobalsEmitted = true;
449  }
450 
451  // Set up
452  MRI = &MF->getRegInfo();
453  F = &MF->getFunction();
454  emitLinkageDirective(F, O);
455  if (isKernelFunction(*F))
456  O << ".entry ";
457  else {
458  O << ".func ";
459  printReturnValStr(*MF, O);
460  }
461 
462  CurrentFnSym->print(O, MAI);
463 
464  emitFunctionParamList(*MF, O);
465 
466  if (isKernelFunction(*F))
467  emitKernelFunctionDirectives(*F, O);
468 
469  OutStreamer->EmitRawText(O.str());
470 
471  VRegMapping.clear();
472  // Emit open brace for function body.
473  OutStreamer->EmitRawText(StringRef("{\n"));
474  setAndEmitFunctionVirtualRegisters(*MF);
475 }
476 
478  bool Result = AsmPrinter::runOnMachineFunction(F);
479  // Emit closing brace for the body of function F.
480  // The closing brace must be emitted here because we need to emit additional
481  // debug labels/data after the last basic block.
482  // We need to emit the closing brace here because we don't have function that
483  // finished emission of the function body.
484  OutStreamer->EmitRawText(StringRef("}\n"));
485  return Result;
486 }
487 
488 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
489  SmallString<128> Str;
490  raw_svector_ostream O(Str);
491  emitDemotedVars(&MF->getFunction(), O);
492  OutStreamer->EmitRawText(O.str());
493 }
494 
495 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
496  VRegMapping.clear();
497 }
498 
500  SmallString<128> Str;
502  return OutContext.getOrCreateSymbol(Str);
503 }
504 
505 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
506  unsigned RegNo = MI->getOperand(0).getReg();
508  OutStreamer->AddComment(Twine("implicit-def: ") +
509  getVirtualRegisterName(RegNo));
510  } else {
511  const NVPTXSubtarget &STI = MI->getMF()->getSubtarget<NVPTXSubtarget>();
512  OutStreamer->AddComment(Twine("implicit-def: ") +
513  STI.getRegisterInfo()->getName(RegNo));
514  }
515  OutStreamer->AddBlankLine();
516 }
517 
518 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
519  raw_ostream &O) const {
520  // If the NVVM IR has some of reqntid* specified, then output
521  // the reqntid directive, and set the unspecified ones to 1.
522  // If none of reqntid* is specified, don't output reqntid directive.
523  unsigned reqntidx, reqntidy, reqntidz;
524  bool specified = false;
525  if (!getReqNTIDx(F, reqntidx))
526  reqntidx = 1;
527  else
528  specified = true;
529  if (!getReqNTIDy(F, reqntidy))
530  reqntidy = 1;
531  else
532  specified = true;
533  if (!getReqNTIDz(F, reqntidz))
534  reqntidz = 1;
535  else
536  specified = true;
537 
538  if (specified)
539  O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
540  << "\n";
541 
542  // If the NVVM IR has some of maxntid* specified, then output
543  // the maxntid directive, and set the unspecified ones to 1.
544  // If none of maxntid* is specified, don't output maxntid directive.
545  unsigned maxntidx, maxntidy, maxntidz;
546  specified = false;
547  if (!getMaxNTIDx(F, maxntidx))
548  maxntidx = 1;
549  else
550  specified = true;
551  if (!getMaxNTIDy(F, maxntidy))
552  maxntidy = 1;
553  else
554  specified = true;
555  if (!getMaxNTIDz(F, maxntidz))
556  maxntidz = 1;
557  else
558  specified = true;
559 
560  if (specified)
561  O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
562  << "\n";
563 
564  unsigned mincta;
565  if (getMinCTASm(F, mincta))
566  O << ".minnctapersm " << mincta << "\n";
567 
568  unsigned maxnreg;
569  if (getMaxNReg(F, maxnreg))
570  O << ".maxnreg " << maxnreg << "\n";
571 }
572 
573 std::string
575  const TargetRegisterClass *RC = MRI->getRegClass(Reg);
576 
577  std::string Name;
578  raw_string_ostream NameStr(Name);
579 
580  VRegRCMap::const_iterator I = VRegMapping.find(RC);
581  assert(I != VRegMapping.end() && "Bad register class");
582  const DenseMap<unsigned, unsigned> &RegMap = I->second;
583 
584  VRegMap::const_iterator VI = RegMap.find(Reg);
585  assert(VI != RegMap.end() && "Bad virtual register");
586  unsigned MappedVR = VI->second;
587 
588  NameStr << getNVPTXRegClassStr(RC) << MappedVR;
589 
590  NameStr.flush();
591  return Name;
592 }
593 
594 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
595  raw_ostream &O) {
596  O << getVirtualRegisterName(vr);
597 }
598 
599 void NVPTXAsmPrinter::printVecModifiedImmediate(
600  const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
601  static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
602  int Imm = (int) MO.getImm();
603  if (0 == strcmp(Modifier, "vecelem"))
604  O << "_" << vecelem[Imm];
605  else if (0 == strcmp(Modifier, "vecv4comm1")) {
606  if ((Imm < 0) || (Imm > 3))
607  O << "//";
608  } else if (0 == strcmp(Modifier, "vecv4comm2")) {
609  if ((Imm < 4) || (Imm > 7))
610  O << "//";
611  } else if (0 == strcmp(Modifier, "vecv4pos")) {
612  if (Imm < 0)
613  Imm = 0;
614  O << "_" << vecelem[Imm % 4];
615  } else if (0 == strcmp(Modifier, "vecv2comm1")) {
616  if ((Imm < 0) || (Imm > 1))
617  O << "//";
618  } else if (0 == strcmp(Modifier, "vecv2comm2")) {
619  if ((Imm < 2) || (Imm > 3))
620  O << "//";
621  } else if (0 == strcmp(Modifier, "vecv2pos")) {
622  if (Imm < 0)
623  Imm = 0;
624  O << "_" << vecelem[Imm % 2];
625  } else
626  llvm_unreachable("Unknown Modifier on immediate operand");
627 }
628 
629 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
630  emitLinkageDirective(F, O);
631  if (isKernelFunction(*F))
632  O << ".entry ";
633  else
634  O << ".func ";
635  printReturnValStr(F, O);
636  getSymbol(F)->print(O, MAI);
637  O << "\n";
638  emitFunctionParamList(F, O);
639  O << ";\n";
640 }
641 
642 static bool usedInGlobalVarDef(const Constant *C) {
643  if (!C)
644  return false;
645 
646  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
647  return GV->getName() != "llvm.used";
648  }
649 
650  for (const User *U : C->users())
651  if (const Constant *C = dyn_cast<Constant>(U))
652  if (usedInGlobalVarDef(C))
653  return true;
654 
655  return false;
656 }
657 
658 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
659  if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
660  if (othergv->getName() == "llvm.used")
661  return true;
662  }
663 
664  if (const Instruction *instr = dyn_cast<Instruction>(U)) {
665  if (instr->getParent() && instr->getParent()->getParent()) {
666  const Function *curFunc = instr->getParent()->getParent();
667  if (oneFunc && (curFunc != oneFunc))
668  return false;
669  oneFunc = curFunc;
670  return true;
671  } else
672  return false;
673  }
674 
675  for (const User *UU : U->users())
676  if (!usedInOneFunc(UU, oneFunc))
677  return false;
678 
679  return true;
680 }
681 
682 /* Find out if a global variable can be demoted to local scope.
683  * Currently, this is valid for CUDA shared variables, which have local
684  * scope and global lifetime. So the conditions to check are :
685  * 1. Is the global variable in shared address space?
686  * 2. Does it have internal linkage?
687  * 3. Is the global variable referenced only in one function?
688  */
689 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
690  if (!gv->hasInternalLinkage())
691  return false;
692  PointerType *Pty = gv->getType();
694  return false;
695 
696  const Function *oneFunc = nullptr;
697 
698  bool flag = usedInOneFunc(gv, oneFunc);
699  if (!flag)
700  return false;
701  if (!oneFunc)
702  return false;
703  f = oneFunc;
704  return true;
705 }
706 
707 static bool useFuncSeen(const Constant *C,
709  for (const User *U : C->users()) {
710  if (const Constant *cu = dyn_cast<Constant>(U)) {
711  if (useFuncSeen(cu, seenMap))
712  return true;
713  } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
714  const BasicBlock *bb = I->getParent();
715  if (!bb)
716  continue;
717  const Function *caller = bb->getParent();
718  if (!caller)
719  continue;
720  if (seenMap.find(caller) != seenMap.end())
721  return true;
722  }
723  }
724  return false;
725 }
726 
727 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
729  for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
730  const Function *F = &*FI;
731 
732  if (F->getAttributes().hasFnAttribute("nvptx-libcall-callee")) {
733  emitDeclaration(F, O);
734  continue;
735  }
736 
737  if (F->isDeclaration()) {
738  if (F->use_empty())
739  continue;
740  if (F->getIntrinsicID())
741  continue;
742  emitDeclaration(F, O);
743  continue;
744  }
745  for (const User *U : F->users()) {
746  if (const Constant *C = dyn_cast<Constant>(U)) {
747  if (usedInGlobalVarDef(C)) {
748  // The use is in the initialization of a global variable
749  // that is a function pointer, so print a declaration
750  // for the original function
751  emitDeclaration(F, O);
752  break;
753  }
754  // Emit a declaration of this function if the function that
755  // uses this constant expr has already been seen.
756  if (useFuncSeen(C, seenMap)) {
757  emitDeclaration(F, O);
758  break;
759  }
760  }
761 
762  if (!isa<Instruction>(U))
763  continue;
764  const Instruction *instr = cast<Instruction>(U);
765  const BasicBlock *bb = instr->getParent();
766  if (!bb)
767  continue;
768  const Function *caller = bb->getParent();
769  if (!caller)
770  continue;
771 
772  // If a caller has already been seen, then the caller is
773  // appearing in the module before the callee. so print out
774  // a declaration for the callee.
775  if (seenMap.find(caller) != seenMap.end()) {
776  emitDeclaration(F, O);
777  break;
778  }
779  }
780  seenMap[F] = true;
781  }
782 }
783 
785  if (!GV) return true;
786  const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
787  if (!InitList) return true; // Not an array; we don't know how to parse.
788  return InitList->getNumOperands() == 0;
789 }
790 
792  // Construct a default subtarget off of the TargetMachine defaults. The
793  // rest of NVPTX isn't friendly to change subtargets per function and
794  // so the default TargetMachine will have all of the options.
795  const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
796  const auto* STI = static_cast<const NVPTXSubtarget*>(NTM.getSubtargetImpl());
797 
798  if (M.alias_size()) {
799  report_fatal_error("Module has aliases, which NVPTX does not support.");
800  return true; // error
801  }
802  if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_ctors"))) {
804  "Module has a nontrivial global ctor, which NVPTX does not support.");
805  return true; // error
806  }
807  if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_dtors"))) {
809  "Module has a nontrivial global dtor, which NVPTX does not support.");
810  return true; // error
811  }
812 
813  SmallString<128> Str1;
814  raw_svector_ostream OS1(Str1);
815 
816  // We need to call the parent's one explicitly.
817  bool Result = AsmPrinter::doInitialization(M);
818 
819  // Emit header before any dwarf directives are emitted below.
820  emitHeader(M, OS1, *STI);
821  OutStreamer->EmitRawText(OS1.str());
822 
823  // Emit module-level inline asm if it exists.
824  if (!M.getModuleInlineAsm().empty()) {
825  OutStreamer->AddComment("Start of file scope inline assembly");
826  OutStreamer->AddBlankLine();
827  OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
828  OutStreamer->AddBlankLine();
829  OutStreamer->AddComment("End of file scope inline assembly");
830  OutStreamer->AddBlankLine();
831  }
832 
833  GlobalsEmitted = false;
834 
835  return Result;
836 }
837 
838 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
839  SmallString<128> Str2;
840  raw_svector_ostream OS2(Str2);
841 
842  emitDeclarations(M, OS2);
843 
844  // As ptxas does not support forward references of globals, we need to first
845  // sort the list of module-level globals in def-use order. We visit each
846  // global variable in order, and ensure that we emit it *after* its dependent
847  // globals. We use a little extra memory maintaining both a set and a list to
848  // have fast searches while maintaining a strict ordering.
852 
853  // Visit each global variable, in order
854  for (const GlobalVariable &I : M.globals())
855  VisitGlobalVariableForEmission(&I, Globals, GVVisited, GVVisiting);
856 
857  assert(GVVisited.size() == M.getGlobalList().size() &&
858  "Missed a global variable");
859  assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
860 
861  // Print out module-level global variables in proper order
862  for (unsigned i = 0, e = Globals.size(); i != e; ++i)
863  printModuleLevelGV(Globals[i], OS2);
864 
865  OS2 << '\n';
866 
867  OutStreamer->EmitRawText(OS2.str());
868 }
869 
870 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
871  const NVPTXSubtarget &STI) {
872  O << "//\n";
873  O << "// Generated by LLVM NVPTX Back-End\n";
874  O << "//\n";
875  O << "\n";
876 
877  unsigned PTXVersion = STI.getPTXVersion();
878  O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
879 
880  O << ".target ";
881  O << STI.getTargetName();
882 
883  const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
884  if (NTM.getDrvInterface() == NVPTX::NVCL)
885  O << ", texmode_independent";
886 
887  bool HasFullDebugInfo = false;
888  for (DICompileUnit *CU : M.debug_compile_units()) {
889  switch(CU->getEmissionKind()) {
892  break;
895  HasFullDebugInfo = true;
896  break;
897  }
898  if (HasFullDebugInfo)
899  break;
900  }
901  // FIXME: remove comment once debug info is properly supported.
902  if (MMI && MMI->hasDebugInfo() && HasFullDebugInfo)
903  O << "//, debug";
904 
905  O << "\n";
906 
907  O << ".address_size ";
908  if (NTM.is64Bit())
909  O << "64";
910  else
911  O << "32";
912  O << "\n";
913 
914  O << "\n";
915 }
916 
918  bool HasDebugInfo = MMI && MMI->hasDebugInfo();
919 
920  // If we did not emit any functions, then the global declarations have not
921  // yet been emitted.
922  if (!GlobalsEmitted) {
923  emitGlobals(M);
924  GlobalsEmitted = true;
925  }
926 
927  // XXX Temproarily remove global variables so that doFinalization() will not
928  // emit them again (global variables are emitted at beginning).
929 
930  Module::GlobalListType &global_list = M.getGlobalList();
931  int i, n = global_list.size();
932  GlobalVariable **gv_array = new GlobalVariable *[n];
933 
934  // first, back-up GlobalVariable in gv_array
935  i = 0;
936  for (Module::global_iterator I = global_list.begin(), E = global_list.end();
937  I != E; ++I)
938  gv_array[i++] = &*I;
939 
940  // second, empty global_list
941  while (!global_list.empty())
942  global_list.remove(global_list.begin());
943 
944  // call doFinalization
945  bool ret = AsmPrinter::doFinalization(M);
946 
947  // now we restore global variables
948  for (i = 0; i < n; i++)
949  global_list.insert(global_list.end(), gv_array[i]);
950 
952 
953  delete[] gv_array;
954  // FIXME: remove comment once debug info is properly supported.
955  // Close the last emitted section
956  if (HasDebugInfo)
957  OutStreamer->EmitRawText("//\t}");
958 
959  // Output last DWARF .file directives, if any.
960  static_cast<NVPTXTargetStreamer *>(OutStreamer->getTargetStreamer())
961  ->outputDwarfFileDirectives();
962 
963  return ret;
964 
965  //bool Result = AsmPrinter::doFinalization(M);
966  // Instead of calling the parents doFinalization, we may
967  // clone parents doFinalization and customize here.
968  // Currently, we if NVISA out the EmitGlobals() in
969  // parent's doFinalization, which is too intrusive.
970  //
971  // Same for the doInitialization.
972  //return Result;
973 }
974 
975 // This function emits appropriate linkage directives for
976 // functions and global variables.
977 //
978 // extern function declaration -> .extern
979 // extern function definition -> .visible
980 // external global variable with init -> .visible
981 // external without init -> .extern
982 // appending -> not allowed, assert.
983 // for any linkage other than
984 // internal, private, linker_private,
985 // linker_private_weak, linker_private_weak_def_auto,
986 // we emit -> .weak.
987 
988 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
989  raw_ostream &O) {
990  if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
991  if (V->hasExternalLinkage()) {
992  if (isa<GlobalVariable>(V)) {
993  const GlobalVariable *GVar = cast<GlobalVariable>(V);
994  if (GVar) {
995  if (GVar->hasInitializer())
996  O << ".visible ";
997  else
998  O << ".extern ";
999  }
1000  } else if (V->isDeclaration())
1001  O << ".extern ";
1002  else
1003  O << ".visible ";
1004  } else if (V->hasAppendingLinkage()) {
1005  std::string msg;
1006  msg.append("Error: ");
1007  msg.append("Symbol ");
1008  if (V->hasName())
1009  msg.append(V->getName());
1010  msg.append("has unsupported appending linkage type");
1011  llvm_unreachable(msg.c_str());
1012  } else if (!V->hasInternalLinkage() &&
1013  !V->hasPrivateLinkage()) {
1014  O << ".weak ";
1015  }
1016  }
1017 }
1018 
1019 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1020  raw_ostream &O,
1021  bool processDemoted) {
1022  // Skip meta data
1023  if (GVar->hasSection()) {
1024  if (GVar->getSection() == "llvm.metadata")
1025  return;
1026  }
1027 
1028  // Skip LLVM intrinsic global variables
1029  if (GVar->getName().startswith("llvm.") ||
1030  GVar->getName().startswith("nvvm."))
1031  return;
1032 
1033  const DataLayout &DL = getDataLayout();
1034 
1035  // GlobalVariables are always constant pointers themselves.
1036  PointerType *PTy = GVar->getType();
1037  Type *ETy = GVar->getValueType();
1038 
1039  if (GVar->hasExternalLinkage()) {
1040  if (GVar->hasInitializer())
1041  O << ".visible ";
1042  else
1043  O << ".extern ";
1044  } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1046  GVar->hasCommonLinkage()) {
1047  O << ".weak ";
1048  }
1049 
1050  if (isTexture(*GVar)) {
1051  O << ".global .texref " << getTextureName(*GVar) << ";\n";
1052  return;
1053  }
1054 
1055  if (isSurface(*GVar)) {
1056  O << ".global .surfref " << getSurfaceName(*GVar) << ";\n";
1057  return;
1058  }
1059 
1060  if (GVar->isDeclaration()) {
1061  // (extern) declarations, no definition or initializer
1062  // Currently the only known declaration is for an automatic __local
1063  // (.shared) promoted to global.
1064  emitPTXGlobalVariable(GVar, O);
1065  O << ";\n";
1066  return;
1067  }
1068 
1069  if (isSampler(*GVar)) {
1070  O << ".global .samplerref " << getSamplerName(*GVar);
1071 
1072  const Constant *Initializer = nullptr;
1073  if (GVar->hasInitializer())
1074  Initializer = GVar->getInitializer();
1075  const ConstantInt *CI = nullptr;
1076  if (Initializer)
1077  CI = dyn_cast<ConstantInt>(Initializer);
1078  if (CI) {
1079  unsigned sample = CI->getZExtValue();
1080 
1081  O << " = { ";
1082 
1083  for (int i = 0,
1084  addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1085  i < 3; i++) {
1086  O << "addr_mode_" << i << " = ";
1087  switch (addr) {
1088  case 0:
1089  O << "wrap";
1090  break;
1091  case 1:
1092  O << "clamp_to_border";
1093  break;
1094  case 2:
1095  O << "clamp_to_edge";
1096  break;
1097  case 3:
1098  O << "wrap";
1099  break;
1100  case 4:
1101  O << "mirror";
1102  break;
1103  }
1104  O << ", ";
1105  }
1106  O << "filter_mode = ";
1107  switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1108  case 0:
1109  O << "nearest";
1110  break;
1111  case 1:
1112  O << "linear";
1113  break;
1114  case 2:
1115  llvm_unreachable("Anisotropic filtering is not supported");
1116  default:
1117  O << "nearest";
1118  break;
1119  }
1120  if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1121  O << ", force_unnormalized_coords = 1";
1122  }
1123  O << " }";
1124  }
1125 
1126  O << ";\n";
1127  return;
1128  }
1129 
1130  if (GVar->hasPrivateLinkage()) {
1131  if (strncmp(GVar->getName().data(), "unrollpragma", 12) == 0)
1132  return;
1133 
1134  // FIXME - need better way (e.g. Metadata) to avoid generating this global
1135  if (strncmp(GVar->getName().data(), "filename", 8) == 0)
1136  return;
1137  if (GVar->use_empty())
1138  return;
1139  }
1140 
1141  const Function *demotedFunc = nullptr;
1142  if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1143  O << "// " << GVar->getName() << " has been demoted\n";
1144  if (localDecls.find(demotedFunc) != localDecls.end())
1145  localDecls[demotedFunc].push_back(GVar);
1146  else {
1147  std::vector<const GlobalVariable *> temp;
1148  temp.push_back(GVar);
1149  localDecls[demotedFunc] = temp;
1150  }
1151  return;
1152  }
1153 
1154  O << ".";
1155  emitPTXAddressSpace(PTy->getAddressSpace(), O);
1156 
1157  if (isManaged(*GVar)) {
1158  O << " .attribute(.managed)";
1159  }
1160 
1161  if (GVar->getAlignment() == 0)
1162  O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
1163  else
1164  O << " .align " << GVar->getAlignment();
1165 
1166  if (ETy->isFloatingPointTy() || ETy->isPointerTy() ||
1167  (ETy->isIntegerTy() && ETy->getScalarSizeInBits() <= 64)) {
1168  O << " .";
1169  // Special case: ABI requires that we use .u8 for predicates
1170  if (ETy->isIntegerTy(1))
1171  O << "u8";
1172  else
1173  O << getPTXFundamentalTypeStr(ETy, false);
1174  O << " ";
1175  getSymbol(GVar)->print(O, MAI);
1176 
1177  // Ptx allows variable initilization only for constant and global state
1178  // spaces.
1179  if (GVar->hasInitializer()) {
1180  if ((PTy->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1181  (PTy->getAddressSpace() == ADDRESS_SPACE_CONST)) {
1182  const Constant *Initializer = GVar->getInitializer();
1183  // 'undef' is treated as there is no value specified.
1184  if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1185  O << " = ";
1186  printScalarConstant(Initializer, O);
1187  }
1188  } else {
1189  // The frontend adds zero-initializer to device and constant variables
1190  // that don't have an initial value, and UndefValue to shared
1191  // variables, so skip warning for this case.
1192  if (!GVar->getInitializer()->isNullValue() &&
1193  !isa<UndefValue>(GVar->getInitializer())) {
1194  report_fatal_error("initial value of '" + GVar->getName() +
1195  "' is not allowed in addrspace(" +
1196  Twine(PTy->getAddressSpace()) + ")");
1197  }
1198  }
1199  }
1200  } else {
1201  unsigned int ElementSize = 0;
1202 
1203  // Although PTX has direct support for struct type and array type and
1204  // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1205  // targets that support these high level field accesses. Structs, arrays
1206  // and vectors are lowered into arrays of bytes.
1207  switch (ETy->getTypeID()) {
1208  case Type::IntegerTyID: // Integers larger than 64 bits
1209  case Type::StructTyID:
1210  case Type::ArrayTyID:
1211  case Type::VectorTyID:
1212  ElementSize = DL.getTypeStoreSize(ETy);
1213  // Ptx allows variable initilization only for constant and
1214  // global state spaces.
1215  if (((PTy->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1216  (PTy->getAddressSpace() == ADDRESS_SPACE_CONST)) &&
1217  GVar->hasInitializer()) {
1218  const Constant *Initializer = GVar->getInitializer();
1219  if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1220  AggBuffer aggBuffer(ElementSize, O, *this);
1221  bufferAggregateConstant(Initializer, &aggBuffer);
1222  if (aggBuffer.numSymbols) {
1223  if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
1224  O << " .u64 ";
1225  getSymbol(GVar)->print(O, MAI);
1226  O << "[";
1227  O << ElementSize / 8;
1228  } else {
1229  O << " .u32 ";
1230  getSymbol(GVar)->print(O, MAI);
1231  O << "[";
1232  O << ElementSize / 4;
1233  }
1234  O << "]";
1235  } else {
1236  O << " .b8 ";
1237  getSymbol(GVar)->print(O, MAI);
1238  O << "[";
1239  O << ElementSize;
1240  O << "]";
1241  }
1242  O << " = {";
1243  aggBuffer.print();
1244  O << "}";
1245  } else {
1246  O << " .b8 ";
1247  getSymbol(GVar)->print(O, MAI);
1248  if (ElementSize) {
1249  O << "[";
1250  O << ElementSize;
1251  O << "]";
1252  }
1253  }
1254  } else {
1255  O << " .b8 ";
1256  getSymbol(GVar)->print(O, MAI);
1257  if (ElementSize) {
1258  O << "[";
1259  O << ElementSize;
1260  O << "]";
1261  }
1262  }
1263  break;
1264  default:
1265  llvm_unreachable("type not supported yet");
1266  }
1267  }
1268  O << ";\n";
1269 }
1270 
1271 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1272  if (localDecls.find(f) == localDecls.end())
1273  return;
1274 
1275  std::vector<const GlobalVariable *> &gvars = localDecls[f];
1276 
1277  for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1278  O << "\t// demoted variable\n\t";
1279  printModuleLevelGV(gvars[i], O, true);
1280  }
1281 }
1282 
1283 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1284  raw_ostream &O) const {
1285  switch (AddressSpace) {
1286  case ADDRESS_SPACE_LOCAL:
1287  O << "local";
1288  break;
1289  case ADDRESS_SPACE_GLOBAL:
1290  O << "global";
1291  break;
1292  case ADDRESS_SPACE_CONST:
1293  O << "const";
1294  break;
1295  case ADDRESS_SPACE_SHARED:
1296  O << "shared";
1297  break;
1298  default:
1299  report_fatal_error("Bad address space found while emitting PTX: " +
1301  break;
1302  }
1303 }
1304 
1305 std::string
1306 NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
1307  switch (Ty->getTypeID()) {
1308  default:
1309  llvm_unreachable("unexpected type");
1310  break;
1311  case Type::IntegerTyID: {
1312  unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1313  if (NumBits == 1)
1314  return "pred";
1315  else if (NumBits <= 64) {
1316  std::string name = "u";
1317  return name + utostr(NumBits);
1318  } else {
1319  llvm_unreachable("Integer too large");
1320  break;
1321  }
1322  break;
1323  }
1324  case Type::HalfTyID:
1325  // fp16 is stored as .b16 for compatibility with pre-sm_53 PTX assembly.
1326  return "b16";
1327  case Type::FloatTyID:
1328  return "f32";
1329  case Type::DoubleTyID:
1330  return "f64";
1331  case Type::PointerTyID:
1332  if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
1333  if (useB4PTR)
1334  return "b64";
1335  else
1336  return "u64";
1337  else if (useB4PTR)
1338  return "b32";
1339  else
1340  return "u32";
1341  }
1342  llvm_unreachable("unexpected type");
1343  return nullptr;
1344 }
1345 
1346 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1347  raw_ostream &O) {
1348  const DataLayout &DL = getDataLayout();
1349 
1350  // GlobalVariables are always constant pointers themselves.
1351  Type *ETy = GVar->getValueType();
1352 
1353  O << ".";
1354  emitPTXAddressSpace(GVar->getType()->getAddressSpace(), O);
1355  if (GVar->getAlignment() == 0)
1356  O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
1357  else
1358  O << " .align " << GVar->getAlignment();
1359 
1360  // Special case for i128
1361  if (ETy->isIntegerTy(128)) {
1362  O << " .b8 ";
1363  getSymbol(GVar)->print(O, MAI);
1364  O << "[16]";
1365  return;
1366  }
1367 
1368  if (ETy->isFloatingPointTy() || ETy->isIntOrPtrTy()) {
1369  O << " .";
1370  O << getPTXFundamentalTypeStr(ETy);
1371  O << " ";
1372  getSymbol(GVar)->print(O, MAI);
1373  return;
1374  }
1375 
1376  int64_t ElementSize = 0;
1377 
1378  // Although PTX has direct support for struct type and array type and LLVM IR
1379  // is very similar to PTX, the LLVM CodeGen does not support for targets that
1380  // support these high level field accesses. Structs and arrays are lowered
1381  // into arrays of bytes.
1382  switch (ETy->getTypeID()) {
1383  case Type::StructTyID:
1384  case Type::ArrayTyID:
1385  case Type::VectorTyID:
1386  ElementSize = DL.getTypeStoreSize(ETy);
1387  O << " .b8 ";
1388  getSymbol(GVar)->print(O, MAI);
1389  O << "[";
1390  if (ElementSize) {
1391  O << ElementSize;
1392  }
1393  O << "]";
1394  break;
1395  default:
1396  llvm_unreachable("type not supported yet");
1397  }
1398 }
1399 
1400 static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty) {
1401  if (Ty->isSingleValueType())
1402  return DL.getPrefTypeAlignment(Ty);
1403 
1404  auto *ATy = dyn_cast<ArrayType>(Ty);
1405  if (ATy)
1406  return getOpenCLAlignment(DL, ATy->getElementType());
1407 
1408  auto *STy = dyn_cast<StructType>(Ty);
1409  if (STy) {
1410  unsigned int alignStruct = 1;
1411  // Go through each element of the struct and find the
1412  // largest alignment.
1413  for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1414  Type *ETy = STy->getElementType(i);
1415  unsigned int align = getOpenCLAlignment(DL, ETy);
1416  if (align > alignStruct)
1417  alignStruct = align;
1418  }
1419  return alignStruct;
1420  }
1421 
1422  auto *FTy = dyn_cast<FunctionType>(Ty);
1423  if (FTy)
1424  return DL.getPointerPrefAlignment();
1425  return DL.getPrefTypeAlignment(Ty);
1426 }
1427 
1428 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1429  int paramIndex, raw_ostream &O) {
1430  getSymbol(I->getParent())->print(O, MAI);
1431  O << "_param_" << paramIndex;
1432 }
1433 
1434 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1435  const DataLayout &DL = getDataLayout();
1436  const AttributeList &PAL = F->getAttributes();
1437  const NVPTXSubtarget &STI = TM.getSubtarget<NVPTXSubtarget>(*F);
1438  const TargetLowering *TLI = STI.getTargetLowering();
1440  unsigned paramIndex = 0;
1441  bool first = true;
1442  bool isKernelFunc = isKernelFunction(*F);
1443  bool isABI = (STI.getSmVersion() >= 20);
1444  bool hasImageHandles = STI.hasImageHandles();
1445  MVT thePointerTy = TLI->getPointerTy(DL);
1446 
1447  if (F->arg_empty()) {
1448  O << "()\n";
1449  return;
1450  }
1451 
1452  O << "(\n";
1453 
1454  for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1455  Type *Ty = I->getType();
1456 
1457  if (!first)
1458  O << ",\n";
1459 
1460  first = false;
1461 
1462  // Handle image/sampler parameters
1463  if (isKernelFunction(*F)) {
1464  if (isSampler(*I) || isImage(*I)) {
1465  if (isImage(*I)) {
1466  std::string sname = I->getName();
1467  if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1468  if (hasImageHandles)
1469  O << "\t.param .u64 .ptr .surfref ";
1470  else
1471  O << "\t.param .surfref ";
1472  CurrentFnSym->print(O, MAI);
1473  O << "_param_" << paramIndex;
1474  }
1475  else { // Default image is read_only
1476  if (hasImageHandles)
1477  O << "\t.param .u64 .ptr .texref ";
1478  else
1479  O << "\t.param .texref ";
1480  CurrentFnSym->print(O, MAI);
1481  O << "_param_" << paramIndex;
1482  }
1483  } else {
1484  if (hasImageHandles)
1485  O << "\t.param .u64 .ptr .samplerref ";
1486  else
1487  O << "\t.param .samplerref ";
1488  CurrentFnSym->print(O, MAI);
1489  O << "_param_" << paramIndex;
1490  }
1491  continue;
1492  }
1493  }
1494 
1495  if (!PAL.hasParamAttribute(paramIndex, Attribute::ByVal)) {
1496  if (Ty->isAggregateType() || Ty->isVectorTy() || Ty->isIntegerTy(128)) {
1497  // Just print .param .align <a> .b8 .param[size];
1498  // <a> = PAL.getparamalignment
1499  // size = typeallocsize of element type
1500  unsigned align = PAL.getParamAlignment(paramIndex);
1501  if (align == 0)
1502  align = DL.getABITypeAlignment(Ty);
1503 
1504  unsigned sz = DL.getTypeAllocSize(Ty);
1505  O << "\t.param .align " << align << " .b8 ";
1506  printParamName(I, paramIndex, O);
1507  O << "[" << sz << "]";
1508 
1509  continue;
1510  }
1511  // Just a scalar
1512  auto *PTy = dyn_cast<PointerType>(Ty);
1513  if (isKernelFunc) {
1514  if (PTy) {
1515  // Special handling for pointer arguments to kernel
1516  O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1517 
1518  if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1519  NVPTX::CUDA) {
1520  Type *ETy = PTy->getElementType();
1521  int addrSpace = PTy->getAddressSpace();
1522  switch (addrSpace) {
1523  default:
1524  O << ".ptr ";
1525  break;
1526  case ADDRESS_SPACE_CONST:
1527  O << ".ptr .const ";
1528  break;
1529  case ADDRESS_SPACE_SHARED:
1530  O << ".ptr .shared ";
1531  break;
1532  case ADDRESS_SPACE_GLOBAL:
1533  O << ".ptr .global ";
1534  break;
1535  }
1536  O << ".align " << (int)getOpenCLAlignment(DL, ETy) << " ";
1537  }
1538  printParamName(I, paramIndex, O);
1539  continue;
1540  }
1541 
1542  // non-pointer scalar to kernel func
1543  O << "\t.param .";
1544  // Special case: predicate operands become .u8 types
1545  if (Ty->isIntegerTy(1))
1546  O << "u8";
1547  else
1548  O << getPTXFundamentalTypeStr(Ty);
1549  O << " ";
1550  printParamName(I, paramIndex, O);
1551  continue;
1552  }
1553  // Non-kernel function, just print .param .b<size> for ABI
1554  // and .reg .b<size> for non-ABI
1555  unsigned sz = 0;
1556  if (isa<IntegerType>(Ty)) {
1557  sz = cast<IntegerType>(Ty)->getBitWidth();
1558  if (sz < 32)
1559  sz = 32;
1560  } else if (isa<PointerType>(Ty))
1561  sz = thePointerTy.getSizeInBits();
1562  else if (Ty->isHalfTy())
1563  // PTX ABI requires all scalar parameters to be at least 32
1564  // bits in size. fp16 normally uses .b16 as its storage type
1565  // in PTX, so its size must be adjusted here, too.
1566  sz = 32;
1567  else
1568  sz = Ty->getPrimitiveSizeInBits();
1569  if (isABI)
1570  O << "\t.param .b" << sz << " ";
1571  else
1572  O << "\t.reg .b" << sz << " ";
1573  printParamName(I, paramIndex, O);
1574  continue;
1575  }
1576 
1577  // param has byVal attribute. So should be a pointer
1578  auto *PTy = dyn_cast<PointerType>(Ty);
1579  assert(PTy && "Param with byval attribute should be a pointer type");
1580  Type *ETy = PTy->getElementType();
1581 
1582  if (isABI || isKernelFunc) {
1583  // Just print .param .align <a> .b8 .param[size];
1584  // <a> = PAL.getparamalignment
1585  // size = typeallocsize of element type
1586  unsigned align = PAL.getParamAlignment(paramIndex);
1587  if (align == 0)
1588  align = DL.getABITypeAlignment(ETy);
1589  // Work around a bug in ptxas. When PTX code takes address of
1590  // byval parameter with alignment < 4, ptxas generates code to
1591  // spill argument into memory. Alas on sm_50+ ptxas generates
1592  // SASS code that fails with misaligned access. To work around
1593  // the problem, make sure that we align byval parameters by at
1594  // least 4. Matching change must be made in LowerCall() where we
1595  // prepare parameters for the call.
1596  //
1597  // TODO: this will need to be undone when we get to support multi-TU
1598  // device-side compilation as it breaks ABI compatibility with nvcc.
1599  // Hopefully ptxas bug is fixed by then.
1600  if (!isKernelFunc && align < 4)
1601  align = 4;
1602  unsigned sz = DL.getTypeAllocSize(ETy);
1603  O << "\t.param .align " << align << " .b8 ";
1604  printParamName(I, paramIndex, O);
1605  O << "[" << sz << "]";
1606  continue;
1607  } else {
1608  // Split the ETy into constituent parts and
1609  // print .param .b<size> <name> for each part.
1610  // Further, if a part is vector, print the above for
1611  // each vector element.
1612  SmallVector<EVT, 16> vtparts;
1613  ComputeValueVTs(*TLI, DL, ETy, vtparts);
1614  for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1615  unsigned elems = 1;
1616  EVT elemtype = vtparts[i];
1617  if (vtparts[i].isVector()) {
1618  elems = vtparts[i].getVectorNumElements();
1619  elemtype = vtparts[i].getVectorElementType();
1620  }
1621 
1622  for (unsigned j = 0, je = elems; j != je; ++j) {
1623  unsigned sz = elemtype.getSizeInBits();
1624  if (elemtype.isInteger() && (sz < 32))
1625  sz = 32;
1626  O << "\t.reg .b" << sz << " ";
1627  printParamName(I, paramIndex, O);
1628  if (j < je - 1)
1629  O << ",\n";
1630  ++paramIndex;
1631  }
1632  if (i < e - 1)
1633  O << ",\n";
1634  }
1635  --paramIndex;
1636  continue;
1637  }
1638  }
1639 
1640  O << "\n)\n";
1641 }
1642 
1643 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1644  raw_ostream &O) {
1645  const Function &F = MF.getFunction();
1646  emitFunctionParamList(&F, O);
1647 }
1648 
1649 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1650  const MachineFunction &MF) {
1651  SmallString<128> Str;
1652  raw_svector_ostream O(Str);
1653 
1654  // Map the global virtual register number to a register class specific
1655  // virtual register number starting from 1 with that class.
1657  //unsigned numRegClasses = TRI->getNumRegClasses();
1658 
1659  // Emit the Fake Stack Object
1660  const MachineFrameInfo &MFI = MF.getFrameInfo();
1661  int NumBytes = (int) MFI.getStackSize();
1662  if (NumBytes) {
1663  O << "\t.local .align " << MFI.getMaxAlignment() << " .b8 \t" << DEPOTNAME
1664  << getFunctionNumber() << "[" << NumBytes << "];\n";
1665  if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
1666  O << "\t.reg .b64 \t%SP;\n";
1667  O << "\t.reg .b64 \t%SPL;\n";
1668  } else {
1669  O << "\t.reg .b32 \t%SP;\n";
1670  O << "\t.reg .b32 \t%SPL;\n";
1671  }
1672  }
1673 
1674  // Go through all virtual registers to establish the mapping between the
1675  // global virtual
1676  // register number and the per class virtual register number.
1677  // We use the per class virtual register number in the ptx output.
1678  unsigned int numVRs = MRI->getNumVirtRegs();
1679  for (unsigned i = 0; i < numVRs; i++) {
1680  unsigned int vr = TRI->index2VirtReg(i);
1681  const TargetRegisterClass *RC = MRI->getRegClass(vr);
1682  DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1683  int n = regmap.size();
1684  regmap.insert(std::make_pair(vr, n + 1));
1685  }
1686 
1687  // Emit register declarations
1688  // @TODO: Extract out the real register usage
1689  // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1690  // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1691  // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1692  // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1693  // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1694  // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1695  // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1696 
1697  // Emit declaration of the virtual registers or 'physical' registers for
1698  // each register class
1699  for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1700  const TargetRegisterClass *RC = TRI->getRegClass(i);
1701  DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1702  std::string rcname = getNVPTXRegClassName(RC);
1703  std::string rcStr = getNVPTXRegClassStr(RC);
1704  int n = regmap.size();
1705 
1706  // Only declare those registers that may be used.
1707  if (n) {
1708  O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1709  << ">;\n";
1710  }
1711  }
1712 
1713  OutStreamer->EmitRawText(O.str());
1714 }
1715 
1716 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1717  APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1718  bool ignored;
1719  unsigned int numHex;
1720  const char *lead;
1721 
1722  if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1723  numHex = 8;
1724  lead = "0f";
1726  } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1727  numHex = 16;
1728  lead = "0d";
1730  } else
1731  llvm_unreachable("unsupported fp type");
1732 
1733  APInt API = APF.bitcastToAPInt();
1734  O << lead << format_hex_no_prefix(API.getZExtValue(), numHex, /*Upper=*/true);
1735 }
1736 
1737 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1738  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1739  O << CI->getValue();
1740  return;
1741  }
1742  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1743  printFPConstant(CFP, O);
1744  return;
1745  }
1746  if (isa<ConstantPointerNull>(CPV)) {
1747  O << "0";
1748  return;
1749  }
1750  if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1751  bool IsNonGenericPointer = false;
1752  if (GVar->getType()->getAddressSpace() != 0) {
1753  IsNonGenericPointer = true;
1754  }
1755  if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1756  O << "generic(";
1757  getSymbol(GVar)->print(O, MAI);
1758  O << ")";
1759  } else {
1760  getSymbol(GVar)->print(O, MAI);
1761  }
1762  return;
1763  }
1764  if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1765  const Value *v = Cexpr->stripPointerCasts();
1766  PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1767  bool IsNonGenericPointer = false;
1768  if (PTy && PTy->getAddressSpace() != 0) {
1769  IsNonGenericPointer = true;
1770  }
1771  if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1772  if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1773  O << "generic(";
1774  getSymbol(GVar)->print(O, MAI);
1775  O << ")";
1776  } else {
1777  getSymbol(GVar)->print(O, MAI);
1778  }
1779  return;
1780  } else {
1781  lowerConstant(CPV)->print(O, MAI);
1782  return;
1783  }
1784  }
1785  llvm_unreachable("Not scalar type found in printScalarConstant()");
1786 }
1787 
1788 // These utility functions assure we get the right sequence of bytes for a given
1789 // type even for big-endian machines
1790 template <typename T> static void ConvertIntToBytes(unsigned char *p, T val) {
1791  int64_t vp = (int64_t)val;
1792  for (unsigned i = 0; i < sizeof(T); ++i) {
1793  p[i] = (unsigned char)vp;
1794  vp >>= 8;
1795  }
1796 }
1797 static void ConvertFloatToBytes(unsigned char *p, float val) {
1798  int32_t *vp = (int32_t *)&val;
1799  for (unsigned i = 0; i < sizeof(int32_t); ++i) {
1800  p[i] = (unsigned char)*vp;
1801  *vp >>= 8;
1802  }
1803 }
1804 static void ConvertDoubleToBytes(unsigned char *p, double val) {
1805  int64_t *vp = (int64_t *)&val;
1806  for (unsigned i = 0; i < sizeof(int64_t); ++i) {
1807  p[i] = (unsigned char)*vp;
1808  *vp >>= 8;
1809  }
1810 }
1811 
1812 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1813  AggBuffer *aggBuffer) {
1814  const DataLayout &DL = getDataLayout();
1815 
1816  if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1817  int s = DL.getTypeAllocSize(CPV->getType());
1818  if (s < Bytes)
1819  s = Bytes;
1820  aggBuffer->addZeros(s);
1821  return;
1822  }
1823 
1824  unsigned char ptr[8];
1825  switch (CPV->getType()->getTypeID()) {
1826 
1827  case Type::IntegerTyID: {
1828  Type *ETy = CPV->getType();
1829  if (ETy == Type::getInt8Ty(CPV->getContext())) {
1830  unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
1831  ConvertIntToBytes<>(ptr, c);
1832  aggBuffer->addBytes(ptr, 1, Bytes);
1833  } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1834  short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
1835  ConvertIntToBytes<>(ptr, int16);
1836  aggBuffer->addBytes(ptr, 2, Bytes);
1837  } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1838  if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1839  int int32 = (int)(constInt->getZExtValue());
1840  ConvertIntToBytes<>(ptr, int32);
1841  aggBuffer->addBytes(ptr, 4, Bytes);
1842  break;
1843  } else if (const auto *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1844  if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1845  ConstantFoldConstant(Cexpr, DL))) {
1846  int int32 = (int)(constInt->getZExtValue());
1847  ConvertIntToBytes<>(ptr, int32);
1848  aggBuffer->addBytes(ptr, 4, Bytes);
1849  break;
1850  }
1851  if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1852  Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1853  aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1854  aggBuffer->addZeros(4);
1855  break;
1856  }
1857  }
1858  llvm_unreachable("unsupported integer const type");
1859  } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1860  if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1861  long long int64 = (long long)(constInt->getZExtValue());
1862  ConvertIntToBytes<>(ptr, int64);
1863  aggBuffer->addBytes(ptr, 8, Bytes);
1864  break;
1865  } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1866  if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1867  ConstantFoldConstant(Cexpr, DL))) {
1868  long long int64 = (long long)(constInt->getZExtValue());
1869  ConvertIntToBytes<>(ptr, int64);
1870  aggBuffer->addBytes(ptr, 8, Bytes);
1871  break;
1872  }
1873  if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1874  Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1875  aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1876  aggBuffer->addZeros(8);
1877  break;
1878  }
1879  }
1880  llvm_unreachable("unsupported integer const type");
1881  } else
1882  llvm_unreachable("unsupported integer const type");
1883  break;
1884  }
1885  case Type::HalfTyID:
1886  case Type::FloatTyID:
1887  case Type::DoubleTyID: {
1888  const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1889  Type *Ty = CFP->getType();
1890  if (Ty == Type::getHalfTy(CPV->getContext())) {
1891  APInt API = CFP->getValueAPF().bitcastToAPInt();
1892  uint16_t float16 = API.getLoBits(16).getZExtValue();
1893  ConvertIntToBytes<>(ptr, float16);
1894  aggBuffer->addBytes(ptr, 2, Bytes);
1895  } else if (Ty == Type::getFloatTy(CPV->getContext())) {
1896  float float32 = (float) CFP->getValueAPF().convertToFloat();
1897  ConvertFloatToBytes(ptr, float32);
1898  aggBuffer->addBytes(ptr, 4, Bytes);
1899  } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1900  double float64 = CFP->getValueAPF().convertToDouble();
1901  ConvertDoubleToBytes(ptr, float64);
1902  aggBuffer->addBytes(ptr, 8, Bytes);
1903  } else {
1904  llvm_unreachable("unsupported fp const type");
1905  }
1906  break;
1907  }
1908  case Type::PointerTyID: {
1909  if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1910  aggBuffer->addSymbol(GVar, GVar);
1911  } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1912  const Value *v = Cexpr->stripPointerCasts();
1913  aggBuffer->addSymbol(v, Cexpr);
1914  }
1915  unsigned int s = DL.getTypeAllocSize(CPV->getType());
1916  aggBuffer->addZeros(s);
1917  break;
1918  }
1919 
1920  case Type::ArrayTyID:
1921  case Type::VectorTyID:
1922  case Type::StructTyID: {
1923  if (isa<ConstantAggregate>(CPV) || isa<ConstantDataSequential>(CPV)) {
1924  int ElementSize = DL.getTypeAllocSize(CPV->getType());
1925  bufferAggregateConstant(CPV, aggBuffer);
1926  if (Bytes > ElementSize)
1927  aggBuffer->addZeros(Bytes - ElementSize);
1928  } else if (isa<ConstantAggregateZero>(CPV))
1929  aggBuffer->addZeros(Bytes);
1930  else
1931  llvm_unreachable("Unexpected Constant type");
1932  break;
1933  }
1934 
1935  default:
1936  llvm_unreachable("unsupported type");
1937  }
1938 }
1939 
1940 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1941  AggBuffer *aggBuffer) {
1942  const DataLayout &DL = getDataLayout();
1943  int Bytes;
1944 
1945  // Integers of arbitrary width
1946  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1947  APInt Val = CI->getValue();
1948  for (unsigned I = 0, E = DL.getTypeAllocSize(CPV->getType()); I < E; ++I) {
1949  uint8_t Byte = Val.getLoBits(8).getZExtValue();
1950  aggBuffer->addBytes(&Byte, 1, 1);
1951  Val.lshrInPlace(8);
1952  }
1953  return;
1954  }
1955 
1956  // Old constants
1957  if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1958  if (CPV->getNumOperands())
1959  for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1960  bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1961  return;
1962  }
1963 
1964  if (const ConstantDataSequential *CDS =
1965  dyn_cast<ConstantDataSequential>(CPV)) {
1966  if (CDS->getNumElements())
1967  for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1968  bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1969  aggBuffer);
1970  return;
1971  }
1972 
1973  if (isa<ConstantStruct>(CPV)) {
1974  if (CPV->getNumOperands()) {
1975  StructType *ST = cast<StructType>(CPV->getType());
1976  for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1977  if (i == (e - 1))
1978  Bytes = DL.getStructLayout(ST)->getElementOffset(0) +
1979  DL.getTypeAllocSize(ST) -
1980  DL.getStructLayout(ST)->getElementOffset(i);
1981  else
1982  Bytes = DL.getStructLayout(ST)->getElementOffset(i + 1) -
1983  DL.getStructLayout(ST)->getElementOffset(i);
1984  bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1985  }
1986  }
1987  return;
1988  }
1989  llvm_unreachable("unsupported constant type in printAggregateConstant()");
1990 }
1991 
1992 /// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
1993 /// a copy from AsmPrinter::lowerConstant, except customized to only handle
1994 /// expressions that are representable in PTX and create
1995 /// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
1996 const MCExpr *
1997 NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
1998  MCContext &Ctx = OutContext;
1999 
2000  if (CV->isNullValue() || isa<UndefValue>(CV))
2001  return MCConstantExpr::create(0, Ctx);
2002 
2003  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2004  return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2005 
2006  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2007  const MCSymbolRefExpr *Expr =
2009  if (ProcessingGeneric) {
2010  return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
2011  } else {
2012  return Expr;
2013  }
2014  }
2015 
2016  const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2017  if (!CE) {
2018  llvm_unreachable("Unknown constant value to lower!");
2019  }
2020 
2021  switch (CE->getOpcode()) {
2022  default:
2023  // If the code isn't optimized, there may be outstanding folding
2024  // opportunities. Attempt to fold the expression using DataLayout as a
2025  // last resort before giving up.
2027  if (C && C != CE)
2028  return lowerConstantForGV(C, ProcessingGeneric);
2029 
2030  // Otherwise report the problem to the user.
2031  {
2032  std::string S;
2033  raw_string_ostream OS(S);
2034  OS << "Unsupported expression in static initializer: ";
2035  CE->printAsOperand(OS, /*PrintType=*/false,
2036  !MF ? nullptr : MF->getFunction().getParent());
2037  report_fatal_error(OS.str());
2038  }
2039 
2040  case Instruction::AddrSpaceCast: {
2041  // Strip the addrspacecast and pass along the operand
2042  PointerType *DstTy = cast<PointerType>(CE->getType());
2043  if (DstTy->getAddressSpace() == 0) {
2044  return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2045  }
2046  std::string S;
2047  raw_string_ostream OS(S);
2048  OS << "Unsupported expression in static initializer: ";
2049  CE->printAsOperand(OS, /*PrintType=*/ false,
2050  !MF ? nullptr : MF->getFunction().getParent());
2051  report_fatal_error(OS.str());
2052  }
2053 
2054  case Instruction::GetElementPtr: {
2055  const DataLayout &DL = getDataLayout();
2056 
2057  // Generate a symbolic expression for the byte address
2058  APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2059  cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2060 
2061  const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2062  ProcessingGeneric);
2063  if (!OffsetAI)
2064  return Base;
2065 
2066  int64_t Offset = OffsetAI.getSExtValue();
2067  return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2068  Ctx);
2069  }
2070 
2071  case Instruction::Trunc:
2072  // We emit the value and depend on the assembler to truncate the generated
2073  // expression properly. This is important for differences between
2074  // blockaddress labels. Since the two labels are in the same function, it
2075  // is reasonable to treat their delta as a 32-bit value.
2077  case Instruction::BitCast:
2078  return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2079 
2080  case Instruction::IntToPtr: {
2081  const DataLayout &DL = getDataLayout();
2082 
2083  // Handle casts to pointers by changing them into casts to the appropriate
2084  // integer type. This promotes constant folding and simplifies this code.
2085  Constant *Op = CE->getOperand(0);
2087  false/*ZExt*/);
2088  return lowerConstantForGV(Op, ProcessingGeneric);
2089  }
2090 
2091  case Instruction::PtrToInt: {
2092  const DataLayout &DL = getDataLayout();
2093 
2094  // Support only foldable casts to/from pointers that can be eliminated by
2095  // changing the pointer to the appropriately sized integer type.
2096  Constant *Op = CE->getOperand(0);
2097  Type *Ty = CE->getType();
2098 
2099  const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2100 
2101  // We can emit the pointer value into this slot if the slot is an
2102  // integer slot equal to the size of the pointer.
2103  if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2104  return OpExpr;
2105 
2106  // Otherwise the pointer is smaller than the resultant integer, mask off
2107  // the high bits so we are sure to get a proper truncation if the input is
2108  // a constant expr.
2109  unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2110  const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2111  return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2112  }
2113 
2114  // The MC library also has a right-shift operator, but it isn't consistently
2115  // signed or unsigned between different targets.
2116  case Instruction::Add: {
2117  const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2118  const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2119  switch (CE->getOpcode()) {
2120  default: llvm_unreachable("Unknown binary operator constant cast expr");
2121  case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2122  }
2123  }
2124  }
2125 }
2126 
2127 // Copy of MCExpr::print customized for NVPTX
2128 void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2129  switch (Expr.getKind()) {
2130  case MCExpr::Target:
2131  return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
2132  case MCExpr::Constant:
2133  OS << cast<MCConstantExpr>(Expr).getValue();
2134  return;
2135 
2136  case MCExpr::SymbolRef: {
2137  const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2138  const MCSymbol &Sym = SRE.getSymbol();
2139  Sym.print(OS, MAI);
2140  return;
2141  }
2142 
2143  case MCExpr::Unary: {
2144  const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2145  switch (UE.getOpcode()) {
2146  case MCUnaryExpr::LNot: OS << '!'; break;
2147  case MCUnaryExpr::Minus: OS << '-'; break;
2148  case MCUnaryExpr::Not: OS << '~'; break;
2149  case MCUnaryExpr::Plus: OS << '+'; break;
2150  }
2151  printMCExpr(*UE.getSubExpr(), OS);
2152  return;
2153  }
2154 
2155  case MCExpr::Binary: {
2156  const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2157 
2158  // Only print parens around the LHS if it is non-trivial.
2159  if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2160  isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2161  printMCExpr(*BE.getLHS(), OS);
2162  } else {
2163  OS << '(';
2164  printMCExpr(*BE.getLHS(), OS);
2165  OS<< ')';
2166  }
2167 
2168  switch (BE.getOpcode()) {
2169  case MCBinaryExpr::Add:
2170  // Print "X-42" instead of "X+-42".
2171  if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2172  if (RHSC->getValue() < 0) {
2173  OS << RHSC->getValue();
2174  return;
2175  }
2176  }
2177 
2178  OS << '+';
2179  break;
2180  default: llvm_unreachable("Unhandled binary operator");
2181  }
2182 
2183  // Only print parens around the LHS if it is non-trivial.
2184  if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2185  printMCExpr(*BE.getRHS(), OS);
2186  } else {
2187  OS << '(';
2188  printMCExpr(*BE.getRHS(), OS);
2189  OS << ')';
2190  }
2191  return;
2192  }
2193  }
2194 
2195  llvm_unreachable("Invalid expression kind!");
2196 }
2197 
2198 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2199 ///
2200 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2201  unsigned AsmVariant,
2202  const char *ExtraCode, raw_ostream &O) {
2203  if (ExtraCode && ExtraCode[0]) {
2204  if (ExtraCode[1] != 0)
2205  return true; // Unknown modifier.
2206 
2207  switch (ExtraCode[0]) {
2208  default:
2209  // See if this is a generic print operand
2210  return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2211  case 'r':
2212  break;
2213  }
2214  }
2215 
2216  printOperand(MI, OpNo, O);
2217 
2218  return false;
2219 }
2220 
2221 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2222  const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2223  const char *ExtraCode, raw_ostream &O) {
2224  if (ExtraCode && ExtraCode[0])
2225  return true; // Unknown modifier
2226 
2227  O << '[';
2228  printMemOperand(MI, OpNo, O);
2229  O << ']';
2230 
2231  return false;
2232 }
2233 
2234 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2235  raw_ostream &O, const char *Modifier) {
2236  const MachineOperand &MO = MI->getOperand(opNum);
2237  switch (MO.getType()) {
2240  if (MO.getReg() == NVPTX::VRDepot)
2241  O << DEPOTNAME << getFunctionNumber();
2242  else
2244  } else {
2245  emitVirtualRegister(MO.getReg(), O);
2246  }
2247  return;
2248 
2250  if (!Modifier)
2251  O << MO.getImm();
2252  else if (strstr(Modifier, "vec") == Modifier)
2253  printVecModifiedImmediate(MO, Modifier, O);
2254  else
2256  "Don't know how to handle modifier on immediate operand");
2257  return;
2258 
2260  printFPConstant(MO.getFPImm(), O);
2261  break;
2262 
2264  getSymbol(MO.getGlobal())->print(O, MAI);
2265  break;
2266 
2268  MO.getMBB()->getSymbol()->print(O, MAI);
2269  return;
2270 
2271  default:
2272  llvm_unreachable("Operand type not supported.");
2273  }
2274 }
2275 
2276 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2277  raw_ostream &O, const char *Modifier) {
2278  printOperand(MI, opNum, O);
2279 
2280  if (Modifier && strcmp(Modifier, "add") == 0) {
2281  O << ", ";
2282  printOperand(MI, opNum + 1, O);
2283  } else {
2284  if (MI->getOperand(opNum + 1).isImm() &&
2285  MI->getOperand(opNum + 1).getImm() == 0)
2286  return; // don't print ',0' or '+0'
2287  O << "+";
2288  printOperand(MI, opNum + 1, O);
2289  }
2290 }
2291 
2292 // Force static initialization.
2296 }
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
uint64_t CallInst * C
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:89
unsigned getAlignment() const
Definition: GlobalObject.h:58
unsigned getPTXVersion() const
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:110
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static Type * getDoubleTy(LLVMContext &C)
Definition: Type.cpp:164
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition: Constants.h:1209
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1562
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
Bitwise negation.
Definition: MCExpr.h:364
MachineBasicBlock * getMBB() const
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition: AsmPrinter.h:93
bool hasDebugInfo() const
Returns true if valid debug info is present.
MCSymbol * GetExternalSymbolSymbol(StringRef Sym) const
Return the MCSymbol for the specified ExternalSymbol.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:322
bool getAlign(const Function &F, unsigned index, unsigned &align)
bool hasPrivateLinkage() const
Definition: GlobalValue.h:434
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:139
This class represents lattice values for constants.
Definition: AllocatorList.h:23
bool getMaxNReg(const Function &F, unsigned &x)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
static unsigned index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
unsigned getPointerPrefAlignment(unsigned AS=0) const
Return target&#39;s alignment for stack-based pointers FIXME: The defaults need to be removed once all of...
Definition: DataLayout.cpp:619
2: 32-bit floating point type
Definition: Type.h:58
bool doFinalization(Module &M) override
Shut down the asmprinter.
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition: AsmPrinter.h:88
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
static MCOperand createExpr(const MCExpr *Val)
Definition: MCInst.h:136
Implements a dense probed hash-table based set.
Definition: DenseSet.h:249
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:587
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:163
unsigned getReg() const
getReg - Returns the register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
bool isTexture(const Value &val)
unsigned Reg
bool hasAvailableExternallyLinkage() const
Definition: GlobalValue.h:422
Opcode getOpcode() const
Get the kind of this unary expression.
Definition: MCExpr.h:403
float convertToFloat() const
Definition: APFloat.h:1097
const GlobalVariable * getNamedGlobal(StringRef Name) const
Return the global variable in the module with the specified name, of arbitrary type.
Definition: Module.h:401
const MCExpr * getLHS() const
Get the left-hand side expression of the binary operator.
Definition: MCExpr.h:563
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:704
Unary plus.
Definition: MCExpr.h:365
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:509
MachineBasicBlock reference.
13: Structures
Definition: Type.h:72
unsigned const TargetRegisterInfo * TRI
Metadata node.
Definition: Metadata.h:863
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:465
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition: ValueTypes.h:140
F(f)
MachineFunction * MF
The current machine function.
Definition: AsmPrinter.h:96
1: 16-bit floating point type
Definition: Type.h:57
const GlobalListType & getGlobalList() const
Get the Module&#39;s list of global variables (constant).
Definition: Module.h:520
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:176
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:229
15: Pointers
Definition: Type.h:74
static IntegerType * getInt16Ty(LLVMContext &C)
Definition: Type.cpp:174
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:127
const TargetRegisterClass * getRegClass(unsigned i) const
Returns the register class associated with the enumeration value.
static const NVPTXFloatMCExpr * createConstantFPSingle(const APFloat &Flt, MCContext &Ctx)
Definition: NVPTXMCExpr.h:48
bool hasImageHandles() const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:221
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
static void DiscoverDependentGlobals(const Value *V, DenseSet< const GlobalVariable *> &Globals)
DiscoverDependentGlobals - Return a set of GlobalVariables on which V depends.
const MCSymbol * getFunctionFrameSymbol() const override
Return symbol for the function pseudo stack if the stack frame is not a register based.
static Constant * getIntegerCast(Constant *C, Type *Ty, bool isSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
Definition: Constants.cpp:1612
amdgpu Simplify well known AMD library false Value Value const Twine & Name
APInt getLoBits(unsigned numBits) const
Compute an APInt containing numBits lowbits from this APInt.
Definition: APInt.cpp:515
static MCOperand createReg(unsigned Reg)
Definition: MCInst.h:115
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
static Type * getFloatTy(LLVMContext &C)
Definition: Type.cpp:163
unsigned getPointerTypeSizeInBits(Type *) const
Layout pointer size, in bits, based on the type.
Definition: DataLayout.cpp:645
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:137
bool isFloatingPointTy() const
Return true if this is one of the six floating-point types.
Definition: Type.h:161
static bool usedInOneFunc(const User *U, Function const *&oneFunc)
const ConstantFP * getFPImm() const
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:411
Class to represent struct types.
Definition: DerivedTypes.h:200
void clearAnnotationCache(const Module *Mod)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:196
Name of external global symbol.
This file contains the simple types necessary to represent the attributes associated with functions a...
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:165
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:408
static const NVPTXFloatMCExpr * createConstantFPDouble(const APFloat &Flt, MCContext &Ctx)
Definition: NVPTXMCExpr.h:53
const char * getSymbolName() const
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition: APInt.h:977
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
This file implements a class to represent arbitrary precision integral constant values and operations...
bool hasCommonLinkage() const
Definition: GlobalValue.h:439
Target & getTheNVPTXTarget64()
unsigned getNumRegClasses() const
bool getMaxNTIDz(const Function &F, unsigned &z)
unsigned getSizeInBits() const
Context object for machine code objects.
Definition: MCContext.h:62
bool hasExternalLinkage() const
Definition: GlobalValue.h:421
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Attempt to fold the constant using the specified DataLayout.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:266
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:84
A constant value that is initialized with an expression using other constant values.
Definition: Constants.h:888
Class to represent function types.
Definition: DerivedTypes.h:102
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:291
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1574
bool isKernelFunction(const Function &F)
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:405
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
bool isSurface(const Value &val)
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
Definition: AsmPrinter.h:295
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition: APFloat.cpp:4443
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition: Constants.h:573
const MCExpr * getRHS() const
Get the right-hand side expression of the binary operator.
Definition: MCExpr.h:566
#define T
Unary assembler expressions.
Definition: MCExpr.h:359
Class to represent array types.
Definition: DerivedTypes.h:368
bool getMaxNTIDx(const Function &F, unsigned &x)
std::string getTextureName(const Value &val)
ManagedStringPool * getManagedStrPool() const
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition: Type.h:211
bool runOnMachineFunction(MachineFunction &F) override
Emit the specified function out to the OutStreamer.
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:223
RegisterAsmPrinter - Helper template for registering a target specific assembly printer, for use in the target machine initialization function.
static const fltSemantics & IEEEdouble() LLVM_READNONE
Definition: APFloat.cpp:122
#define DEPOTNAME
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:460
bool hasLinkOnceLinkage() const
Definition: GlobalValue.h:425
bool isSampler(const Value &val)
void ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< uint64_t > *Offsets=nullptr, uint64_t StartingOffset=0)
ComputeValueVTs - Given an LLVM IR type, compute a sequence of EVTs that represent all the individual...
Definition: Analysis.cpp:83
const NVPTXSubtarget * getSubtargetImpl(const Function &) const override
Virtual method implemented by subclasses that returns a reference to that target&#39;s TargetSubtargetInf...
Unary expressions.
Definition: MCExpr.h:41
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition: AsmPrinter.h:99
Value * getOperand(unsigned i) const
Definition: User.h:169
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:158
static const NVPTXGenericMCSymbolRefExpr * create(const MCSymbolRefExpr *SymExpr, MCContext &Ctx)
Definition: NVPTXMCExpr.cpp:54
Class to represent pointers.
Definition: DerivedTypes.h:466
bool hasAppendingLinkage() const
Definition: GlobalValue.h:432
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:176
11: Arbitrary bit width integers
Definition: Type.h:70
Target & getTheNVPTXTarget32()
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:749
0: type with no size
Definition: Type.h:56
Address of a global value.
static bool isEmptyXXStructor(GlobalVariable *GV)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:148
void print(raw_ostream &OS, const MCAsmInfo *MAI, bool InParens=false) const
Definition: MCExpr.cpp:41
unsigned const MachineRegisterInfo * MRI
MCSymbol * CurrentFnSym
The symbol for the current function.
Definition: AsmPrinter.h:112
MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
Machine Value Type.
bool hasName() const
Definition: Value.h:250
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
const MCAsmInfo * MAI
Target Asm Printer information.
Definition: AsmPrinter.h:84
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const char * getImageHandleSymbol(unsigned Idx) const
Returns the symbol name at the given index.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:41
static bool is64Bit(const char *name)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:223
static MCOperand GetSymbolRef(const MachineOperand &MO, const MCSymbol *Symbol, HexagonAsmPrinter &Printer, bool MustExtend)
const GlobalValue * getGlobal() const
const NVPTXTargetLowering * getTargetLowering() const override
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant...
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:263
size_t alias_size() const
Definition: Module.h:620
double convertToDouble() const
Definition: APFloat.h:1096
TargetMachine & TM
Target machine description.
Definition: AsmPrinter.h:81
std::string getTargetName() const
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:739
This file declares a class to represent arbitrary precision floating point values and provide a varie...
unsigned getMaxAlignment() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
bool hasInternalLinkage() const
Definition: GlobalValue.h:433
bool isHalfTy() const
Return true if this is &#39;half&#39;, a 16-bit IEEE fp type.
Definition: Type.h:143
static const char * getRegisterName(unsigned RegNo)
This class describes a target machine that is implemented with the LLVM target-independent code gener...
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:494
NVPTX::DrvInterface getDrvInterface() const
unsigned size() const
Definition: DenseMap.h:125
Logical negation.
Definition: MCExpr.h:362
Extended Value Type.
Definition: ValueTypes.h:33
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:528
Binary assembler expressions.
Definition: MCExpr.h:416
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
size_t size() const
Definition: SmallVector.h:52
std::string getVirtualRegisterName(unsigned) const
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:4224
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:498
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool getMaxNTIDy(const Function &F, unsigned &y)
bool getReqNTIDx(const Function &F, unsigned &x)
unsigned first
bool hasWeakLinkage() const
Definition: GlobalValue.h:429
const APFloat & getValueAPF() const
Definition: Constants.h:302
bool isImage(const Value &val)
14: Arrays
Definition: Type.h:73
bool getReqNTIDz(const Function &F, unsigned &z)
unsigned getFunctionNumber() const
Return a unique ID for the current function.
Definition: AsmPrinter.cpp:207
static Type * getHalfTy(LLVMContext &C)
Definition: Type.cpp:162
static const fltSemantics & IEEEsingle() LLVM_READNONE
Definition: APFloat.cpp:119
static void printMemOperand(raw_ostream &OS, const MachineMemOperand &MMO, const MachineFunction *MF, const Module *M, const MachineFrameInfo *MFI, const TargetInstrInfo *TII, LLVMContext &Ctx)
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
Definition: User.h:191
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
Equivalent to hasAttribute(ArgNo + FirstArgIndex, Kind).
void setOpcode(unsigned Op)
Definition: MCInst.h:170
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1166
static void ConvertFloatToBytes(unsigned char *p, float val)
std::string * getManagedString(const char *S)
16: SIMD &#39;packed&#39; format, or other vector type
Definition: Type.h:75
static void printMCExpr(const MCExpr *E, raw_ostream &OS)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:129
MCSymbol * getSymbol(const GlobalValue *GV) const
Definition: AsmPrinter.cpp:429
const MCSymbol & getSymbol() const
Definition: MCExpr.h:335
ExprKind getKind() const
Definition: MCExpr.h:72
virtual const MCExpr * lowerConstant(const Constant *CV)
Lower the specified LLVM Constant to an MCExpr.
MachineOperand class - Representation of each machine instruction operand.
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:81
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:845
Module.h This file contains the declarations for the Module class.
bool isVector(MCInstrInfo const &MCII, MCInst const &MCI)
AddressSpace
Definition: NVPTXBaseInfo.h:21
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:729
bool isImageReadWrite(const Value &val)
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition: Type.h:257
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
Definition: AsmPrinter.cpp:230
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
StringRef str()
Return a StringRef for the vector contents.
Definition: raw_ostream.h:534
std::string getSurfaceName(const Value &val)
const char * getName(unsigned RegNo) const
static void VisitGlobalVariableForEmission(const GlobalVariable *GV, SmallVectorImpl< const GlobalVariable *> &Order, DenseSet< const GlobalVariable *> &Visited, DenseSet< const GlobalVariable *> &Visiting)
VisitGlobalVariableForEmission - Add GV to the list of GlobalVariable instances to be emitted...
std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:223
int64_t getImm() const
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:193
const Function & getFunction() const
Return the LLVM function that this machine code represents.
std::string getSamplerName(const Value &val)
Class for arbitrary precision integers.
Definition: APInt.h:69
ConstantArray - Constant Array Declarations.
Definition: Constants.h:413
bool isManaged(const Value &val)
bool getReqNTIDy(const Function &F, unsigned &y)
iterator_range< user_iterator > users()
Definition: Value.h:399
MDNode * GetUnrollMetadata(MDNode *LoopID, StringRef Name)
Given an llvm.loop loop id metadata node, returns the loop hint metadata node with the given name (fo...
Definition: LoopUnroll.cpp:895
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:435
Representation of each machine instruction.
Definition: MachineInstr.h:63
pointer remove(iterator &IT)
Definition: ilist.h:250
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
static bool printOperand(raw_ostream &OS, const SelectionDAG *G, const SDValue Value)
unsigned getParamAlignment(unsigned ArgNo) const
Return the alignment for the specified function parameter.
NVPTXTargetMachine.
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
Definition: AsmPrinter.cpp:247
iterator insert(iterator where, pointer New)
Definition: ilist.h:227
iterator end()
Definition: Module.h:596
const Function * getParent() const
Definition: Argument.h:41
std::string getNVPTXRegClassStr(TargetRegisterClass const *RC)
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:550
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:175
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:122
virtual void EmitBasicBlockStart(const MachineBasicBlock &MBB) const
Targets can override this to emit stuff at the start of a basic block.
static bool usedInGlobalVarDef(const Constant *C)
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:213
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
Definition: Format.h:198
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
#define I(x, y, z)
Definition: MD5.cpp:58
std::string getNVPTXRegClassName(TargetRegisterClass const *RC)
iterator_range< debug_compile_units_iterator > debug_compile_units() const
Return an iterator for all DICompileUnits listed in this Module&#39;s llvm.dbg.cu named metadata node and...
Definition: Module.h:777
iterator begin()
Definition: Module.h:594
iterator end()
Definition: DenseMap.h:108
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
virtual void print(raw_ostream &OS, const Module *M) const
print - Print out the internal state of the pass.
Definition: Pass.cpp:123
References to labels and assigned expressions.
Definition: MCExpr.h:40
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:322
Type * getValueType() const
Definition: GlobalValue.h:275
Unary minus.
Definition: MCExpr.h:363
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:91
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
static const NVPTXFloatMCExpr * createConstantFPHalf(const APFloat &Flt, MCContext &Ctx)
Definition: NVPTXMCExpr.h:43
static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f)
const std::string & getModuleInlineAsm() const
Get any module-scope inline assembly blocks.
Definition: Module.h:247
Opcode getOpcode() const
Get the kind of this binary expression.
Definition: MCExpr.h:560
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:205
3: 64-bit floating point type
Definition: Type.h:59
Implments NVPTX-specific streamer.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Equivalent to hasAttribute(AttributeList::FunctionIndex, Kind) but may be faster. ...
static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool useFuncSeen(const Constant *C, DenseMap< const Function *, bool > &seenMap)
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:482
const MCExpr * getSubExpr() const
Get the child of this unary expression.
Definition: MCExpr.h:406
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition: Type.h:249
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:114
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:72
bool isLoopHeader(const MachineBasicBlock *BB) const
True if the block is a loop header node.
static const char * name
Floating-point immediate operand.
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:418
bool hasInitializer() const
Definitions have initializers, declarations don&#39;t.
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
Constant expressions.
Definition: MCExpr.h:39
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:250
Binary expressions.
Definition: MCExpr.h:38
unsigned int getSmVersion() const
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
uint64_t getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
Definition: DataLayout.h:445
const DataLayout & getDataLayout() const
Return information about data layout.
Definition: AsmPrinter.cpp:215
static void ConvertDoubleToBytes(unsigned char *p, double val)
iterator_range< global_iterator > globals()
Definition: Module.h:583
IRTranslator LLVM IR MI
void addOperand(const MCOperand &Op)
Definition: MCInst.h:183
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
APInt bitcastToAPInt() const
Definition: APFloat.h:1093
bool getMinCTASm(const Function &F, unsigned &x)
Target specific expression.
Definition: MCExpr.h:42
static void ConvertIntToBytes(unsigned char *p, T val)
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:413
Instances of this class represent operands of the MCInst class.
Definition: MCInst.h:34
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects...
static MCOperand createImm(int64_t Val)
Definition: MCInst.h:122
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:173
bool use_empty() const
Definition: Value.h:322
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:163
bool isImageWriteOnly(const Value &val)
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:273
void LLVMInitializeNVPTXAsmPrinter()
bool doFinalization(Module &M) override
Shut down the asmprinter.
This file describes how to lower LLVM code to machine code.
const BasicBlock * getParent() const
Definition: Instruction.h:66
const NVPTXRegisterInfo * getRegisterInfo() const override
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition: MCSymbol.cpp:59