97 cl::desc(
"Lower GPU ctor / dtors to globals on the device."),
100#define DEPOTNAME "__local_depot"
110 if (
const User *U = dyn_cast<User>(V)) {
111 for (
unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
127 if (Visited.
count(GV))
131 if (!Visiting.
insert(GV).second)
149 NVPTX_MC::verifyInstructionPredicates(
MI->getOpcode(),
153 lowerToMCInst(
MI, Inst);
158bool NVPTXAsmPrinter::lowerImageHandleOperand(
const MachineInstr *
MI,
166 if (OpNo == 4 && MO.
isImm()) {
167 lowerImageHandleSymbol(MO.
getImm(), MCOp);
171 lowerImageHandleSymbol(MO.
getImm(), MCOp);
181 if (OpNo == VecSize && MO.
isImm()) {
182 lowerImageHandleSymbol(MO.
getImm(), MCOp);
189 if (OpNo == 0 && MO.
isImm()) {
190 lowerImageHandleSymbol(MO.
getImm(), MCOp);
197 if (OpNo == 1 && MO.
isImm()) {
198 lowerImageHandleSymbol(MO.
getImm(), MCOp);
208void NVPTXAsmPrinter::lowerImageHandleSymbol(
unsigned Index,
MCOperand &MCOp) {
221 if (
MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
229 for (
unsigned i = 0, e =
MI->getNumOperands(); i !=
e; ++i) {
234 if (lowerImageHandleOperand(
MI, i, MCOp)) {
240 if (lowerOperand(MO, MCOp))
290unsigned NVPTXAsmPrinter::encodeVirtualRegister(
unsigned Reg) {
295 unsigned RegNum = RegMap[
Reg];
300 if (RC == &NVPTX::Int1RegsRegClass) {
302 }
else if (RC == &NVPTX::Int16RegsRegClass) {
304 }
else if (RC == &NVPTX::Int32RegsRegClass) {
306 }
else if (RC == &NVPTX::Int64RegsRegClass) {
308 }
else if (RC == &NVPTX::Float32RegsRegClass) {
310 }
else if (RC == &NVPTX::Float64RegsRegClass) {
312 }
else if (RC == &NVPTX::Float16RegsRegClass) {
314 }
else if (RC == &NVPTX::Float16x2RegsRegClass) {
321 Ret |= (RegNum & 0x0FFFFFFF);
326 return Reg & 0x0FFFFFFF;
342 Type *Ty =
F->getReturnType();
354 if (
auto *ITy = dyn_cast<IntegerType>(Ty)) {
355 size = ITy->getBitWidth();
365 O <<
".param .b" <<
size <<
" func_retval0";
366 }
else if (isa<PointerType>(Ty)) {
367 O <<
".param .b" << TLI->getPointerTy(
DL).getSizeInBits()
370 unsigned totalsz =
DL.getTypeAllocSize(Ty);
371 unsigned retAlignment = 0;
373 retAlignment = TLI->getFunctionParamOptimizedAlign(F, Ty,
DL).value();
374 O <<
".param .align " << retAlignment <<
" .b8 func_retval0[" << totalsz
382 for (
unsigned i = 0, e = vtparts.
size(); i != e; ++i) {
384 EVT elemtype = vtparts[i];
386 elems = vtparts[i].getVectorNumElements();
387 elemtype = vtparts[i].getVectorElementType();
390 for (
unsigned j = 0, je = elems;
j != je; ++
j) {
394 O <<
".reg .b" << sz <<
" func_retval" << idx;
409 printReturnValStr(&F, O);
414bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
429 if (
const BasicBlock *PBB = PMBB->getBasicBlock()) {
431 PBB->getTerminator()->getMetadata(LLVMContext::MD_loop)) {
434 if (
MDNode *UnrollCountMD =
436 if (mdconst::extract<ConstantInt>(UnrollCountMD->getOperand(1))
448 if (isLoopHeaderOfNoUnroll(
MBB))
452void NVPTXAsmPrinter::emitFunctionEntryLabel() {
456 if (!GlobalsEmitted) {
458 GlobalsEmitted =
true;
464 emitLinkageDirective(F, O);
469 printReturnValStr(*
MF, O);
474 emitFunctionParamList(F, O);
477 emitKernelFunctionDirectives(*F, O);
487 setAndEmitFunctionVirtualRegisters(*
MF);
504void NVPTXAsmPrinter::emitFunctionBodyStart() {
511void NVPTXAsmPrinter::emitFunctionBodyEnd() {
521void NVPTXAsmPrinter::emitImplicitDef(
const MachineInstr *
MI)
const {
534void NVPTXAsmPrinter::emitKernelFunctionDirectives(
const Function &
F,
539 unsigned reqntidx, reqntidy, reqntidz;
540 bool specified =
false;
555 O <<
".reqntid " << reqntidx <<
", " << reqntidy <<
", " << reqntidz
561 unsigned maxntidx, maxntidy, maxntidz;
577 O <<
".maxntid " << maxntidx <<
", " << maxntidy <<
", " << maxntidz
582 O <<
".minnctapersm " << mincta <<
"\n";
586 O <<
".maxnreg " << maxnreg <<
"\n";
597 assert(
I != VRegMapping.
end() &&
"Bad register class");
601 assert(
VI != RegMap.
end() &&
"Bad virtual register");
602 unsigned MappedVR =
VI->second;
610void NVPTXAsmPrinter::emitVirtualRegister(
unsigned int vr,
616 emitLinkageDirective(F, O);
621 printReturnValStr(F, O);
624 emitFunctionParamList(F, O);
635 return GV->getName() !=
"llvm.used";
638 for (
const User *U :
C->users())
639 if (
const Constant *
C = dyn_cast<Constant>(U))
647 if (
const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
648 if (othergv->getName() ==
"llvm.used")
653 if (
instr->getParent() &&
instr->getParent()->getParent()) {
655 if (oneFunc && (curFunc != oneFunc))
663 for (
const User *UU : U->users())
697 for (
const User *U :
C->users()) {
698 if (
const Constant *cu = dyn_cast<Constant>(U)) {
701 }
else if (
const Instruction *
I = dyn_cast<Instruction>(U)) {
718 if (
F.getAttributes().hasFnAttr(
"nvptx-libcall-callee")) {
719 emitDeclaration(&F, O);
723 if (
F.isDeclaration()) {
726 if (
F.getIntrinsicID())
728 emitDeclaration(&F, O);
731 for (
const User *U :
F.users()) {
732 if (
const Constant *
C = dyn_cast<Constant>(U)) {
737 emitDeclaration(&F, O);
743 emitDeclaration(&F, O);
748 if (!isa<Instruction>(U))
762 emitDeclaration(&F, O);
771 if (!GV)
return true;
773 if (!InitList)
return true;
777void NVPTXAsmPrinter::emitStartOfAsmFile(
Module &M) {
787 emitHeader(M, OS1, *STI);
792 if (M.alias_size()) {
799 "Module has a nontrivial global ctor, which NVPTX does not support.");
805 "Module has a nontrivial global dtor, which NVPTX does not support.");
812 GlobalsEmitted =
false;
817void NVPTXAsmPrinter::emitGlobals(
const Module &M) {
821 emitDeclarations(M, OS2);
836 assert(GVVisited.
size() == M.global_size() &&
"Missed a global variable");
837 assert(GVVisiting.
size() == 0 &&
"Did not fully process a global variable");
844 for (
unsigned i = 0, e =
Globals.size(); i != e; ++i)
845 printModuleLevelGV(Globals[i], OS2,
false, STI);
855 O <<
"// Generated by LLVM NVPTX Back-End\n";
860 O <<
".version " << (PTXVersion / 10) <<
"." << (PTXVersion % 10) <<
"\n";
867 O <<
", texmode_independent";
869 bool HasFullDebugInfo =
false;
871 switch(
CU->getEmissionKind()) {
877 HasFullDebugInfo =
true;
880 if (HasFullDebugInfo)
888 O <<
".address_size ";
903 if (!GlobalsEmitted) {
905 GlobalsEmitted =
true;
919 OutStreamer->emitRawText(
"\t.section\t.debug_loc\t{\t}");
923 TS->outputDwarfFileDirectives();
941void NVPTXAsmPrinter::emitLinkageDirective(
const GlobalValue *V,
944 if (V->hasExternalLinkage()) {
945 if (isa<GlobalVariable>(V)) {
953 }
else if (
V->isDeclaration())
957 }
else if (
V->hasAppendingLinkage()) {
959 msg.append(
"Error: ");
960 msg.append(
"Symbol ");
962 msg.append(std::string(
V->getName()));
963 msg.append(
"has unsupported appending linkage type");
965 }
else if (!
V->hasInternalLinkage() &&
966 !
V->hasPrivateLinkage()) {
972void NVPTXAsmPrinter::printModuleLevelGV(
const GlobalVariable *GVar,
1017 emitPTXGlobalVariable(GVar, O, STI);
1025 const Constant *Initializer =
nullptr;
1030 CI = dyn_cast<ConstantInt>(Initializer);
1039 O <<
"addr_mode_" << i <<
" = ";
1045 O <<
"clamp_to_border";
1048 O <<
"clamp_to_edge";
1059 O <<
"filter_mode = ";
1074 O <<
", force_unnormalized_coords = 1";
1084 if (strncmp(GVar->
getName().
data(),
"unrollpragma", 12) == 0)
1088 if (strncmp(GVar->
getName().
data(),
"filename", 8) == 0)
1094 const Function *demotedFunc =
nullptr;
1096 O <<
"// " << GVar->
getName() <<
" has been demoted\n";
1097 if (localDecls.find(demotedFunc) != localDecls.end())
1098 localDecls[demotedFunc].push_back(GVar);
1100 std::vector<const GlobalVariable *> temp;
1101 temp.push_back(GVar);
1102 localDecls[demotedFunc] = temp;
1108 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1113 ".attribute(.managed) requires PTX version >= 4.0 and sm_30");
1115 O <<
" .attribute(.managed)";
1119 O <<
" .align " <<
A->value();
1121 O <<
" .align " << (int)
DL.getPrefTypeAlign(ETy).value();
1130 O << getPTXFundamentalTypeStr(ETy,
false);
1141 if (!Initializer->
isNullValue() && !isa<UndefValue>(Initializer)) {
1143 printScalarConstant(Initializer, O);
1152 "' is not allowed in addrspace(" +
1153 Twine(PTy->getAddressSpace()) +
")");
1169 ElementSize =
DL.getTypeStoreSize(ETy);
1176 if (!isa<UndefValue>(Initializer) && !Initializer->
isNullValue()) {
1177 AggBuffer aggBuffer(ElementSize, *
this);
1178 bufferAggregateConstant(Initializer, &aggBuffer);
1179 if (aggBuffer.numSymbols()) {
1181 if (ElementSize % ptrSize ||
1182 !aggBuffer.allSymbolsAligned(ptrSize)) {
1186 "initialized packed aggregate with pointers '" +
1188 "' requires at least PTX ISA version 7.1");
1191 O <<
"[" << ElementSize <<
"] = {";
1192 aggBuffer.printBytes(O);
1195 O <<
" .u" << ptrSize * 8 <<
" ";
1197 O <<
"[" << ElementSize / ptrSize <<
"] = {";
1198 aggBuffer.printWords(O);
1204 O <<
"[" << ElementSize <<
"] = {";
1205 aggBuffer.printBytes(O);
1234void NVPTXAsmPrinter::AggBuffer::printSymbol(
unsigned nSym,
raw_ostream &os) {
1235 const Value *
v = Symbols[nSym];
1236 const Value *v0 = SymbolsBeforeStripping[nSym];
1237 if (
const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1241 bool isGenericPointer = PTy && PTy->getAddressSpace() == 0;
1242 if (EmitGeneric && isGenericPointer && !isa<Function>(v)) {
1244 Name->print(os, AP.MAI);
1247 Name->print(os, AP.MAI);
1249 }
else if (
const ConstantExpr *CExpr = dyn_cast<ConstantExpr>(v0)) {
1250 const MCExpr *Expr = AP.lowerConstantForGV(cast<Constant>(CExpr),
false);
1251 AP.printMCExpr(*Expr, os);
1256void NVPTXAsmPrinter::AggBuffer::printBytes(
raw_ostream &os) {
1257 unsigned int ptrSize = AP.MAI->getCodePointerSize();
1258 symbolPosInBuffer.push_back(size);
1259 unsigned int nSym = 0;
1260 unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
1261 for (
unsigned int pos = 0; pos <
size;) {
1264 if (pos != nextSymbolPos) {
1265 os << (
unsigned int)buffer[pos];
1272 std::string symText;
1274 printSymbol(nSym, oss);
1275 for (
unsigned i = 0; i < ptrSize; ++i) {
1279 os <<
"(" << symText <<
")";
1282 nextSymbolPos = symbolPosInBuffer[++nSym];
1283 assert(nextSymbolPos >= pos);
1287void NVPTXAsmPrinter::AggBuffer::printWords(
raw_ostream &os) {
1288 unsigned int ptrSize = AP.MAI->getCodePointerSize();
1289 symbolPosInBuffer.push_back(size);
1290 unsigned int nSym = 0;
1291 unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
1292 assert(nextSymbolPos % ptrSize == 0);
1293 for (
unsigned int pos = 0; pos <
size; pos += ptrSize) {
1296 if (pos == nextSymbolPos) {
1297 printSymbol(nSym, os);
1298 nextSymbolPos = symbolPosInBuffer[++nSym];
1299 assert(nextSymbolPos % ptrSize == 0);
1300 assert(nextSymbolPos >= pos + ptrSize);
1301 }
else if (ptrSize == 4)
1309 if (localDecls.find(f) == localDecls.end())
1312 std::vector<const GlobalVariable *> &gvars = localDecls[
f];
1319 O <<
"\t// demoted variable\n\t";
1320 printModuleLevelGV(GV, O,
true, STI);
1324void NVPTXAsmPrinter::emitPTXAddressSpace(
unsigned int AddressSpace,
1347NVPTXAsmPrinter::getPTXFundamentalTypeStr(
Type *Ty,
bool useB4PTR)
const {
1350 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1353 else if (NumBits <= 64) {
1354 std::string
name =
"u";
1355 return name + utostr(NumBits);
1371 assert((PtrSize == 64 || PtrSize == 32) &&
"Unexpected pointer size");
1389void NVPTXAsmPrinter::emitPTXGlobalVariable(
const GlobalVariable *GVar,
1402 ".attribute(.managed) requires PTX version >= 4.0 and sm_30");
1404 O <<
" .attribute(.managed)";
1407 O <<
" .align " <<
A->value();
1409 O <<
" .align " << (int)
DL.getPrefTypeAlign(ETy).value();
1421 O << getPTXFundamentalTypeStr(ETy);
1427 int64_t ElementSize = 0;
1437 ElementSize =
DL.getTypeStoreSize(ETy);
1458 unsigned paramIndex = 0;
1464 if (
F->arg_empty() && !
F->isVarArg()) {
1471 for (
I =
F->arg_begin(),
E =
F->arg_end();
I !=
E; ++
I, paramIndex++) {
1472 Type *Ty =
I->getType();
1483 std::string sname = std::string(
I->getName());
1485 if (hasImageHandles)
1486 O <<
"\t.param .u64 .ptr .surfref ";
1488 O <<
"\t.param .surfref ";
1489 O << TLI->getParamName(F, paramIndex);
1492 if (hasImageHandles)
1493 O <<
"\t.param .u64 .ptr .texref ";
1495 O <<
"\t.param .texref ";
1496 O << TLI->getParamName(F, paramIndex);
1499 if (hasImageHandles)
1500 O <<
"\t.param .u64 .ptr .samplerref ";
1502 O <<
"\t.param .samplerref ";
1503 O << TLI->getParamName(F, paramIndex);
1509 auto getOptimalAlignForParam = [TLI, &
DL, &PAL,
F,
1511 Align TypeAlign = TLI->getFunctionParamOptimizedAlign(F, Ty,
DL);
1512 MaybeAlign ParamAlign = PAL.getParamAlignment(paramIndex);
1513 return std::max(TypeAlign, ParamAlign.
valueOrOne());
1516 if (!PAL.hasParamAttr(paramIndex, Attribute::ByVal)) {
1522 Align OptimalAlign = getOptimalAlignForParam(Ty);
1524 O <<
"\t.param .align " << OptimalAlign.
value() <<
" .b8 ";
1525 O << TLI->getParamName(F, paramIndex);
1526 O <<
"[" <<
DL.getTypeAllocSize(Ty) <<
"]";
1531 auto *PTy = dyn_cast<PointerType>(Ty);
1532 unsigned PTySizeInBits = 0;
1535 TLI->getPointerTy(
DL, PTy->getAddressSpace()).getSizeInBits();
1536 assert(PTySizeInBits &&
"Invalid pointer size");
1542 O <<
"\t.param .u" << PTySizeInBits <<
" ";
1546 int addrSpace = PTy->getAddressSpace();
1547 switch (addrSpace) {
1552 O <<
".ptr .const ";
1555 O <<
".ptr .shared ";
1558 O <<
".ptr .global ";
1561 Align ParamAlign =
I->getParamAlign().valueOrOne();
1562 O <<
".align " << ParamAlign.
value() <<
" ";
1564 O << TLI->getParamName(F, paramIndex);
1574 O << getPTXFundamentalTypeStr(Ty);
1576 O << TLI->getParamName(F, paramIndex);
1582 if (isa<IntegerType>(Ty)) {
1583 sz = cast<IntegerType>(Ty)->getBitWidth();
1586 assert(PTySizeInBits &&
"Invalid pointer size");
1596 O <<
"\t.param .b" << sz <<
" ";
1598 O <<
"\t.reg .b" << sz <<
" ";
1599 O << TLI->getParamName(F, paramIndex);
1604 Type *ETy = PAL.getParamByValType(paramIndex);
1605 assert(ETy &&
"Param should have byval type");
1607 if (isABI || isKernelFunc) {
1612 Align OptimalAlign =
1614 ? getOptimalAlignForParam(ETy)
1615 : TLI->getFunctionByValParamAlign(
1616 F, ETy, PAL.getParamAlignment(paramIndex).valueOrOne(),
DL);
1618 unsigned sz =
DL.getTypeAllocSize(ETy);
1619 O <<
"\t.param .align " << OptimalAlign.
value() <<
" .b8 ";
1620 O << TLI->getParamName(F, paramIndex);
1621 O <<
"[" << sz <<
"]";
1630 for (
unsigned i = 0, e = vtparts.
size(); i != e; ++i) {
1632 EVT elemtype = vtparts[i];
1634 elems = vtparts[i].getVectorNumElements();
1635 elemtype = vtparts[i].getVectorElementType();
1638 for (
unsigned j = 0, je = elems;
j != je; ++
j) {
1642 O <<
"\t.reg .b" << sz <<
" ";
1643 O << TLI->getParamName(F, paramIndex);
1656 if (
F->isVarArg()) {
1661 O << TLI->getParamName(F, -1) <<
"[]";
1667void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1684 O <<
"\t.reg .b64 \t%SP;\n";
1685 O <<
"\t.reg .b64 \t%SPL;\n";
1687 O <<
"\t.reg .b32 \t%SP;\n";
1688 O <<
"\t.reg .b32 \t%SPL;\n";
1697 for (
unsigned i = 0; i < numVRs; i++) {
1701 int n = regmap.
size();
1702 regmap.
insert(std::make_pair(vr, n + 1));
1717 for (
unsigned i=0; i<
TRI->getNumRegClasses(); i++) {
1722 int n = regmap.
size();
1726 O <<
"\t.reg " << rcname <<
" \t" << rcStr <<
"<" << (n+1)
1737 unsigned int numHex;
1756 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1760 if (
const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1761 printFPConstant(CFP, O);
1764 if (isa<ConstantPointerNull>(CPV)) {
1768 if (
const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1769 bool IsNonGenericPointer =
false;
1771 IsNonGenericPointer =
true;
1773 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1782 if (
const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1783 const MCExpr *
E = lowerConstantForGV(cast<Constant>(Cexpr),
false);
1790void NVPTXAsmPrinter::bufferLEByte(
const Constant *CPV,
int Bytes,
1791 AggBuffer *AggBuffer) {
1793 int AllocSize =
DL.getTypeAllocSize(CPV->
getType());
1797 AggBuffer->addZeros(Bytes ? Bytes : AllocSize);
1802 auto AddIntToBuffer = [AggBuffer, Bytes](
const APInt &Val) {
1803 size_t NumBytes = (Val.getBitWidth() + 7) / 8;
1805 for (
unsigned I = 0;
I < NumBytes; ++
I) {
1806 Buf[
I] = Val.extractBitsAsZExtValue(8,
I * 8);
1808 AggBuffer->addBytes(Buf.data(), NumBytes, Bytes);
1813 if (
const auto CI = dyn_cast<ConstantInt>(CPV)) {
1817 if (
const auto *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1818 if (
const auto *CI =
1823 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1824 Value *
V = Cexpr->getOperand(0)->stripPointerCasts();
1825 AggBuffer->addSymbol(V, Cexpr->getOperand(0));
1826 AggBuffer->addZeros(AllocSize);
1837 AddIntToBuffer(cast<ConstantFP>(CPV)->getValueAPF().bitcastToAPInt());
1841 if (
const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1842 AggBuffer->addSymbol(GVar, GVar);
1843 }
else if (
const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1844 const Value *
v = Cexpr->stripPointerCasts();
1845 AggBuffer->addSymbol(v, Cexpr);
1847 AggBuffer->addZeros(AllocSize);
1854 if (isa<ConstantAggregate>(CPV) || isa<ConstantDataSequential>(CPV)) {
1855 bufferAggregateConstant(CPV, AggBuffer);
1856 if (Bytes > AllocSize)
1857 AggBuffer->addZeros(Bytes - AllocSize);
1858 }
else if (isa<ConstantAggregateZero>(CPV))
1859 AggBuffer->addZeros(Bytes);
1870void NVPTXAsmPrinter::bufferAggregateConstant(
const Constant *CPV,
1871 AggBuffer *aggBuffer) {
1876 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1878 for (
unsigned I = 0,
E =
DL.getTypeAllocSize(CPV->
getType());
I <
E; ++
I) {
1880 aggBuffer->addBytes(&Byte, 1, 1);
1887 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1890 bufferLEByte(cast<Constant>(CPV->
getOperand(i)), 0, aggBuffer);
1895 dyn_cast<ConstantDataSequential>(CPV)) {
1896 if (CDS->getNumElements())
1897 for (
unsigned i = 0; i < CDS->getNumElements(); ++i)
1898 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1903 if (isa<ConstantStruct>(CPV)) {
1908 Bytes =
DL.getStructLayout(ST)->getElementOffset(0) +
1909 DL.getTypeAllocSize(ST) -
1910 DL.getStructLayout(ST)->getElementOffset(i);
1912 Bytes =
DL.getStructLayout(ST)->getElementOffset(i + 1) -
1913 DL.getStructLayout(ST)->getElementOffset(i);
1914 bufferLEByte(cast<Constant>(CPV->
getOperand(i)), Bytes, aggBuffer);
1927NVPTXAsmPrinter::lowerConstantForGV(
const Constant *CV,
bool ProcessingGeneric) {
1933 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1936 if (
const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
1939 if (ProcessingGeneric) {
1951 switch (
CE->getOpcode()) {
1958 return lowerConstantForGV(
C, ProcessingGeneric);
1963 OS <<
"Unsupported expression in static initializer: ";
1964 CE->printAsOperand(
OS,
false,
1969 case Instruction::AddrSpaceCast: {
1972 if (DstTy->getAddressSpace() == 0) {
1973 return lowerConstantForGV(cast<const Constant>(
CE->getOperand(0)),
true);
1977 OS <<
"Unsupported expression in static initializer: ";
1978 CE->printAsOperand(
OS,
false,
1983 case Instruction::GetElementPtr: {
1987 APInt OffsetAI(
DL.getPointerTypeSizeInBits(
CE->getType()), 0);
1988 cast<GEPOperator>(CE)->accumulateConstantOffset(
DL, OffsetAI);
1990 const MCExpr *
Base = lowerConstantForGV(
CE->getOperand(0),
1995 int64_t
Offset = OffsetAI.getSExtValue();
2000 case Instruction::Trunc:
2006 case Instruction::BitCast:
2007 return lowerConstantForGV(
CE->getOperand(0), ProcessingGeneric);
2009 case Instruction::IntToPtr: {
2017 return lowerConstantForGV(Op, ProcessingGeneric);
2020 case Instruction::PtrToInt: {
2026 Type *Ty =
CE->getType();
2028 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2032 if (
DL.getTypeAllocSize(Ty) ==
DL.getTypeAllocSize(
Op->getType()))
2038 unsigned InBits =
DL.getTypeAllocSizeInBits(
Op->getType());
2045 case Instruction::Add: {
2046 const MCExpr *
LHS = lowerConstantForGV(
CE->getOperand(0), ProcessingGeneric);
2047 const MCExpr *
RHS = lowerConstantForGV(
CE->getOperand(1), ProcessingGeneric);
2048 switch (
CE->getOpcode()) {
2060 return cast<MCTargetExpr>(&Expr)->printImpl(
OS,
MAI);
2062 OS << cast<MCConstantExpr>(Expr).getValue();
2088 if (isa<MCConstantExpr>(BE.
getLHS()) || isa<MCSymbolRefExpr>(BE.
getLHS()) ||
2089 isa<NVPTXGenericMCSymbolRefExpr>(BE.
getLHS())) {
2101 if (RHSC->getValue() < 0) {
2102 OS << RHSC->getValue();
2113 if (isa<MCConstantExpr>(BE.
getRHS()) || isa<MCSymbolRefExpr>(BE.
getRHS())) {
2129bool NVPTXAsmPrinter::PrintAsmOperand(
const MachineInstr *
MI,
unsigned OpNo,
2131 if (ExtraCode && ExtraCode[0]) {
2132 if (ExtraCode[1] != 0)
2135 switch (ExtraCode[0]) {
2144 printOperand(
MI, OpNo, O);
2149bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
const MachineInstr *
MI,
2151 const char *ExtraCode,
2153 if (ExtraCode && ExtraCode[0])
2157 printMemOperand(
MI, OpNo, O);
2163void NVPTXAsmPrinter::printOperand(
const MachineInstr *
MI,
int opNum,
2169 if (MO.
getReg() == NVPTX::VRDepot)
2174 emitVirtualRegister(MO.
getReg(), O);
2199void NVPTXAsmPrinter::printMemOperand(
const MachineInstr *
MI,
int opNum,
2201 printOperand(
MI, opNum, O);
2203 if (Modifier && strcmp(Modifier,
"add") == 0) {
2205 printOperand(
MI, opNum + 1, O);
2207 if (
MI->getOperand(opNum + 1).isImm() &&
2208 MI->getOperand(opNum + 1).getImm() == 0)
2211 printOperand(
MI, opNum + 1, O);
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< bool > LowerCtorDtor("amdgpu-lower-global-ctor-dtor", cl::desc("Lower GPU ctor / dtors to globals on the device."), cl::init(true), cl::Hidden)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_EXTERNAL_VISIBILITY
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Looks at all the uses of the given value Returns the Liveness deduced from the uses of this value Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses If the result is MaybeLiveUses might be modified but its content should be ignored(since it might not be complete). DeadArgumentEliminationPass
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
unsigned const TargetRegisterInfo * TRI
Module.h This file contains the declarations for the Module class.
static bool isEmptyXXStructor(GlobalVariable *GV)
static bool usedInOneFunc(const User *U, Function const *&oneFunc)
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,...
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeNVPTXAsmPrinter()
static bool usedInGlobalVarDef(const Constant *C)
static bool useFuncSeen(const Constant *C, DenseMap< const Function *, bool > &seenMap)
static cl::opt< bool > LowerCtorDtor("nvptx-lower-global-ctor-dtor", cl::desc("Lower GPU ctor / dtors to globals on the device."), cl::init(false), cl::Hidden)
static void DiscoverDependentGlobals(const Value *V, DenseSet< const GlobalVariable * > &Globals)
DiscoverDependentGlobals - Return a set of GlobalVariables on which V depends.
static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f)
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallString class.
This file defines the SmallVector class.
opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
APInt bitcastToAPInt() const
Class for arbitrary precision integers.
APInt getLoBits(unsigned numBits) const
Compute an APInt containing numBits lowbits from this APInt.
uint64_t getZExtValue() const
Get zero extended value.
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
This class represents an incoming formal argument to a Function.
MCSymbol * getSymbol(const GlobalValue *GV) const
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
TargetMachine & TM
Target machine description.
virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS)
Print the MachineOperand as a symbol.
const MCAsmInfo * MAI
Target Asm Printer information.
MachineFunction * MF
The current machine function.
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
unsigned getFunctionNumber() const
Return a unique ID for the current function.
MCSymbol * CurrentFnSym
The symbol for the current function.
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
MCContext & OutContext
This is the context for the output file that we are streaming.
bool doFinalization(Module &M) override
Shut down the asmprinter.
MCSymbol * GetExternalSymbolSymbol(StringRef Sym) const
Return the MCSymbol for the specified ExternalSymbol.
virtual void emitBasicBlockStart(const MachineBasicBlock &MBB)
Targets can override this to emit stuff at the start of a basic block.
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
const DataLayout & getDataLayout() const
Return information about data layout.
void emitInitialRawDwarfLocDirective(const MachineFunction &MF)
Emits inital debug location directive.
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
LLVM Basic Block Representation.
const Function * getParent() const
Return the enclosing method, or null if none.
ConstantArray - Constant Array Declarations.
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
A constant value that is initialized with an expression using other constant values.
static Constant * getIntegerCast(Constant *C, Type *Ty, bool IsSigned)
Create a ZExt, Bitcast or Trunc for integer -> integer casts.
ConstantFP - Floating Point Values [float, double].
const APFloat & getValueAPF() const
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
const APInt & getValue() const
Return the constant as an APInt value reference.
This is an important base class in LLVM.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
A parsed version of the target data layout string in and methods for querying it.
iterator find(const_arg_type_t< KeyT > Val)
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
StringRef getSection() const
Get the custom section of this global if it has one.
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
bool hasSection() const
Check if this global has a custom object file section.
bool hasLinkOnceLinkage() const
bool hasExternalLinkage() const
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasPrivateLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
bool hasInternalLinkage() const
PointerType * getType() const
Global values are always pointers.
bool hasWeakLinkage() const
bool hasCommonLinkage() const
bool hasAvailableExternallyLinkage() const
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
This class describes a target machine that is implemented with the LLVM target-independent code gener...
unsigned getCodePointerSize() const
Get the code pointer size in bytes.
Binary assembler expressions.
const MCExpr * getLHS() const
Get the left-hand side expression of the binary operator.
const MCExpr * getRHS() const
Get the right-hand side expression of the binary operator.
static const MCBinaryExpr * createAnd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Opcode getOpcode() const
Get the kind of this binary expression.
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Context object for machine code objects.
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Base class for the full range of assembler expressions which are needed for parsing.
@ Unary
Unary expressions.
@ Constant
Constant expressions.
@ SymbolRef
References to labels and assigned expressions.
@ Target
Target specific expression.
@ Binary
Binary expressions.
Instances of this class represent a single low-level machine instruction.
void addOperand(const MCOperand Op)
void setOpcode(unsigned Op)
Describe properties that are true of each instruction in the target description file.
Instances of this class represent operands of the MCInst class.
static MCOperand createReg(unsigned Reg)
static MCOperand createExpr(const MCExpr *Val)
static MCOperand createImm(int64_t Val)
Represent a reference to a symbol from inside an expression.
const MCSymbol & getSymbol() const
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Unary assembler expressions.
Opcode getOpcode() const
Get the kind of this unary expression.
const MCExpr * getSubExpr() const
Get the child of this unary expression.
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
iterator_range< pred_iterator > predecessors()
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
Align getMaxAlign() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Representation of each machine instruction.
bool isLoopHeader(const MachineBasicBlock *BB) const
True if the block is a loop header node.
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
bool hasDebugInfo() const
Returns true if valid debug info is present.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
MachineBasicBlock * getMBB() const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
@ MO_Immediate
Immediate operand.
@ MO_GlobalAddress
Address of a global value.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_FPImmediate
Floating-point immediate operand.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
A Module instance is used to store all the information related to an LLVM module.
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
bool runOnMachineFunction(MachineFunction &F) override
Emit the specified function out to the OutStreamer.
std::string getVirtualRegisterName(unsigned) const
bool doFinalization(Module &M) override
Shut down the asmprinter.
const MCSymbol * getFunctionFrameSymbol() const override
Return symbol for the function pseudo stack if the stack frame is not a register based.
static const NVPTXFloatMCExpr * createConstantFPHalf(const APFloat &Flt, MCContext &Ctx)
static const NVPTXFloatMCExpr * createConstantFPSingle(const APFloat &Flt, MCContext &Ctx)
static const NVPTXFloatMCExpr * createConstantFPDouble(const APFloat &Flt, MCContext &Ctx)
static const NVPTXGenericMCSymbolRefExpr * create(const MCSymbolRefExpr *SymExpr, MCContext &Ctx)
static const char * getRegisterName(MCRegister Reg)
const char * getImageHandleSymbol(unsigned Idx) const
Returns the symbol name at the given index.
const char * getName(unsigned RegNo) const
std::string getTargetName() const
bool hasImageHandles() const
unsigned getMaxRequiredAlignment() const
bool hasMaskOperator() const
const NVPTXTargetLowering * getTargetLowering() const override
unsigned getPTXVersion() const
const NVPTXRegisterInfo * getRegisterInfo() const override
unsigned int getSmVersion() const
NVPTX::DrvInterface getDrvInterface() const
const NVPTXSubtarget * getSubtargetImpl(const Function &) const override
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
UniqueStringSaver & getStrPool() const
Implments NVPTX-specific streamer.
void closeLastSection()
Close last section.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Wrapper class representing virtual and physical registers.
bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
bool startswith(StringRef Prefix) const
const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Class to represent struct types.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
unsigned getPointerSizeInBits(unsigned AS) const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isPointerTy() const
True if this is an instance of PointerType.
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ HalfTyID
16-bit floating point type
@ VoidTyID
type with no size
@ FloatTyID
32-bit floating point type
@ IntegerTyID
Arbitrary bit width integers.
@ FixedVectorTyID
Fixed width SIMD vector type.
@ BFloatTyID
16-bit floating point type (7-bit significand)
@ DoubleTyID
64-bit floating point type
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isAggregateType() const
Return true if the type is an aggregate type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
TypeID getTypeID() const
Return the type id for the type.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
StringRef save(const char *S)
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
bool erase(const ValueT &V)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
A raw_ostream that writes to an SmallVector or SmallString.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
LegalityPredicate isVector(unsigned TypeIdx)
True iff the specified type index is a vector.
@ CE
Windows NT (Windows on ARM)
Reg
All possible values of the reg field in the ModR/M byte.
initializer< Ty > init(const Ty &Val)
uint64_t read64le(const void *P)
uint32_t read32le(const void *P)
This is an optimization pass for GlobalISel generic memory operations.
void ComputeValueVTs(const TargetLowering &TLI, const DataLayout &DL, Type *Ty, SmallVectorImpl< EVT > &ValueVTs, SmallVectorImpl< TypeSize > *Offsets, TypeSize StartingOffset)
ComputeValueVTs - Given an LLVM IR type, compute a sequence of EVTs that represent all the individual...
bool shouldEmitPTXNoReturn(const Value *V, const TargetMachine &TM)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
std::string getSamplerName(const Value &val)
bool getAlign(const Function &F, unsigned index, unsigned &align)
bool getMinCTASm(const Function &F, unsigned &x)
std::string getNVPTXRegClassName(TargetRegisterClass const *RC)
bool isImage(const Value &val)
bool getMaxNTIDz(const Function &F, unsigned &z)
Constant * ConstantFoldConstant(const Constant *C, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldConstant - Fold the constant using the specified DataLayout.
bool isManaged(const Value &val)
unsigned promoteScalarArgumentSize(unsigned size)
bool isSurface(const Value &val)
void clearAnnotationCache(const Module *Mod)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
std::string getSurfaceName(const Value &val)
bool getReqNTIDx(const Function &F, unsigned &x)
bool getReqNTIDy(const Function &F, unsigned &y)
FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, bool Upper=false)
format_hex_no_prefix - Output N as a fixed width hexadecimal.
bool getMaxNReg(const Function &F, unsigned &x)
bool isTexture(const Value &val)
bool isImageWriteOnly(const Value &val)
bool isImageReadWrite(const Value &val)
void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, std::optional< size_t > Width=std::nullopt)
std::string getTextureName(const Value &val)
std::string getNVPTXRegClassStr(TargetRegisterClass const *RC)
Target & getTheNVPTXTarget64()
bool isKernelFunction(const Function &F)
bool getReqNTIDz(const Function &F, unsigned &z)
bool getMaxNTIDx(const Function &F, unsigned &x)
bool getMaxNTIDy(const Function &F, unsigned &y)
bool isSampler(const Value &val)
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...
Target & getTheNVPTXTarget32()
static const fltSemantics & IEEEsingle() LLVM_READNONE
static constexpr roundingMode rmNearestTiesToEven
static const fltSemantics & IEEEdouble() LLVM_READNONE
This struct is a compact representation of a valid (non-zero power of two) alignment.
uint64_t value() const
This is a hole in the type system and should not be abused.
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
bool isInteger() const
Return true if this is an integer or a vector integer type.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...