33 #include "llvm/Config/llvm-config.h"
106 if (
const auto *MAV = dyn_cast<MetadataAsValue>(V))
107 if (
const auto *VAM = dyn_cast<ValueAsMetadata>(MAV->getMetadata()))
108 return VAM->getValue();
116 if (
const Constant *
C = dyn_cast<Constant>(V))
117 if (
C->getNumOperands() && !isa<GlobalValue>(
C))
118 for (
const Value *
Op :
C->operands())
119 if (!isa<BasicBlock>(
Op) && !isa<GlobalValue>(
Op))
124 unsigned ID = OM.size() + 1;
132 if (
G.hasInitializer())
133 if (!isa<GlobalValue>(
G.getInitializer()))
138 if (!isa<GlobalValue>(A.getAliasee()))
143 if (!isa<GlobalValue>(
I.getResolver()))
148 for (
const Use &U :
F.operands())
149 if (!isa<GlobalValue>(U.get()))
154 if (
F.isDeclaration())
162 for (
const Value *
Op :
I.operands()) {
164 if ((isa<Constant>(*
Op) && !isa<GlobalValue>(*
Op)) ||
175 static std::vector<unsigned>
178 using Entry = std::pair<const Use *, unsigned>;
182 if (OM.lookup(U.getUser()))
183 List.push_back(std::make_pair(&U,
List.size()));
192 bool GetsReversed = !isa<BasicBlock>(V);
193 if (
auto *BA = dyn_cast<BlockAddress>(V))
194 ID = OM.lookup(BA->getBasicBlock());
196 const Use *LU = L.first;
197 const Use *RU = R.first;
201 auto LID = OM.lookup(LU->getUser());
202 auto RID = OM.lookup(RU->getUser());
222 return LU->getOperandNo() < RU->getOperandNo();
223 return LU->getOperandNo() > RU->getOperandNo();
227 return L.second < R.second;
233 std::vector<unsigned> Shuffle(
List.size());
234 for (
size_t I = 0,
E =
List.size();
I !=
E; ++
I)
235 Shuffle[
I] =
List[
I].second;
242 for (
const auto &Pair : OM) {
243 const Value *V = Pair.first;
247 std::vector<unsigned> Shuffle =
253 if (
auto *
I = dyn_cast<Instruction>(V))
254 F =
I->getFunction();
255 if (
auto *A = dyn_cast<Argument>(V))
257 if (
auto *
BB = dyn_cast<BasicBlock>(V))
265 if (
const Argument *MA = dyn_cast<Argument>(V))
266 return MA->getParent() ? MA->getParent()->getParent() :
nullptr;
269 return BB->getParent() ?
BB->getParent()->getParent() :
nullptr;
272 const Function *
M =
I->getParent() ?
I->getParent()->getParent() :
nullptr;
273 return M ?
M->getParent() :
nullptr;
276 if (
const GlobalValue *GV = dyn_cast<GlobalValue>(V))
277 return GV->getParent();
279 if (
const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
281 if (isa<Instruction>(U))
292 default: Out <<
"cc" << cc;
break;
314 Out <<
"aarch64_sve_vector_pcs";
351 assert(!
Name.empty() &&
"Cannot get empty name!");
354 bool NeedsQuotes = isdigit(
static_cast<unsigned char>(
Name[0]));
356 for (
unsigned char C :
Name) {
361 if (!isalnum(
static_cast<unsigned char>(
C)) &&
C !=
'-' &&
C !=
'.' &&
378 printEscapedString(
Name, OS);
414 if (isa<ScalableVectorType>(Ty))
416 Out <<
Mask.size() <<
" x i32> ";
417 bool FirstElt =
true;
418 if (
all_of(
Mask, [](
int Elt) {
return Elt == 0; })) {
419 Out <<
"zeroinitializer";
424 for (
int Elt :
Mask) {
443 TypePrinting(
const Module *M =
nullptr) : DeferredM(
M) {}
445 TypePrinting(
const TypePrinting &) =
delete;
446 TypePrinting &operator=(
const TypePrinting &) =
delete;
452 std::vector<StructType *> &getNumberedTypes();
461 void incorporateTypes();
471 std::vector<StructType *> NumberedTypes;
481 std::vector<StructType *> &TypePrinting::getNumberedTypes() {
487 if (NumberedTypes.size() == Type2Number.size())
488 return NumberedTypes;
490 NumberedTypes.resize(Type2Number.size());
491 for (
const auto &
P : Type2Number) {
492 assert(
P.second < NumberedTypes.size() &&
"Didn't get a dense numbering?");
493 assert(!NumberedTypes[
P.second] &&
"Didn't get a unique numbering?");
494 NumberedTypes[
P.second] =
P.first;
496 return NumberedTypes;
501 return NamedTypes.empty() && Type2Number.empty();
504 void TypePrinting::incorporateTypes() {
508 NamedTypes.run(*DeferredM,
false);
513 unsigned NextNumber = 0;
515 std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
518 if (STy->isLiteral())
521 if (STy->getName().empty())
522 Type2Number[STy] = NextNumber++;
527 NamedTypes.erase(NextToUse, NamedTypes.end());
548 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
569 return printStructBody(STy, OS);
575 const auto I = Type2Number.find(STy);
576 if (
I != Type2Number.end())
577 OS <<
'%' <<
I->second;
579 OS <<
"%\"type " << STy <<
'\"';
610 OS <<
EC.getKnownMinValue() <<
" x ";
615 case Type::DXILPointerTyID:
616 // DXIL pointer types are only handled by the DirectX backend. To avoid
617 // extra dependencies we just print the pointer's address
here.
618 OS <<
"dxil-ptr (" << Ty <<
")";
649 AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;
653 //===----------------------------------------------------------------------===//
654 // SlotTracker Class: Enumerate slot numbers for unnamed values
655 //===----------------------------------------------------------------------===//
658 class SlotTracker : public AbstractSlotTrackerStorage {
661 using ValueMap = DenseMap<const Value *, unsigned>;
665 const Module* TheModule;
668 const Function* TheFunction = nullptr;
669 bool FunctionProcessed = false;
670 bool ShouldInitializeAllMetadata;
672 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
674 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
675 ProcessFunctionHookFn;
678 const ModuleSummaryIndex *TheIndex = nullptr;
689 DenseMap<const MDNode*, unsigned> mdnMap;
690 unsigned mdnNext = 0;
693 DenseMap<AttributeSet, unsigned> asMap;
697 StringMap<unsigned> ModulePathMap;
698 unsigned ModulePathNext = 0;
701 DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
702 unsigned GUIDNext = 0;
705 StringMap<unsigned> TypeIdMap;
706 unsigned TypeIdNext = 0;
714 explicit SlotTracker(const Module *M,
715 bool ShouldInitializeAllMetadata = false);
722 explicit SlotTracker(const Function *F,
723 bool ShouldInitializeAllMetadata = false);
726 explicit SlotTracker(const ModuleSummaryIndex *Index);
728 SlotTracker(const SlotTracker &) = delete;
729 SlotTracker &operator=(const SlotTracker &) = delete;
731 ~SlotTracker() = default;
734 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);
735 void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,
736 const Function *, bool)>);
738 unsigned getNextMetadataSlot() override { return mdnNext; }
740 void createMetadataSlot(const MDNode *N) override;
744 int getLocalSlot(const Value *V);
745 int getGlobalSlot(const GlobalValue *V);
746 int getMetadataSlot(const MDNode *N) override;
747 int getAttributeGroupSlot(AttributeSet AS);
748 int getModulePathSlot(StringRef Path);
749 int getGUIDSlot(GlobalValue::GUID GUID);
750 int getTypeIdSlot(StringRef Id);
754 void incorporateFunction(const Function *F) {
756 FunctionProcessed = false;
759 const Function *getFunction() const { return TheFunction; }
764 void purgeFunction();
767 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
769 mdn_iterator mdn_begin() { return mdnMap.begin(); }
770 mdn_iterator mdn_end() { return mdnMap.end(); }
771 unsigned mdn_size() const { return mdnMap.size(); }
772 bool mdn_empty() const { return mdnMap.empty(); }
775 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
777 as_iterator as_begin() { return asMap.begin(); }
778 as_iterator as_end() { return asMap.end(); }
779 unsigned as_size() const { return asMap.size(); }
780 bool as_empty() const { return asMap.empty(); }
783 using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
786 inline void initializeIfNeeded();
787 int initializeIndexIfNeeded();
789 // Implementation Details
792 void CreateModuleSlot(const GlobalValue *V);
795 void CreateMetadataSlot(const MDNode *N);
798 void CreateFunctionSlot(const Value *V);
801 void CreateAttributeSetSlot(AttributeSet AS);
803 inline void CreateModulePathSlot(StringRef Path);
804 void CreateGUIDSlot(GlobalValue::GUID GUID);
805 void CreateTypeIdSlot(StringRef Id);
809 void processModule();
810 // Returns number of allocated slots
814 void processFunction();
817 void processGlobalObjectMetadata(const GlobalObject &GO);
820 void processFunctionMetadata(const Function &F);
823 void processInstructionMetadata(const Instruction &I);
826 } // end namespace llvm
828 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
830 : M(M), F(F), Machine(&Machine) {}
832 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
833 bool ShouldInitializeAllMetadata)
834 : ShouldCreateStorage(M),
835 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
837 ModuleSlotTracker::~ModuleSlotTracker() = default;
839 SlotTracker *ModuleSlotTracker::getMachine() {
840 if (!ShouldCreateStorage)
843 ShouldCreateStorage = false;
845 std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
846 Machine = MachineStorage.get();
847 if (ProcessModuleHookFn)
848 Machine->setProcessHook(ProcessModuleHookFn);
849 if (ProcessFunctionHookFn)
850 Machine->setProcessHook(ProcessFunctionHookFn);
854 void ModuleSlotTracker::incorporateFunction(const Function &F) {
855 // Using getMachine() may lazily create the slot tracker.
859 // Nothing to do if this is the right function already.
863 Machine->purgeFunction();
864 Machine->incorporateFunction(&F);
868 int ModuleSlotTracker::getLocalSlot(const Value *V) {
869 assert(F && "No function incorporated");
870 return Machine->getLocalSlot(V);
873 void ModuleSlotTracker::setProcessHook(
874 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
876 ProcessModuleHookFn = Fn;
879 void ModuleSlotTracker::setProcessHook(
880 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
882 ProcessFunctionHookFn = Fn;
885 static SlotTracker *createSlotTracker(const Value *V) {
886 if (const Argument *FA = dyn_cast<Argument>(V))
887 return new SlotTracker(FA->getParent());
889 if (const Instruction *I = dyn_cast<Instruction>(V))
891 return new SlotTracker(I->getParent()->getParent());
893 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
894 return new SlotTracker(BB->getParent());
896 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
897 return new SlotTracker(GV->getParent());
899 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
900 return new SlotTracker(GA->getParent());
902 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
903 return new SlotTracker(GIF->getParent());
905 if (const Function *Func = dyn_cast<Function>(V))
906 return new SlotTracker(Func);
912 #define ST_DEBUG(X) dbgs() << X
917 // Module level constructor. Causes the contents of the Module (sans functions)
918 // to be added to the slot table.
919 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
920 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
922 // Function level constructor. Causes the contents of the Module and the one
923 // function provided to be added to the slot table.
924 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
925 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
926 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
928 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
929 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
931 inline void SlotTracker::initializeIfNeeded() {
934 TheModule = nullptr; ///< Prevent re-processing next time we're
called.
937 if (TheFunction && !FunctionProcessed)
944 int NumSlots = processIndex();
951 void SlotTracker::processModule() {
957 CreateModuleSlot(&Var);
958 processGlobalObjectMetadata(Var);
960 if (
Attrs.hasAttributes())
961 CreateAttributeSetSlot(
Attrs);
966 CreateModuleSlot(&A);
971 CreateModuleSlot(&
I);
976 for (
unsigned i = 0,
e = NMD.getNumOperands();
i !=
e; ++
i)
977 CreateMetadataSlot(NMD.getOperand(
i));
983 CreateModuleSlot(&
F);
985 if (ShouldInitializeAllMetadata)
986 processFunctionMetadata(
F);
992 CreateAttributeSetSlot(FnAttrs);
995 if (ProcessModuleHookFn)
996 ProcessModuleHookFn(
this, TheModule, ShouldInitializeAllMetadata);
1002 void SlotTracker::processFunction() {
1003 ST_DEBUG(
"begin processFunction!\n");
1007 if (!ShouldInitializeAllMetadata)
1008 processFunctionMetadata(*TheFunction);
1012 AE = TheFunction->
arg_end(); AI != AE; ++AI)
1014 CreateFunctionSlot(&*AI);
1016 ST_DEBUG(
"Inserting Instructions:\n");
1019 for (
auto &
BB : *TheFunction) {
1021 CreateFunctionSlot(&
BB);
1023 for (
auto &
I :
BB) {
1024 if (!
I.getType()->isVoidTy() && !
I.hasName())
1025 CreateFunctionSlot(&
I);
1029 if (
const auto *Call = dyn_cast<CallBase>(&
I)) {
1032 if (
Attrs.hasAttributes())
1033 CreateAttributeSetSlot(
Attrs);
1038 if (ProcessFunctionHookFn)
1039 ProcessFunctionHookFn(
this, TheFunction, ShouldInitializeAllMetadata);
1041 FunctionProcessed =
true;
1043 ST_DEBUG(
"end processFunction!\n");
1047 int SlotTracker::processIndex() {
1054 std::map<uint64_t, StringRef> ModuleIdToPathMap;
1056 ModuleIdToPathMap[ModPath.second.first] = ModPath.first();
1057 for (
auto &ModPair : ModuleIdToPathMap)
1058 CreateModulePathSlot(ModPair.second);
1061 GUIDNext = ModulePathNext;
1063 for (
auto &GlobalList : *TheIndex)
1064 CreateGUIDSlot(GlobalList.first);
1066 for (
auto &TId : TheIndex->typeIdCompatibleVtableMap())
1070 TypeIdNext = GUIDNext;
1071 for (
const auto &TID : TheIndex->typeIds())
1072 CreateTypeIdSlot(TID.second.first);
1078 void SlotTracker::processGlobalObjectMetadata(
const GlobalObject &GO) {
1081 for (
auto &MD : MDs)
1082 CreateMetadataSlot(MD.second);
1085 void SlotTracker::processFunctionMetadata(
const Function &
F) {
1086 processGlobalObjectMetadata(
F);
1087 for (
auto &
BB :
F) {
1089 processInstructionMetadata(
I);
1093 void SlotTracker::processInstructionMetadata(
const Instruction &
I) {
1095 if (
const CallInst *CI = dyn_cast<CallInst>(&
I))
1096 if (
Function *
F = CI->getCalledFunction())
1097 if (
F->isIntrinsic())
1098 for (
auto &
Op :
I.operands())
1099 if (
auto *V = dyn_cast_or_null<MetadataAsValue>(
Op))
1100 if (
MDNode *
N = dyn_cast<MDNode>(V->getMetadata()))
1101 CreateMetadataSlot(
N);
1105 I.getAllMetadata(MDs);
1106 for (
auto &MD : MDs)
1107 CreateMetadataSlot(MD.second);
1114 ST_DEBUG(
"begin purgeFunction!\n");
1116 TheFunction =
nullptr;
1117 FunctionProcessed =
false;
1128 return MI == mMap.
end() ? -1 : (
int)
MI->second;
1134 ProcessModuleHookFn = Fn;
1140 ProcessFunctionHookFn = Fn;
1153 return MI == mdnMap.end() ? -1 : (
int)
MI->second;
1158 assert(!isa<Constant>(V) &&
"Can't get a constant or global slot with this!");
1164 return FI == fMap.
end() ? -1 : (
int)FI->second;
1173 return AI == asMap.end() ? -1 : (
int)AI->second;
1181 auto I = ModulePathMap.
find(Path);
1182 return I == ModulePathMap.
end() ? -1 : (
int)
I->second;
1191 return I == GUIDMap.end() ? -1 : (
int)
I->second;
1200 return I == TypeIdMap.
end() ? -1 : (
int)
I->second;
1204 void SlotTracker::CreateModuleSlot(
const GlobalValue *V) {
1205 assert(V &&
"Can't insert a null Value into SlotTracker!");
1209 unsigned DestSlot = mNext++;
1212 ST_DEBUG(
" Inserting value [" << V->
getType() <<
"] = " << V <<
" slot=" <<
1215 ST_DEBUG((isa<GlobalVariable>(V) ?
'G' :
1216 (isa<Function>(V) ?
'F' :
1217 (isa<GlobalAlias>(V) ?
'A' :
1218 (isa<GlobalIFunc>(V) ?
'I' :
'o')))) <<
"]\n");
1222 void SlotTracker::CreateFunctionSlot(
const Value *V) {
1225 unsigned DestSlot = fNext++;
1229 ST_DEBUG(
" Inserting value [" << V->
getType() <<
"] = " << V <<
" slot=" <<
1230 DestSlot <<
" [o]\n");
1234 void SlotTracker::CreateMetadataSlot(
const MDNode *
N) {
1235 assert(
N &&
"Can't insert a null Value into SlotTracker!");
1239 if (isa<DIExpression>(
N) || isa<DIArgList>(
N))
1242 unsigned DestSlot = mdnNext;
1243 if (!mdnMap.insert(std::make_pair(
N, DestSlot)).second)
1248 for (
unsigned i = 0,
e =
N->getNumOperands();
i !=
e; ++
i)
1249 if (
const MDNode *
Op = dyn_cast_or_null<MDNode>(
N->getOperand(
i)))
1250 CreateMetadataSlot(
Op);
1253 void SlotTracker::CreateAttributeSetSlot(
AttributeSet AS) {
1257 if (
I != asMap.end())
1260 unsigned DestSlot = asNext++;
1261 asMap[AS] = DestSlot;
1265 void SlotTracker::CreateModulePathSlot(
StringRef Path) {
1266 ModulePathMap[
Path] = ModulePathNext++;
1271 GUIDMap[GUID] = GUIDNext++;
1275 void SlotTracker::CreateTypeIdSlot(
StringRef Id) {
1276 TypeIdMap[
Id] = TypeIdNext++;
1281 struct AsmWriterContext {
1282 TypePrinting *TypePrinter =
nullptr;
1289 static AsmWriterContext &getEmpty() {
1290 static AsmWriterContext EmptyCtx(
nullptr,
nullptr);
1296 virtual void onWriteMetadataAsOperand(
const Metadata *) {}
1298 virtual ~AsmWriterContext() =
default;
1307 AsmWriterContext &WriterCtx);
1310 AsmWriterContext &WriterCtx,
1311 bool FromValue =
false);
1314 if (
const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))
1315 Out << FPO->getFastMathFlags();
1318 dyn_cast<OverflowingBinaryOperator>(U)) {
1319 if (OBO->hasNoUnsignedWrap())
1321 if (OBO->hasNoSignedWrap())
1324 dyn_cast<PossiblyExactOperator>(U)) {
1328 if (
GEP->isInBounds())
1334 AsmWriterContext &WriterCtx) {
1335 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1336 if (CI->getType()->isIntegerTy(1)) {
1337 Out << (CI->getZExtValue() ?
"true" :
"false");
1340 Out << CI->getValue();
1344 if (
const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1345 const APFloat &APF = CFP->getValueAPF();
1356 bool isNaN = APF.
isNaN();
1357 if (!isInf && !isNaN) {
1367 "[-+]?[0-9] regex does not match!");
1378 static_assert(
sizeof(
double) ==
sizeof(
uint64_t),
1379 "assuming that double is 64 bits!");
1436 if (isa<ConstantAggregateZero>(CV)) {
1437 Out <<
"zeroinitializer";
1441 if (
const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1442 Out <<
"blockaddress(";
1450 if (
const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
1451 Out <<
"dso_local_equivalent ";
1456 if (
const auto *
NC = dyn_cast<NoCFIValue>(CV)) {
1462 if (
const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1463 Type *ETy = CA->getType()->getElementType();
1465 WriterCtx.TypePrinter->print(ETy, Out);
1468 for (
unsigned i = 1,
e = CA->getNumOperands();
i !=
e; ++
i) {
1470 WriterCtx.TypePrinter->print(ETy, Out);
1481 if (CA->isString()) {
1483 printEscapedString(CA->getAsString(), Out);
1488 Type *ETy = CA->getType()->getElementType();
1490 WriterCtx.TypePrinter->print(ETy, Out);
1493 for (
unsigned i = 1,
e = CA->getNumElements();
i !=
e; ++
i) {
1495 WriterCtx.TypePrinter->print(ETy, Out);
1504 if (CS->getType()->isPacked())
1507 unsigned N = CS->getNumOperands();
1510 WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);
1515 for (
unsigned i = 1;
i <
N;
i++) {
1517 WriterCtx.TypePrinter->print(CS->getOperand(
i)->getType(), Out);
1526 if (CS->getType()->isPacked())
1531 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1532 auto *CVVTy = cast<FixedVectorType>(CV->getType());
1533 Type *ETy = CVVTy->getElementType();
1535 WriterCtx.TypePrinter->print(ETy, Out);
1537 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);
1538 for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
1540 WriterCtx.TypePrinter->print(ETy, Out);
1542 WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);
1548 if (isa<ConstantPointerNull>(CV)) {
1553 if (isa<ConstantTokenNone>(CV)) {
1558 if (isa<PoisonValue>(CV)) {
1563 if (isa<UndefValue>(CV)) {
1568 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1569 Out << CE->getOpcodeName();
1570 WriteOptimizationInfo(Out, CE);
1571 if (CE->isCompare())
1572 Out << ' ' << CmpInst::getPredicateName(
1573 static_cast<CmpInst::Predicate>(CE->getPredicate()));
1576 Optional<unsigned> InRangeOp;
1577 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1578 WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);
1580 InRangeOp = GEP->getInRangeIndex();
1585 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1586 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1588 WriterCtx.TypePrinter->print((*OI)->getType(), Out);
1590 WriteAsOperandInternal(Out, *OI, WriterCtx);
1591 if (OI+1 != CE->op_end())
1595 if (CE->hasIndices())
1596 for (unsigned I : CE->getIndices())
1601 WriterCtx.TypePrinter->print(CE->getType(), Out);
1604 if (CE->getOpcode() == Instruction::ShuffleVector)
1605 PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
1611 Out << "<placeholder or erroneous Constant>";
1614 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1615 AsmWriterContext &WriterCtx) {
1617 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1618 const Metadata *MD = Node->getOperand(mi);
1621 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1622 Value *V = MDV->getValue();
1623 WriterCtx.TypePrinter->print(V->getType(), Out);
1625 WriteAsOperandInternal(Out, V, WriterCtx);
1627 WriteAsOperandInternal(Out, MD, WriterCtx);
1628 WriterCtx.onWriteMetadataAsOperand(MD);
1639 struct FieldSeparator {
1643 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1646 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1651 return OS << FS.Sep;
1654 struct MDFieldPrinter {
1657 AsmWriterContext &WriterCtx;
1659 explicit MDFieldPrinter(raw_ostream &Out)
1660 : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
1661 MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
1662 : Out(Out), WriterCtx(Ctx) {}
1664 void printTag(const DINode *N);
1665 void printMacinfoType(const DIMacroNode *N);
1666 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1667 void printString(StringRef Name, StringRef Value,
1668 bool ShouldSkipEmpty = true);
1669 void printMetadata(StringRef Name, const Metadata *MD,
1670 bool ShouldSkipNull = true);
1671 template <class IntTy>
1672 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1673 void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
1674 bool ShouldSkipZero);
1675 void printBool(StringRef Name, bool Value, Optional<bool> Default = None);
1676 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1677 void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1678 template <class IntTy, class Stringifier>
1679 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1680 bool ShouldSkipZero = true);
1681 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1682 void printNameTableKind(StringRef Name,
1683 DICompileUnit::DebugNameTableKind NTK);
1686 } // end anonymous namespace
1688 void MDFieldPrinter::printTag(const DINode *N) {
1689 Out << FS << "tag: ";
1690 auto Tag = dwarf::TagString(N->getTag());
1697 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1698 Out << FS << "type: ";
1699 auto Type = dwarf::MacinfoString(N->getMacinfoType());
1703 Out << N->getMacinfoType();
1706 void MDFieldPrinter::printChecksum(
1707 const DIFile::ChecksumInfo<StringRef> &Checksum) {
1708 Out << FS << "checksumkind: " << Checksum.getKindAsString();
1709 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1712 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1713 bool ShouldSkipEmpty) {
1714 if (ShouldSkipEmpty && Value.empty())
1717 Out << FS << Name << ": \"";
1718 printEscapedString(Value, Out);
1722 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1723 AsmWriterContext &WriterCtx) {
1728 WriteAsOperandInternal(Out, MD, WriterCtx);
1729 WriterCtx.onWriteMetadataAsOperand(MD);
1732 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1733 bool ShouldSkipNull) {
1734 if (ShouldSkipNull && !MD)
1737 Out << FS << Name << ": ";
1738 writeMetadataAsOperand(Out, MD, WriterCtx);
1741 template <class IntTy>
1742 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1743 if (ShouldSkipZero && !Int)
1746 Out << FS << Name << ": " << Int;
1749 void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
1750 bool IsUnsigned, bool ShouldSkipZero) {
1751 if (ShouldSkipZero && Int.isZero())
1754 Out << FS << Name << ": ";
1755 Int.print(Out, !IsUnsigned);
1758 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1759 Optional<bool> Default) {
1760 if (Default && Value == *Default)
1762 Out << FS << Name << ": " << (Value ? "true" : "false");
1765 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1769 Out << FS << Name << ": ";
1771 SmallVector<DINode::DIFlags, 8> SplitFlags;
1772 auto Extra = DINode::splitFlags(Flags, SplitFlags);
1774 FieldSeparator FlagsFS(" | ");
1775 for (auto F : SplitFlags) {
1776 auto StringF = DINode::getFlagString(F);
1777 assert(!StringF.empty() && "Expected valid flag");
1778 Out << FlagsFS << StringF;
1780 if (Extra || SplitFlags.empty())
1781 Out << FlagsFS << Extra;
1784 void MDFieldPrinter::printDISPFlags(StringRef Name,
1785 DISubprogram::DISPFlags Flags) {
1786 // Always print this field, because no flags in the IR at all will be
1787 // interpreted as old-style isDefinition: true.
1788 Out << FS << Name << ": ";
1795 SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
1796 auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
1798 FieldSeparator FlagsFS(" | ");
1799 for (auto F : SplitFlags) {
1800 auto StringF = DISubprogram::getFlagString(F);
1801 assert(!StringF.empty() && "Expected valid flag");
1802 Out << FlagsFS << StringF;
1804 if (Extra || SplitFlags.empty())
1805 Out << FlagsFS << Extra;
1808 void MDFieldPrinter::printEmissionKind(StringRef Name,
1809 DICompileUnit::DebugEmissionKind EK) {
1810 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
1813 void MDFieldPrinter::printNameTableKind(StringRef Name,
1814 DICompileUnit::DebugNameTableKind NTK) {
1815 if (NTK == DICompileUnit::DebugNameTableKind::Default)
1817 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1820 template <class IntTy, class Stringifier>
1821 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1822 Stringifier toString, bool ShouldSkipZero) {
1826 Out << FS << Name << ": ";
1827 auto S = toString(Value);
1834 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1835 AsmWriterContext &WriterCtx) {
1836 Out << "!GenericDINode(";
1837 MDFieldPrinter Printer(Out, WriterCtx);
1838 Printer.printTag(N);
1839 Printer.printString("header", N->getHeader());
1840 if (N->getNumDwarfOperands()) {
1841 Out << Printer.FS << "operands: {";
1843 for (auto &I : N->dwarf_operands()) {
1845 writeMetadataAsOperand(Out, I, WriterCtx);
1852 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1853 AsmWriterContext &WriterCtx) {
1854 Out << "!DILocation(";
1855 MDFieldPrinter Printer(Out, WriterCtx);
1856 // Always output the line, since 0 is a relevant and important value for it.
1857 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1858 Printer.printInt("column", DL->getColumn());
1859 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1860 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1861 Printer.printBool("isImplicitCode", DL->isImplicitCode(),
1862 /* Default */ false);
1866 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1867 AsmWriterContext &WriterCtx) {
1868 Out << "!DISubrange(";
1869 MDFieldPrinter Printer(Out, WriterCtx);
1871 auto *Count = N->getRawCountNode();
1872 if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {
1873 auto *CV = cast<ConstantInt>(CE->getValue());
1874 Printer.printInt("count", CV->getSExtValue(),
1875 /* ShouldSkipZero */ false);
1877 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1879 // A lowerBound of constant 0 should not be skipped, since it is different
1880 // from an unspecified lower bound (= nullptr).
1881 auto *LBound = N->getRawLowerBound();
1882 if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
1883 auto *LV = cast<ConstantInt>(LE->getValue());
1884 Printer.printInt("lowerBound", LV->getSExtValue(),
1885 /* ShouldSkipZero */ false);
1887 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1889 auto *UBound = N->getRawUpperBound();
1890 if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
1891 auto *UV = cast<ConstantInt>(UE->getValue());
1892 Printer.printInt("upperBound", UV->getSExtValue(),
1893 /* ShouldSkipZero */ false);
1895 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1897 auto *Stride = N->getRawStride();
1898 if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
1899 auto *SV = cast<ConstantInt>(SE->getValue());
1900 Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
1902 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1907 static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
1908 AsmWriterContext &WriterCtx) {
1909 Out << "!DIGenericSubrange(";
1910 MDFieldPrinter Printer(Out, WriterCtx);
1912 auto IsConstant = [&](Metadata *Bound) -> bool {
1913 if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
1914 return BE->isConstant() &&
1915 DIExpression::SignedOrUnsignedConstant::SignedConstant ==
1921 auto GetConstant = [&](Metadata *Bound) -> int64_t {
1922 assert(IsConstant(Bound) && "Expected constant");
1923 auto *BE = dyn_cast_or_null<DIExpression>(Bound);
1924 return static_cast<int64_t>(BE->getElement(1));
1927 auto *Count = N->getRawCountNode();
1928 if (IsConstant(Count))
1929 Printer.printInt("count", GetConstant(Count),
1930 /* ShouldSkipZero */ false);
1932 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1934 auto *LBound = N->getRawLowerBound();
1935 if (IsConstant(LBound))
1936 Printer.printInt("lowerBound", GetConstant(LBound),
1937 /* ShouldSkipZero */ false);
1939 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1941 auto *UBound = N->getRawUpperBound();
1942 if (IsConstant(UBound))
1943 Printer.printInt("upperBound", GetConstant(UBound),
1944 /* ShouldSkipZero */ false);
1946 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1948 auto *Stride = N->getRawStride();
1949 if (IsConstant(Stride))
1950 Printer.printInt("stride", GetConstant(Stride),
1951 /* ShouldSkipZero */ false);
1953 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1958 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1959 AsmWriterContext &) {
1960 Out << "!DIEnumerator(";
1961 MDFieldPrinter Printer(Out);
1962 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1963 Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
1964 /*ShouldSkipZero=*/false);
1965 if (N->isUnsigned())
1966 Printer.printBool("isUnsigned", true);
1970 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1971 AsmWriterContext &) {
1972 Out << "!DIBasicType(";
1973 MDFieldPrinter Printer(Out);
1974 if (N->getTag() != dwarf::DW_TAG_base_type)
1975 Printer.printTag(N);
1976 Printer.printString("name", N->getName());
1977 Printer.printInt("size", N->getSizeInBits());
1978 Printer.printInt("align", N->getAlignInBits());
1979 Printer.printDwarfEnum("encoding", N->getEncoding(),
1980 dwarf::AttributeEncodingString);
1981 Printer.printDIFlags("flags", N->getFlags());
1985 static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
1986 AsmWriterContext &WriterCtx) {
1987 Out << "!DIStringType(";
1988 MDFieldPrinter Printer(Out, WriterCtx);
1989 if (N->getTag() != dwarf::DW_TAG_string_type)
1990 Printer.printTag(N);
1991 Printer.printString("name", N->getName());
1992 Printer.printMetadata("stringLength", N->getRawStringLength());
1993 Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
1994 Printer.printMetadata("stringLocationExpression",
1995 N->getRawStringLocationExp());
1996 Printer.printInt("size", N->getSizeInBits());
1997 Printer.printInt("align", N->getAlignInBits());
1998 Printer.printDwarfEnum("encoding", N->getEncoding(),
1999 dwarf::AttributeEncodingString);
2003 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2004 AsmWriterContext &WriterCtx) {
2005 Out << "!DIDerivedType(";
2006 MDFieldPrinter Printer(Out, WriterCtx);
2007 Printer.printTag(N);
2008 Printer.printString("name", N->getName());
2009 Printer.printMetadata("scope", N->getRawScope());
2010 Printer.printMetadata("file", N->getRawFile());
2011 Printer.printInt("line", N->getLine());
2012 Printer.printMetadata("baseType", N->getRawBaseType(),
2013 /* ShouldSkipNull */ false);
2014 Printer.printInt("size", N->getSizeInBits());
2015 Printer.printInt("align", N->getAlignInBits());
2016 Printer.printInt("offset", N->getOffsetInBits());
2017 Printer.printDIFlags("flags", N->getFlags());
2018 Printer.printMetadata("extraData", N->getRawExtraData());
2019 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2020 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
2021 /* ShouldSkipZero */ false);
2022 Printer.printMetadata("annotations", N->getRawAnnotations());
2026 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2027 AsmWriterContext &WriterCtx) {
2028 Out << "!DICompositeType(";
2029 MDFieldPrinter Printer(Out, WriterCtx);
2030 Printer.printTag(N);
2031 Printer.printString("name", N->getName());
2032 Printer.printMetadata("scope", N->getRawScope());
2033 Printer.printMetadata("file", N->getRawFile());
2034 Printer.printInt("line", N->getLine());
2035 Printer.printMetadata("baseType", N->getRawBaseType());
2036 Printer.printInt("size", N->getSizeInBits());
2037 Printer.printInt("align", N->getAlignInBits());
2038 Printer.printInt("offset", N->getOffsetInBits());
2039 Printer.printDIFlags("flags", N->getFlags());
2040 Printer.printMetadata("elements", N->getRawElements());
2041 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
2042 dwarf::LanguageString);
2043 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
2044 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2045 Printer.printString("identifier", N->getIdentifier());
2046 Printer.printMetadata("discriminator", N->getRawDiscriminator());
2047 Printer.printMetadata("dataLocation", N->getRawDataLocation());
2048 Printer.printMetadata("associated", N->getRawAssociated());
2049 Printer.printMetadata("allocated", N->getRawAllocated());
2050 if (auto *RankConst = N->getRankConst())
2051 Printer.printInt("rank", RankConst->getSExtValue(),
2052 /* ShouldSkipZero */ false);
2054 Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2055 Printer.printMetadata("annotations", N->getRawAnnotations());
2059 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2060 AsmWriterContext &WriterCtx) {
2061 Out << "!DISubroutineType(";
2062 MDFieldPrinter Printer(Out, WriterCtx);
2063 Printer.printDIFlags("flags", N->getFlags());
2064 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
2065 Printer.printMetadata("types", N->getRawTypeArray(),
2066 /* ShouldSkipNull */ false);
2070 static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
2072 MDFieldPrinter Printer(Out);
2073 Printer.printString("filename", N->getFilename(),
2074 /* ShouldSkipEmpty */ false);
2075 Printer.printString("directory", N->getDirectory(),
2076 /* ShouldSkipEmpty */ false);
2077 // Print all values for checksum together, or not at all.
2078 if (N->getChecksum())
2079 Printer.printChecksum(*N->getChecksum());
2080 Printer.printString("source", N->getSource().getValueOr(StringRef()),
2081 /* ShouldSkipEmpty */ true);
2085 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2086 AsmWriterContext &WriterCtx) {
2087 Out << "!DICompileUnit(";
2088 MDFieldPrinter Printer(Out, WriterCtx);
2089 Printer.printDwarfEnum("language", N->getSourceLanguage(),
2090 dwarf::LanguageString, /* ShouldSkipZero */ false);
2091 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2092 Printer.printString("producer", N->getProducer());
2093 Printer.printBool("isOptimized", N->isOptimized());
2094 Printer.printString("flags", N->getFlags());
2095 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
2096 /* ShouldSkipZero */ false);
2097 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
2098 Printer.printEmissionKind("emissionKind", N->getEmissionKind());
2099 Printer.printMetadata("enums", N->getRawEnumTypes());
2100 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
2101 Printer.printMetadata("globals", N->getRawGlobalVariables());
2102 Printer.printMetadata("imports", N->getRawImportedEntities());
2103 Printer.printMetadata("macros", N->getRawMacros());
2104 Printer.printInt("dwoId", N->getDWOId());
2105 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
2106 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
2108 Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
2109 Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
2110 Printer.printString("sysroot", N->getSysRoot());
2111 Printer.printString("sdk", N->getSDK());
2115 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2116 AsmWriterContext &WriterCtx) {
2117 Out << "!DISubprogram(";
2118 MDFieldPrinter Printer(Out, WriterCtx);
2119 Printer.printString("name", N->getName());
2120 Printer.printString("linkageName", N->getLinkageName());
2121 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2122 Printer.printMetadata("file", N->getRawFile());
2123 Printer.printInt("line", N->getLine());
2124 Printer.printMetadata("type", N->getRawType());
2125 Printer.printInt("scopeLine", N->getScopeLine());
2126 Printer.printMetadata("containingType", N->getRawContainingType());
2127 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
2128 N->getVirtualIndex() != 0)
2129 Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
2130 Printer.printInt("thisAdjustment", N->getThisAdjustment());
2131 Printer.printDIFlags("flags", N->getFlags());
2132 Printer.printDISPFlags("spFlags", N->getSPFlags());
2133 Printer.printMetadata("unit", N->getRawUnit());
2134 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2135 Printer.printMetadata("declaration", N->getRawDeclaration());
2136 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
2137 Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2138 Printer.printMetadata("annotations", N->getRawAnnotations());
2139 Printer.printString("targetFuncName", N->getTargetFuncName());
2143 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2144 AsmWriterContext &WriterCtx) {
2145 Out << "!DILexicalBlock(";
2146 MDFieldPrinter Printer(Out, WriterCtx);
2147 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2148 Printer.printMetadata("file", N->getRawFile());
2149 Printer.printInt("line", N->getLine());
2150 Printer.printInt("column", N->getColumn());
2154 static void writeDILexicalBlockFile(raw_ostream &Out,
2155 const DILexicalBlockFile *N,
2156 AsmWriterContext &WriterCtx) {
2157 Out << "!DILexicalBlockFile(";
2158 MDFieldPrinter Printer(Out, WriterCtx);
2159 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2160 Printer.printMetadata("file", N->getRawFile());
2161 Printer.printInt("discriminator", N->getDiscriminator(),
2162 /* ShouldSkipZero */ false);
2166 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2167 AsmWriterContext &WriterCtx) {
2168 Out << "!DINamespace(";
2169 MDFieldPrinter Printer(Out, WriterCtx);
2170 Printer.printString("name", N->getName());
2171 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2172 Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2176 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2177 AsmWriterContext &WriterCtx) {
2178 Out << "!DICommonBlock(";
2179 MDFieldPrinter Printer(Out, WriterCtx);
2180 Printer.printMetadata("scope", N->getRawScope(), false);
2181 Printer.printMetadata("declaration", N->getRawDecl(), false);
2182 Printer.printString("name", N->getName());
2183 Printer.printMetadata("file", N->getRawFile());
2184 Printer.printInt("line", N->getLineNo());
2188 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2189 AsmWriterContext &WriterCtx) {
2191 MDFieldPrinter Printer(Out, WriterCtx);
2192 Printer.printMacinfoType(N);
2193 Printer.printInt("line", N->getLine());
2194 Printer.printString("name", N->getName());
2195 Printer.printString("value", N->getValue());
2199 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2200 AsmWriterContext &WriterCtx) {
2201 Out << "!DIMacroFile(";
2202 MDFieldPrinter Printer(Out, WriterCtx);
2203 Printer.printInt("line", N->getLine());
2204 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2205 Printer.printMetadata("nodes", N->getRawElements());
2209 static void writeDIModule(raw_ostream &Out, const DIModule *N,
2210 AsmWriterContext &WriterCtx) {
2211 Out << "!DIModule(";
2212 MDFieldPrinter Printer(Out, WriterCtx);
2213 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2214 Printer.printString("name", N->getName());
2215 Printer.printString("configMacros", N->getConfigurationMacros());
2216 Printer.printString("includePath", N->getIncludePath());
2217 Printer.printString("apinotes", N->getAPINotesFile());
2218 Printer.printMetadata("file", N->getRawFile());
2219 Printer.printInt("line", N->getLineNo());
2220 Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
2224 static void writeDITemplateTypeParameter(raw_ostream &Out,
2225 const DITemplateTypeParameter *N,
2226 AsmWriterContext &WriterCtx) {
2227 Out << "!DITemplateTypeParameter(";
2228 MDFieldPrinter Printer(Out, WriterCtx);
2229 Printer.printString("name", N->getName());
2230 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2231 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2235 static void writeDITemplateValueParameter(raw_ostream &Out,
2236 const DITemplateValueParameter *N,
2237 AsmWriterContext &WriterCtx) {
2238 Out << "!DITemplateValueParameter(";
2239 MDFieldPrinter Printer(Out, WriterCtx);
2240 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2241 Printer.printTag(N);
2242 Printer.printString("name", N->getName());
2243 Printer.printMetadata("type", N->getRawType());
2244 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2245 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2249 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2250 AsmWriterContext &WriterCtx) {
2251 Out << "!DIGlobalVariable(";
2252 MDFieldPrinter Printer(Out, WriterCtx);
2253 Printer.printString("name", N->getName());
2254 Printer.printString("linkageName", N->getLinkageName());
2255 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2256 Printer.printMetadata("file", N->getRawFile());
2257 Printer.printInt("line", N->getLine());
2258 Printer.printMetadata("type", N->getRawType());
2259 Printer.printBool("isLocal", N->isLocalToUnit());
2260 Printer.printBool("isDefinition", N->isDefinition());
2261 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2262 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2263 Printer.printInt("align", N->getAlignInBits());
2264 Printer.printMetadata("annotations", N->getRawAnnotations());
2268 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2269 AsmWriterContext &WriterCtx) {
2270 Out << "!DILocalVariable(";
2271 MDFieldPrinter Printer(Out, WriterCtx);
2272 Printer.printString("name", N->getName());
2273 Printer.printInt("arg", N->getArg());
2274 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2275 Printer.printMetadata("file", N->getRawFile());
2276 Printer.printInt("line", N->getLine());
2277 Printer.printMetadata("type", N->getRawType());
2278 Printer.printDIFlags("flags", N->getFlags());
2279 Printer.printInt("align", N->getAlignInBits());
2280 Printer.printMetadata("annotations", N->getRawAnnotations());
2284 static void writeDILabel(raw_ostream &Out, const DILabel *N,
2285 AsmWriterContext &WriterCtx) {
2287 MDFieldPrinter Printer(Out, WriterCtx);
2288 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2289 Printer.printString("name", N->getName());
2290 Printer.printMetadata("file", N->getRawFile());
2291 Printer.printInt("line", N->getLine());
2295 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2296 AsmWriterContext &WriterCtx) {
2297 Out << "!DIExpression(";
2300 for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
2301 auto OpStr = dwarf::OperationEncodingString(Op.getOp());
2302 assert(!OpStr.empty() && "Expected valid opcode");
2305 if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {
2306 Out << FS << Op.getArg(0);
2307 Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));
2309 for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
2310 Out << FS << Op.getArg(A);
2314 for (const auto &I : N->getElements())
2320 static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
2321 AsmWriterContext &WriterCtx,
2322 bool FromValue = false) {
2324 "Unexpected DIArgList metadata outside of value argument");
2325 Out << "!DIArgList(";
2327 MDFieldPrinter Printer(Out, WriterCtx);
2328 for (Metadata *Arg : N->getArgs()) {
2330 WriteAsOperandInternal(Out, Arg, WriterCtx, true);
2335 static void writeDIGlobalVariableExpression(raw_ostream &Out,
2336 const DIGlobalVariableExpression *N,
2337 AsmWriterContext &WriterCtx) {
2338 Out << "!DIGlobalVariableExpression(";
2339 MDFieldPrinter Printer(Out, WriterCtx);
2340 Printer.printMetadata("var", N->getVariable());
2341 Printer.printMetadata("expr", N->getExpression());
2345 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2346 AsmWriterContext &WriterCtx) {
2347 Out << "!DIObjCProperty(";
2348 MDFieldPrinter Printer(Out, WriterCtx);
2349 Printer.printString("name", N->getName());
2350 Printer.printMetadata("file", N->getRawFile());
2351 Printer.printInt("line", N->getLine());
2352 Printer.printString("setter", N->getSetterName());
2353 Printer.printString("getter", N->getGetterName());
2354 Printer.printInt("attributes", N->getAttributes());
2355 Printer.printMetadata("type", N->getRawType());
2359 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2360 AsmWriterContext &WriterCtx) {
2361 Out << "!DIImportedEntity(";
2362 MDFieldPrinter Printer(Out, WriterCtx);
2363 Printer.printTag(N);
2364 Printer.printString("name", N->getName());
2365 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2366 Printer.printMetadata("entity", N->getRawEntity());
2367 Printer.printMetadata("file", N->getRawFile());
2368 Printer.printInt("line", N->getLine());
2369 Printer.printMetadata("elements", N->getRawElements());
2373 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2374 AsmWriterContext &Ctx) {
2375 if (Node->isDistinct())
2377 else if (Node->isTemporary())
2378 Out << "<temporary!> "; // Handle broken code.
2380 switch (Node->getMetadataID()) {
2382 llvm_unreachable("Expected uniquable MDNode");
2383 #define HANDLE_MDNODE_LEAF(CLASS) \
2384 case Metadata::CLASS##Kind: \
2385 write##CLASS(Out, cast<CLASS>(Node), Ctx); \
2387 #include "llvm/IR/Metadata.def"
2391 // Full implementation of printing a Value as an operand with support for
2392 // TypePrinting, etc.
2393 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2394 AsmWriterContext &WriterCtx) {
2396 PrintLLVMName(Out, V);
2400 const Constant *CV = dyn_cast<Constant>(V);
2401 if (CV && !isa<GlobalValue>(CV)) {
2402 assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
2403 WriteConstantInternal(Out, CV, WriterCtx);
2407 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2409 if (IA->hasSideEffects())
2410 Out << "sideeffect ";
2411 if (IA->isAlignStack())
2412 Out << "alignstack ";
2413 // We don't emit the
AD_ATT dialect
as it's the assumed default.
2414 if (IA->getDialect() == InlineAsm::AD_Intel)
2415 Out << "inteldialect ";
2419 printEscapedString(IA->getAsmString(), Out);
2421 printEscapedString(IA->getConstraintString(), Out);
2426 if (
auto *MD = dyn_cast<MetadataAsValue>(V)) {
2434 auto *
Machine = WriterCtx.Machine;
2437 if (
const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2454 if (
const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2473 AsmWriterContext &WriterCtx,
2477 if (
const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2481 if (
const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {
2486 if (
const MDNode *
N = dyn_cast<MDNode>(MD)) {
2487 std::unique_ptr<SlotTracker> MachineStorage;
2489 if (!WriterCtx.Machine) {
2490 MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);
2491 WriterCtx.Machine = MachineStorage.get();
2493 int Slot = WriterCtx.Machine->getMetadataSlot(
N);
2495 if (
const DILocation *Loc = dyn_cast<DILocation>(
N)) {
2501 Out <<
"<" <<
N <<
">";
2507 if (
const MDString *MDS = dyn_cast<MDString>(MD)) {
2509 printEscapedString(MDS->getString(), Out);
2514 auto *V = cast<ValueAsMetadata>(MD);
2515 assert(WriterCtx.TypePrinter &&
"TypePrinter required for metadata values");
2516 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2517 "Unexpected function-local metadata outside of value argument");
2519 WriterCtx.TypePrinter->print(V->getValue()->
getType(), Out);
2526 class AssemblyWriter {
2528 const Module *TheModule =
nullptr;
2530 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2532 TypePrinting TypePrinter;
2536 bool ShouldPreserveUseListOrder;
2547 bool ShouldPreserveUseListOrder =
false);
2552 AsmWriterContext getContext() {
2553 return AsmWriterContext(&TypePrinter, &
Machine, TheModule);
2556 void printMDNodeBody(
const MDNode *MD);
2559 void printModule(
const Module *M);
2561 void writeOperand(
const Value *
Op,
bool PrintType);
2563 void writeOperandBundles(
const CallBase *Call);
2574 void writeAllMDNodes();
2575 void writeMDNode(
unsigned Slot,
const MDNode *Node);
2576 void writeAttribute(
const Attribute &Attr,
bool InAttrGroup =
false);
2577 void writeAttributeSet(
const AttributeSet &AttrSet,
bool InAttrGroup =
false);
2578 void writeAllAttributeGroups();
2580 void printTypeIdentities();
2584 void printComdat(
const Comdat *
C);
2591 void printUseListOrder(
const Value *V,
const std::vector<unsigned> &Shuffle);
2594 void printModuleSummaryIndex();
2595 void printSummaryInfo(
unsigned Slot,
const ValueInfo &
VI);
2603 void printArgs(
const std::vector<uint64_t> &
Args);
2608 printNonConstVCalls(
const std::vector<FunctionSummary::VFuncId> &VCallList,
2611 printConstVCalls(
const std::vector<FunctionSummary::ConstVCall> &VCallList,
2616 void printMetadataAttachments(
2622 void printInfoComment(
const Value &V);
2633 bool IsForDebug,
bool ShouldPreserveUseListOrder)
2634 : Out(o), TheModule(
M),
Machine(Mac), TypePrinter(
M), AnnotationWriter(AAW),
2635 IsForDebug(IsForDebug),
2636 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2639 for (
const GlobalObject &GO : TheModule->global_objects())
2646 : Out(o), TheIndex(
Index),
Machine(Mac), TypePrinter(nullptr),
2647 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(
false) {}
2649 void AssemblyWriter::writeOperand(
const Value *Operand,
bool PrintType) {
2651 Out <<
"<null operand!>";
2655 TypePrinter.print(Operand->
getType(), Out);
2658 auto WriterCtx = getContext();
2672 Out <<
" syncscope(\"";
2673 printEscapedString(SSNs[SSID], Out);
2683 if (Ordering == AtomicOrdering::NotAtomic)
2686 writeSyncScope(
Context, SSID);
2694 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2695 FailureOrdering != AtomicOrdering::NotAtomic);
2697 writeSyncScope(
Context, SSID);
2702 void AssemblyWriter::writeParamOperand(
const Value *Operand,
2705 Out <<
"<null operand!>";
2710 TypePrinter.print(Operand->
getType(), Out);
2712 if (
Attrs.hasAttributes()) {
2714 writeAttributeSet(
Attrs);
2718 auto WriterCtx = getContext();
2722 void AssemblyWriter::writeOperandBundles(
const CallBase *
Call) {
2723 if (!
Call->hasOperandBundles())
2728 bool FirstBundle =
true;
2729 for (
unsigned i = 0,
e =
Call->getNumOperandBundles();
i !=
e; ++
i) {
2734 FirstBundle =
false;
2742 bool FirstInput =
true;
2743 auto WriterCtx = getContext();
2744 for (
const auto &Input : BU.
Inputs) {
2749 TypePrinter.print(
Input->getType(), Out);
2760 void AssemblyWriter::printModule(
const Module *
M) {
2763 if (ShouldPreserveUseListOrder)
2766 if (!
M->getModuleIdentifier().empty() &&
2769 M->getModuleIdentifier().find(
'\n') == std::string::npos)
2770 Out <<
"; ModuleID = '" <<
M->getModuleIdentifier() <<
"'\n";
2772 if (!
M->getSourceFileName().empty()) {
2773 Out <<
"source_filename = \"";
2774 printEscapedString(
M->getSourceFileName(), Out);
2778 const std::string &
DL =
M->getDataLayoutStr();
2780 Out <<
"target datalayout = \"" <<
DL <<
"\"\n";
2781 if (!
M->getTargetTriple().empty())
2782 Out <<
"target triple = \"" <<
M->getTargetTriple() <<
"\"\n";
2784 if (!
M->getModuleInlineAsm().empty()) {
2791 std::tie(Front,
Asm) =
Asm.split(
'\n');
2795 Out <<
"module asm \"";
2796 printEscapedString(Front, Out);
2798 }
while (!
Asm.empty());
2801 printTypeIdentities();
2804 if (!Comdats.empty())
2806 for (
const Comdat *
C : Comdats) {
2808 if (
C != Comdats.back())
2813 if (!
M->global_empty()) Out <<
'\n';
2815 printGlobal(&GV); Out <<
'\n';
2819 if (!
M->alias_empty()) Out <<
"\n";
2824 if (!
M->ifunc_empty()) Out <<
"\n";
2835 printUseLists(
nullptr);
2840 writeAllAttributeGroups();
2844 if (!
M->named_metadata_empty()) Out <<
'\n';
2847 printNamedMDNode(&Node);
2856 void AssemblyWriter::printModuleSummaryIndex() {
2858 int NumSlots =
Machine.initializeIndexIfNeeded();
2864 std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2865 std::string RegularLTOModuleName =
2866 ModuleSummaryIndex::getRegularLTOModuleName();
2867 moduleVec.resize(TheIndex->modulePaths().size());
2868 for (
auto &ModPath : TheIndex->modulePaths())
2869 moduleVec[
Machine.getModulePathSlot(ModPath.first())] = std::make_pair(
2872 ModPath.second.first == -1u ? RegularLTOModuleName
2873 : (std::string)std::string(ModPath.first()),
2874 ModPath.second.second);
2877 for (
auto &ModPair : moduleVec) {
2878 Out <<
"^" <<
i++ <<
" = module: (";
2880 printEscapedString(ModPair.first, Out);
2881 Out <<
"\", hash: (";
2883 for (
auto Hash : ModPair.second)
2890 for (
auto &GlobalList : *TheIndex) {
2891 auto GUID = GlobalList.first;
2892 for (
auto &Summary : GlobalList.second.SummaryList)
2893 SummaryToGUIDMap[Summary.get()] = GUID;
2897 for (
auto &GlobalList : *TheIndex) {
2898 auto GUID = GlobalList.first;
2899 auto VI = TheIndex->getValueInfo(GlobalList);
2900 printSummaryInfo(
Machine.getGUIDSlot(GUID),
VI);
2904 for (
const auto &TID : TheIndex->typeIds()) {
2905 Out <<
"^" <<
Machine.getTypeIdSlot(TID.second.first)
2906 <<
" = typeid: (name: \"" << TID.second.first <<
"\"";
2907 printTypeIdSummary(TID.second.second);
2908 Out <<
") ; guid = " << TID.first <<
"\n";
2912 for (
auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
2913 auto GUID = GlobalValue::getGUID(TId.first);
2914 Out <<
"^" <<
Machine.getGUIDSlot(GUID)
2915 <<
" = typeidCompatibleVTable: (name: \"" << TId.first <<
"\"";
2916 printTypeIdCompatibleVtableSummary(TId.second);
2917 Out <<
") ; guid = " << GUID <<
"\n";
2921 if (TheIndex->getFlags()) {
2922 Out <<
"^" << NumSlots <<
" = flags: " << TheIndex->getFlags() <<
"\n";
2926 Out <<
"^" << NumSlots <<
" = blockcount: " << TheIndex->getBlockCount()
2933 case WholeProgramDevirtResolution::Indir:
2935 case WholeProgramDevirtResolution::SingleImpl:
2936 return "singleImpl";
2937 case WholeProgramDevirtResolution::BranchFunnel:
2938 return "branchFunnel";
2946 case WholeProgramDevirtResolution::ByArg::Indir:
2948 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2949 return "uniformRetVal";
2950 case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2951 return "uniqueRetVal";
2952 case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2953 return "virtualConstProp";
2962 case TypeTestResolution::Unsat:
2964 case TypeTestResolution::ByteArray:
2966 case TypeTestResolution::Inline:
2970 case TypeTestResolution::AllOnes:
2983 Out <<
", alignLog2: " << TTRes.
AlignLog2;
2985 Out <<
", sizeM1: " << TTRes.
SizeM1;
2988 Out <<
", bitMask: " << (unsigned)TTRes.
BitMask;
2995 void AssemblyWriter::printTypeIdSummary(
const TypeIdSummary &TIS) {
2996 Out <<
", summary: (";
2997 printTypeTestResolution(TIS.
TTRes);
2998 if (!TIS.
WPDRes.empty()) {
2999 Out <<
", wpdResolutions: (";
3001 for (
auto &WPDRes : TIS.
WPDRes) {
3003 Out <<
"(offset: " << WPDRes.first <<
", ";
3004 printWPDRes(WPDRes.second);
3012 void AssemblyWriter::printTypeIdCompatibleVtableSummary(
3014 Out <<
", summary: (";
3016 for (
auto &
P : TI) {
3018 Out <<
"(offset: " <<
P.AddressPointOffset <<
", ";
3019 Out <<
"^" <<
Machine.getGUIDSlot(
P.VTableVI.getGUID());
3025 void AssemblyWriter::printArgs(
const std::vector<uint64_t> &
Args) {
3028 for (
auto arg :
Args) {
3036 Out <<
"wpdRes: (kind: ";
3039 if (WPDRes.
TheKind == WholeProgramDevirtResolution::SingleImpl)
3043 Out <<
", resByArg: (";
3045 for (
auto &ResByArg : WPDRes.
ResByArg) {
3047 printArgs(ResByArg.first);
3048 Out <<
", byArg: (kind: ";
3050 if (ResByArg.second.TheKind ==
3051 WholeProgramDevirtResolution::ByArg::UniformRetVal ||
3052 ResByArg.second.TheKind ==
3053 WholeProgramDevirtResolution::ByArg::UniqueRetVal)
3054 Out <<
", info: " << ResByArg.second.Info;
3058 if (ResByArg.second.Byte || ResByArg.second.Bit)
3059 Out <<
", byte: " << ResByArg.second.Byte
3060 <<
", bit: " << ResByArg.second.Bit;
3071 case GlobalValueSummary::AliasKind:
3073 case GlobalValueSummary::FunctionKind:
3075 case GlobalValueSummary::GlobalVarKind:
3081 void AssemblyWriter::printAliasSummary(
const AliasSummary *AS) {
3082 Out <<
", aliasee: ";
3093 auto VTableFuncs =
GS->vTableFuncs();
3094 Out <<
", varFlags: (readonly: " <<
GS->VarFlags.MaybeReadOnly <<
", "
3095 <<
"writeonly: " <<
GS->VarFlags.MaybeWriteOnly <<
", "
3096 <<
"constant: " <<
GS->VarFlags.Constant;
3097 if (!VTableFuncs.empty())
3099 <<
"vcall_visibility: " <<
GS->VarFlags.VCallVisibility;
3102 if (!VTableFuncs.empty()) {
3103 Out <<
", vTableFuncs: (";
3105 for (
auto &
P : VTableFuncs) {
3107 Out <<
"(virtFunc: ^" <<
Machine.getGUIDSlot(
P.FuncVI.getGUID())
3108 <<
", offset: " <<
P.VTableOffset;
3117 case GlobalValue::ExternalLinkage:
3119 case GlobalValue::PrivateLinkage:
3121 case GlobalValue::InternalLinkage:
3123 case GlobalValue::LinkOnceAnyLinkage:
3125 case GlobalValue::LinkOnceODRLinkage:
3126 return "linkonce_odr";
3127 case GlobalValue::WeakAnyLinkage:
3129 case GlobalValue::WeakODRLinkage:
3131 case GlobalValue::CommonLinkage:
3133 case GlobalValue::AppendingLinkage:
3135 case GlobalValue::ExternalWeakLinkage:
3136 return "extern_weak";
3137 case GlobalValue::AvailableExternallyLinkage:
3138 return "available_externally";
3147 if (
LT == GlobalValue::ExternalLinkage)
3154 case GlobalValue::DefaultVisibility:
3156 case GlobalValue::HiddenVisibility:
3158 case GlobalValue::ProtectedVisibility:
3165 Out <<
", insts: " <<
FS->instCount();
3166 if (
FS->fflags().anyFlagSet())
3167 Out <<
", " <<
FS->fflags();
3169 if (!
FS->calls().empty()) {
3170 Out <<
", calls: (";
3172 for (
auto &
Call :
FS->calls()) {
3174 Out <<
"(callee: ^" <<
Machine.getGUIDSlot(
Call.first.getGUID());
3177 else if (
Call.second.RelBlockFreq)
3178 Out <<
", relbf: " <<
Call.second.RelBlockFreq;
3184 if (
const auto *TIdInfo =
FS->getTypeIdInfo())
3185 printTypeIdInfo(*TIdInfo);
3188 Out <<
"[" << Range.getSignedMin() <<
", " << Range.getSignedMax() <<
"]";
3191 if (!
FS->paramAccesses().empty()) {
3192 Out <<
", params: (";
3194 for (
auto &PS :
FS->paramAccesses()) {
3196 Out <<
"(param: " << PS.ParamNo;
3197 Out <<
", offset: ";
3199 if (!PS.Calls.empty()) {
3200 Out <<
", calls: (";
3202 for (
auto &
Call : PS.Calls) {
3204 Out <<
"(callee: ^" <<
Machine.getGUIDSlot(
Call.Callee.getGUID());
3205 Out <<
", param: " <<
Call.ParamNo;
3206 Out <<
", offset: ";
3207 PrintRange(
Call.Offsets);
3218 void AssemblyWriter::printTypeIdInfo(
3220 Out <<
", typeIdInfo: (";
3221 FieldSeparator TIDFS;
3224 Out <<
"typeTests: (";
3227 auto TidIter = TheIndex->typeIds().equal_range(GUID);
3228 if (TidIter.first == TidIter.second) {
3234 for (
auto It = TidIter.first; It != TidIter.second; ++It) {
3236 auto Slot =
Machine.getTypeIdSlot(It->second.first);
3254 "typeTestAssumeConstVCalls");
3259 "typeCheckedLoadConstVCalls");
3265 auto TidIter = TheIndex->typeIds().equal_range(VFId.
GUID);
3266 if (TidIter.first == TidIter.second) {
3267 Out <<
"vFuncId: (";
3268 Out <<
"guid: " << VFId.
GUID;
3269 Out <<
", offset: " << VFId.
Offset;
3275 for (
auto It = TidIter.first; It != TidIter.second; ++It) {
3277 Out <<
"vFuncId: (";
3278 auto Slot =
Machine.getTypeIdSlot(It->second.first);
3281 Out <<
", offset: " << VFId.
Offset;
3286 void AssemblyWriter::printNonConstVCalls(
3287 const std::vector<FunctionSummary::VFuncId> &VCallList,
const char *
Tag) {
3288 Out <<
Tag <<
": (";
3290 for (
auto &VFuncId : VCallList) {
3292 printVFuncId(VFuncId);
3297 void AssemblyWriter::printConstVCalls(
3298 const std::vector<FunctionSummary::ConstVCall> &VCallList,
3300 Out <<
Tag <<
": (";
3302 for (
auto &ConstVCall : VCallList) {
3305 printVFuncId(ConstVCall.VFunc);
3306 if (!ConstVCall.Args.empty()) {
3308 printArgs(ConstVCall.Args);
3322 Out <<
", visibility: "
3325 Out <<
", live: " << GVFlags.
Live;
3326 Out <<
", dsoLocal: " << GVFlags.
DSOLocal;
3331 printAliasSummary(cast<AliasSummary>(&Summary));
3332 else if (Summary.
getSummaryKind() == GlobalValueSummary::FunctionKind)
3333 printFunctionSummary(cast<FunctionSummary>(&Summary));
3335 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3337 auto RefList = Summary.
refs();
3338 if (!RefList.empty()) {
3341 for (
auto &Ref : RefList) {
3343 if (
Ref.isReadOnly())
3345 else if (
Ref.isWriteOnly())
3346 Out <<
"writeonly ";
3347 Out <<
"^" <<
Machine.getGUIDSlot(
Ref.getGUID());
3355 void AssemblyWriter::printSummaryInfo(
unsigned Slot,
const ValueInfo &
VI) {
3356 Out <<
"^" <<
Slot <<
" = gv: (";
3357 if (!
VI.name().empty())
3358 Out <<
"name: \"" <<
VI.name() <<
"\"";
3360 Out <<
"guid: " <<
VI.getGUID();
3361 if (!
VI.getSummaryList().empty()) {
3362 Out <<
", summaries: (";
3364 for (
auto &Summary :
VI.getSummaryList()) {
3366 printSummary(*Summary);
3371 if (!
VI.name().empty())
3372 Out <<
" ; guid = " <<
VI.getGUID();
3379 Out <<
"<empty name> ";
3381 if (isalpha(
static_cast<unsigned char>(
Name[0])) ||
Name[0] ==
'-' ||
3385 Out <<
'\\' << hexdigit(
Name[0] >> 4) << hexdigit(
Name[0] & 0x0F);
3386 for (
unsigned i = 1,
e =
Name.size();
i !=
e; ++
i) {
3387 unsigned char C =
Name[
i];
3388 if (isalnum(
static_cast<unsigned char>(
C)) ||
C ==
'-' ||
C ==
'$' ||
3389 C ==
'.' ||
C ==
'_')
3392 Out <<
'\\' << hexdigit(
C >> 4) << hexdigit(
C & 0x0F);
3397 void AssemblyWriter::printNamedMDNode(
const NamedMDNode *NMD) {
3409 "DIArgLists should not appear in NamedMDNodes");
3410 if (
auto *Expr = dyn_cast<DIExpression>(
Op)) {
3427 case GlobalValue::DefaultVisibility:
break;
3428 case GlobalValue::HiddenVisibility: Out <<
"hidden ";
break;
3429 case GlobalValue::ProtectedVisibility: Out <<
"protected ";
break;
3436 Out <<
"dso_local ";
3442 case GlobalValue::DefaultStorageClass:
break;
3443 case GlobalValue::DLLImportStorageClass: Out <<
"dllimport ";
break;
3444 case GlobalValue::DLLExportStorageClass: Out <<
"dllexport ";
break;
3451 case GlobalVariable::NotThreadLocal:
3453 case GlobalVariable::GeneralDynamicTLSModel:
3454 Out <<
"thread_local ";
3456 case GlobalVariable::LocalDynamicTLSModel:
3457 Out <<
"thread_local(localdynamic) ";
3459 case GlobalVariable::InitialExecTLSModel:
3460 Out <<
"thread_local(initialexec) ";
3462 case GlobalVariable::LocalExecTLSModel:
3463 Out <<
"thread_local(localexec) ";
3472 case GlobalVariable::UnnamedAddr::Local:
3473 return "local_unnamed_addr";
3474 case GlobalVariable::UnnamedAddr::Global:
3475 return "unnamed_addr";
3486 if (isa<GlobalVariable>(GO))
3500 Out <<
"; Materializable\n";
3521 Out << (GV->
isConstant() ?
"constant " :
"global ");
3530 Out <<
", section \"";
3535 Out <<
", partition \"";
3542 Out <<
", align " <<
A->value();
3546 printMetadataAttachments(MDs,
", ");
3549 if (
Attrs.hasAttributes())
3552 printInfoComment(*GV);
3555 void AssemblyWriter::printAlias(
const GlobalAlias *GA) {
3557 Out <<
"; Materializable\n";
3578 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
3580 TypePrinter.print(GA->
getType(), Out);
3581 Out <<
" <<NULL ALIASEE>>";
3585 Out <<
", partition \"";
3590 printInfoComment(*GA);
3594 void AssemblyWriter::printIFunc(
const GlobalIFunc *GI) {
3596 Out <<
"; Materializable\n";
3614 TypePrinter.print(GI->
getType(), Out);
3615 Out <<
" <<NULL RESOLVER>>";
3619 Out <<
", partition \"";
3624 printInfoComment(*GI);
3628 void AssemblyWriter::printComdat(
const Comdat *
C) {
3632 void AssemblyWriter::printTypeIdentities() {
3633 if (TypePrinter.empty())
3639 auto &NumberedTypes = TypePrinter.getNumberedTypes();
3640 for (
unsigned I = 0,
E = NumberedTypes.size();
I !=
E; ++
I) {
3641 Out <<
'%' <<
I <<
" = type ";
3645 TypePrinter.printStructBody(NumberedTypes[
I], Out);
3649 auto &NamedTypes = TypePrinter.getNamedTypes();
3656 TypePrinter.printStructBody(NamedType, Out);
3662 void AssemblyWriter::printFunction(
const Function *
F) {
3663 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(
F, Out);
3665 if (
F->isMaterializable())
3666 Out <<
"; Materializable\n";
3669 if (
Attrs.hasFnAttrs()) {
3671 std::string AttrStr;
3674 if (!Attr.isStringAttribute()) {
3675 if (!AttrStr.empty()) AttrStr +=
' ';
3676 AttrStr += Attr.getAsString();
3680 if (!AttrStr.empty())
3681 Out <<
"; Function Attrs: " << AttrStr <<
'\n';
3686 if (
F->isDeclaration()) {
3689 F->getAllMetadata(MDs);
3690 printMetadataAttachments(MDs,
" ");
3707 if (
Attrs.hasRetAttrs())
3708 Out <<
Attrs.getAsString(AttributeList::ReturnIndex) <<
' ';
3709 TypePrinter.
print(
F->getReturnType(), Out);
3710 AsmWriterContext WriterCtx(&TypePrinter, &
Machine,
F->getParent());
3716 if (
F->isDeclaration() && !IsForDebug) {
3728 writeAttributeSet(ArgAttrs);
3735 if (
Arg.getArgNo() != 0)
3737 printArgument(&
Arg,
Attrs.getParamAttrs(
Arg.getArgNo()));
3754 if (
F->getAddressSpace() != 0 || !
Mod ||
3756 Out <<
" addrspace(" <<
F->getAddressSpace() <<
")";
3757 if (
Attrs.hasFnAttrs())
3758 Out <<
" #" <<
Machine.getAttributeGroupSlot(
Attrs.getFnAttrs());
3759 if (
F->hasSection()) {
3760 Out <<
" section \"";
3761 printEscapedString(
F->getSection(), Out);
3764 if (
F->hasPartition()) {
3765 Out <<
" partition \"";
3766 printEscapedString(
F->getPartition(), Out);
3771 Out <<
" align " <<
A->value();
3773 Out <<
" gc \"" <<
F->getGC() <<
'"';
3774 if (
F->hasPrefixData()) {
3776 writeOperand(
F->getPrefixData(),
true);
3778 if (
F->hasPrologueData()) {
3779 Out <<
" prologue ";
3780 writeOperand(
F->getPrologueData(),
true);
3782 if (
F->hasPersonalityFn()) {
3783 Out <<
" personality ";
3784 writeOperand(
F->getPersonalityFn(),
true);
3787 if (
F->isDeclaration()) {
3791 F->getAllMetadata(MDs);
3792 printMetadataAttachments(MDs,
" ");
3797 printBasicBlock(&
BB);
3812 TypePrinter.print(
Arg->getType(), Out);
3815 if (
Attrs.hasAttributes()) {
3817 writeAttributeSet(
Attrs);
3821 if (
Arg->hasName()) {
3826 assert(Slot != -1 &&
"expect argument in function here");
3827 Out <<
" %" <<
Slot;
3832 void AssemblyWriter::printBasicBlock(
const BasicBlock *
BB) {
3833 bool IsEntryBlock =
BB->getParent() &&
BB->isEntryBlock();
3834 if (
BB->hasName()) {
3838 }
else if (!IsEntryBlock) {
3847 if (!IsEntryBlock) {
3849 Out.PadToColumn(50);
3854 Out <<
" No predecessors!";
3857 writeOperand(*PI,
false);
3858 for (++PI; PI != PE; ++PI) {
3860 writeOperand(*PI,
false);
3867 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(
BB, Out);
3871 printInstructionLine(
I);
3874 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(
BB, Out);
3878 void AssemblyWriter::printInstructionLine(
const Instruction &
I) {
3879 printInstruction(
I);
3885 void AssemblyWriter::printGCRelocateComment(
const GCRelocateInst &Relocate) {
3895 void AssemblyWriter::printInfoComment(
const Value &V) {
3896 if (
const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
3897 printGCRelocateComment(*Relocate);
3899 if (AnnotationWriter)
3900 AnnotationWriter->printInfoComment(V, Out);
3907 bool PrintAddrSpace = CallAddrSpace != 0;
3908 if (!PrintAddrSpace) {
3914 PrintAddrSpace =
true;
3917 Out <<
" addrspace(" << CallAddrSpace <<
")";
3921 void AssemblyWriter::printInstruction(
const Instruction &
I) {
3922 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&
I, Out);
3931 }
else if (!
I.getType()->isVoidTy()) {
3933 int SlotNum =
Machine.getLocalSlot(&
I);
3935 Out <<
"<badref> = ";
3937 Out <<
'%' << SlotNum <<
" = ";
3940 if (
const CallInst *CI = dyn_cast<CallInst>(&
I)) {
3941 if (CI->isMustTailCall())
3943 else if (CI->isTailCall())
3945 else if (CI->isNoTailCall())
3950 Out <<
I.getOpcodeName();
3953 if ((isa<LoadInst>(
I) && cast<LoadInst>(
I).isAtomic()) ||
3954 (isa<StoreInst>(
I) && cast<StoreInst>(
I).isAtomic()))
3957 if (isa<AtomicCmpXchgInst>(
I) && cast<AtomicCmpXchgInst>(
I).isWeak())
3961 if ((isa<LoadInst>(
I) && cast<LoadInst>(
I).isVolatile()) ||
3962 (isa<StoreInst>(
I) && cast<StoreInst>(
I).isVolatile()) ||
3963 (isa<AtomicCmpXchgInst>(
I) && cast<AtomicCmpXchgInst>(
I).isVolatile()) ||
3964 (isa<AtomicRMWInst>(
I) && cast<AtomicRMWInst>(
I).isVolatile()))
3971 if (
const CmpInst *CI = dyn_cast<CmpInst>(&
I))
3972 Out <<
' ' << CmpInst::getPredicateName(CI->getPredicate());
3976 Out <<
' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
3979 const Value *Operand =
I.getNumOperands() ?
I.getOperand(0) :
nullptr;
3982 if (isa<BranchInst>(
I) && cast<BranchInst>(
I).isConditional()) {
3985 writeOperand(BI.getCondition(),
true);
3987 writeOperand(BI.getSuccessor(0),
true);
3989 writeOperand(BI.getSuccessor(1),
true);
3991 }
else if (isa<SwitchInst>(
I)) {
3995 writeOperand(
SI.getCondition(),
true);
3997 writeOperand(
SI.getDefaultDest(),
true);
3999 for (
auto Case :
SI.cases()) {
4001 writeOperand(Case.getCaseValue(),
true);
4003 writeOperand(Case.getCaseSuccessor(),
true);
4006 }
else if (isa<IndirectBrInst>(
I)) {
4009 writeOperand(Operand,
true);
4012 for (
unsigned i = 1,
e =
I.getNumOperands();
i !=
e; ++
i) {
4015 writeOperand(
I.getOperand(
i),
true);
4018 }
else if (
const PHINode *PN = dyn_cast<PHINode>(&
I)) {
4020 TypePrinter.print(
I.getType(), Out);
4023 for (
unsigned op = 0, Eop = PN->getNumIncomingValues();
op < Eop; ++
op) {
4024 if (
op) Out <<
", ";
4026 writeOperand(PN->getIncomingValue(
op),
false); Out <<
", ";
4027 writeOperand(PN->getIncomingBlock(
op),
false); Out <<
" ]";
4031 writeOperand(
I.getOperand(0),
true);
4032 for (
unsigned i : EVI->indices())
4036 writeOperand(
I.getOperand(0),
true); Out <<
", ";
4037 writeOperand(
I.getOperand(1),
true);
4038 for (
unsigned i : IVI->indices())
4040 }
else if (
const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&
I)) {
4042 TypePrinter.print(
I.getType(), Out);
4043 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
4046 if (LPI->isCleanup())
4049 for (
unsigned i = 0,
e = LPI->getNumClauses();
i !=
e; ++
i) {
4050 if (
i != 0 || LPI->isCleanup()) Out <<
"\n";
4051 if (LPI->isCatch(
i))
4056 writeOperand(LPI->getClause(
i),
true);
4058 }
else if (
const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&
I)) {
4060 writeOperand(CatchSwitch->getParentPad(),
false);
4063 for (
const BasicBlock *PadBB : CatchSwitch->handlers()) {
4066 writeOperand(PadBB,
true);
4070 if (
const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
4071 writeOperand(UnwindDest,
true);
4074 }
else if (
const auto *FPI = dyn_cast<FuncletPadInst>(&
I)) {
4076 writeOperand(FPI->getParentPad(),
false);
4078 for (
unsigned Op = 0, NumOps = FPI->getNumArgOperands();
Op < NumOps;
4082 writeOperand(FPI->getArgOperand(
Op),
true);
4085 }
else if (isa<ReturnInst>(
I) && !Operand) {
4087 }
else if (
const auto *CRI = dyn_cast<CatchReturnInst>(&
I)) {
4089 writeOperand(CRI->getOperand(0),
false);
4092 writeOperand(CRI->getOperand(1),
true);
4093 }
else if (
const auto *CRI = dyn_cast<CleanupReturnInst>(&
I)) {
4095 writeOperand(CRI->getOperand(0),
false);
4098 if (CRI->hasUnwindDest())
4099 writeOperand(CRI->getOperand(1),
true);
4102 }
else if (
const CallInst *CI = dyn_cast<CallInst>(&
I)) {
4109 Operand = CI->getCalledOperand();
4115 Out <<
' ' << PAL.
getAsString(AttributeList::ReturnIndex);
4125 TypePrinter.print(FTy->
isVarArg() ? FTy : RetTy, Out);
4127 writeOperand(Operand,
false);
4129 for (
unsigned op = 0, Eop = CI->arg_size();
op < Eop; ++
op) {
4137 if (CI->isMustTailCall() && CI->getParent() &&
4138 CI->getParent()->getParent() &&
4139 CI->getParent()->getParent()->isVarArg())
4146 writeOperandBundles(CI);
4147 }
else if (
const InvokeInst *II = dyn_cast<InvokeInst>(&
I)) {
4148 Operand = II->getCalledOperand();
4160 Out <<
' ' << PAL.
getAsString(AttributeList::ReturnIndex);
4170 TypePrinter.print(FTy->
isVarArg() ? FTy : RetTy, Out);
4172 writeOperand(Operand,
false);
4174 for (
unsigned op = 0, Eop = II->arg_size();
op < Eop; ++
op) {
4184 writeOperandBundles(II);
4187 writeOperand(II->getNormalDest(),
true);
4189 writeOperand(II->getUnwindDest(),
true);
4190 }
else if (
const CallBrInst *CBI = dyn_cast<CallBrInst>(&
I)) {
4191 Operand = CBI->getCalledOperand();
4203 Out <<
' ' << PAL.
getAsString(AttributeList::ReturnIndex);
4210 TypePrinter.print(FTy->
isVarArg() ? FTy : RetTy, Out);
4212 writeOperand(Operand,
false);
4214 for (
unsigned op = 0, Eop = CBI->arg_size();
op < Eop; ++
op) {
4224 writeOperandBundles(CBI);
4227 writeOperand(CBI->getDefaultDest(),
true);
4229 for (
unsigned i = 0,
e = CBI->getNumIndirectDests();
i !=
e; ++
i) {
4232 writeOperand(CBI->getIndirectDest(
i),
true);
4235 }
else if (
const AllocaInst *AI = dyn_cast<AllocaInst>(&
I)) {
4237 if (AI->isUsedWithInAlloca())
4239 if (AI->isSwiftError())
4240 Out <<
"swifterror ";
4241 TypePrinter.print(AI->getAllocatedType(), Out);
4247 if (!AI->getArraySize() || AI->isArrayAllocation() ||
4248 !AI->getArraySize()->getType()->isIntegerTy(32)) {
4250 writeOperand(AI->getArraySize(),
true);
4253 Out <<
", align " <<
A->value();
4256 unsigned AddrSpace = AI->getType()->getAddressSpace();
4257 if (AddrSpace != 0) {
4258 Out <<
", addrspace(" << AddrSpace <<
')';
4260 }
else if (isa<CastInst>(
I)) {
4263 writeOperand(Operand,
true);
4266 TypePrinter.print(
I.getType(), Out);
4267 }
else if (isa<VAArgInst>(
I)) {
4270 writeOperand(Operand,
true);
4273 TypePrinter.print(
I.getType(), Out);
4274 }
else if (Operand) {
4275 if (
const auto *
GEP = dyn_cast<GetElementPtrInst>(&
I)) {
4277 TypePrinter.print(
GEP->getSourceElementType(), Out);
4279 }
else if (
const auto *LI = dyn_cast<LoadInst>(&
I)) {
4281 TypePrinter.print(LI->getType(), Out);
4288 bool PrintAllTypes =
false;
4292 if (isa<SelectInst>(
I) || isa<StoreInst>(
I) || isa<ShuffleVectorInst>(
I)
4293 || isa<ReturnInst>(
I)) {
4294 PrintAllTypes =
true;
4296 for (
unsigned i = 1,
E =
I.getNumOperands();
i !=
E; ++
i) {
4297 Operand =
I.getOperand(
i);
4300 if (Operand && Operand->
getType() != TheType) {
4301 PrintAllTypes =
true;
4307 if (!PrintAllTypes) {
4309 TypePrinter.print(TheType, Out);
4313 for (
unsigned i = 0,
E =
I.getNumOperands();
i !=
E; ++
i) {
4315 writeOperand(
I.getOperand(
i), PrintAllTypes);
4320 if (
const LoadInst *LI = dyn_cast<LoadInst>(&
I)) {
4322 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4324 Out <<
", align " <<
A->value();
4325 }
else if (
const StoreInst *
SI = dyn_cast<StoreInst>(&
I)) {
4327 writeAtomic(
SI->getContext(),
SI->getOrdering(),
SI->getSyncScopeID());
4329 Out <<
", align " <<
A->value();
4331 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4332 CXI->getFailureOrdering(), CXI->getSyncScopeID());
4333 Out <<
", align " << CXI->getAlign().value();
4334 }
else if (
const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&
I)) {
4335 writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4336 RMWI->getSyncScopeID());
4337 Out <<
", align " << RMWI->getAlign().value();
4338 }
else if (
const FenceInst *FI = dyn_cast<FenceInst>(&
I)) {
4339 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4346 I.getAllMetadata(InstMD);
4347 printMetadataAttachments(InstMD,
", ");
4350 printInfoComment(
I);
4353 void AssemblyWriter::printMetadataAttachments(
4359 if (MDNames.empty())
4360 MDs[0].second->getContext().getMDKindNames(MDNames);
4362 auto WriterCtx = getContext();
4363 for (
const auto &
I : MDs) {
4364 unsigned Kind =
I.first;
4366 if (
Kind < MDNames.size()) {
4370 Out <<
"!<unknown kind #" <<
Kind <<
">";
4376 void AssemblyWriter::writeMDNode(
unsigned Slot,
const MDNode *Node) {
4377 Out <<
'!' <<
Slot <<
" = ";
4378 printMDNodeBody(Node);
4382 void AssemblyWriter::writeAllMDNodes() {
4386 Nodes[
I.second] = cast<MDNode>(
I.first);
4388 for (
unsigned i = 0,
e = Nodes.size();
i !=
e; ++
i) {
4389 writeMDNode(
i, Nodes[
i]);
4393 void AssemblyWriter::printMDNodeBody(
const MDNode *Node) {
4394 auto WriterCtx = getContext();
4398 void AssemblyWriter::writeAttribute(
const Attribute &Attr,
bool InAttrGroup) {
4404 Out << Attribute::getNameFromAttrKind(Attr.
getKindAsEnum());
4407 TypePrinter.print(Ty, Out);
4412 void AssemblyWriter::writeAttributeSet(
const AttributeSet &AttrSet,
4414 bool FirstAttr =
true;
4415 for (
const auto &Attr : AttrSet) {
4418 writeAttribute(Attr, InAttrGroup);
4423 void AssemblyWriter::writeAllAttributeGroups() {
4424 std::vector<std::pair<AttributeSet, unsigned>> asVec;
4425 asVec.resize(
Machine.as_size());
4428 asVec[
I.second] =
I;
4430 for (
const auto &
I : asVec)
4431 Out <<
"attributes #" <<
I.second <<
" = { "
4432 <<
I.first.getAsString(
true) <<
" }\n";
4435 void AssemblyWriter::printUseListOrder(
const Value *V,
4436 const std::vector<unsigned> &Shuffle) {
4437 bool IsInFunction =
Machine.getFunction();
4441 Out <<
"uselistorder";
4442 if (
const BasicBlock *
BB = IsInFunction ?
nullptr : dyn_cast<BasicBlock>(V)) {
4444 writeOperand(
BB->getParent(),
false);
4446 writeOperand(
BB,
false);
4449 writeOperand(V,
true);
4453 assert(Shuffle.size() >= 2 &&
"Shuffle too small");
4455 for (
unsigned I = 1,
E = Shuffle.size();
I !=
E; ++
I)
4456 Out <<
", " << Shuffle[
I];
4460 void AssemblyWriter::printUseLists(
const Function *
F) {
4461 auto It = UseListOrders.find(
F);
4462 if (It == UseListOrders.end())
4465 Out <<
"\n; uselistorder directives\n";
4466 for (
const auto &Pair : It->second)
4467 printUseListOrder(Pair.first, Pair.second);
4475 bool ShouldPreserveUseListOrder,
4476 bool IsForDebug)
const {
4479 AssemblyWriter
W(OS, SlotTable, this->
getParent(), AAW,
4481 ShouldPreserveUseListOrder);
4482 W.printFunction(
this);
4486 bool ShouldPreserveUseListOrder,
4487 bool IsForDebug)
const {
4490 AssemblyWriter
W(OS, SlotTable, this->
getModule(), AAW,
4492 ShouldPreserveUseListOrder);
4493 W.printBasicBlock(
this);
4497 bool ShouldPreserveUseListOrder,
bool IsForDebug)
const {
4500 AssemblyWriter
W(OS, SlotTable,
this, AAW, IsForDebug,
4501 ShouldPreserveUseListOrder);
4502 W.printModule(
this);
4508 AssemblyWriter
W(OS, SlotTable,
getParent(),
nullptr, IsForDebug);
4509 W.printNamedMDNode(
this);
4513 bool IsForDebug)
const {
4520 SlotTable = &*LocalST;
4524 AssemblyWriter
W(OS, *SlotTable,
getParent(),
nullptr, IsForDebug);
4525 W.printNamedMDNode(
this);
4530 ROS <<
" = comdat ";
4537 ROS <<
"exactmatch";
4543 ROS <<
"nodeduplicate";
4555 TP.print(
const_cast<Type*
>(
this), OS);
4561 if (
StructType *STy = dyn_cast<StructType>(
const_cast<Type*
>(
this)))
4564 TP.printStructBody(STy, OS);
4569 if (
const auto *CI = dyn_cast<CallInst>(&
I))
4570 if (
Function *
F = CI->getCalledFunction())
4571 if (
F->isIntrinsic())
4572 for (
auto &
Op :
I.operands())
4573 if (
auto *V = dyn_cast_or_null<MetadataAsValue>(
Op))
4580 bool ShouldInitializeAllMetadata =
false;
4581 if (
auto *
I = dyn_cast<Instruction>(
this))
4583 else if (isa<Function>(
this) || isa<MetadataAsValue>(
this))
4584 ShouldInitializeAllMetadata =
true;
4587 print(ROS, MST, IsForDebug);
4591 bool IsForDebug)
const {
4596 auto incorporateFunction = [&](
const Function *
F) {
4601 if (
const Instruction *
I = dyn_cast<Instruction>(
this)) {
4602 incorporateFunction(
I->getParent() ?
I->getParent()->getParent() :
nullptr);
4604 W.printInstruction(*
I);
4605 }
else if (
const BasicBlock *
BB = dyn_cast<BasicBlock>(
this)) {
4606 incorporateFunction(
BB->getParent());
4608 W.printBasicBlock(
BB);
4609 }
else if (
const GlobalValue *GV = dyn_cast<GlobalValue>(
this)) {
4610 AssemblyWriter
W(OS, SlotTable, GV->
getParent(),
nullptr, IsForDebug);
4613 else if (
const Function *
F = dyn_cast<Function>(GV))
4615 else if (
const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))
4617 else if (
const GlobalIFunc *
I = dyn_cast<GlobalIFunc>(GV))
4621 }
else if (
const MetadataAsValue *V = dyn_cast<MetadataAsValue>(
this)) {
4623 }
else if (
const Constant *
C = dyn_cast<Constant>(
this)) {
4624 TypePrinting TypePrinter;
4625 TypePrinter.print(
C->getType(), OS);
4627 AsmWriterContext WriterCtx(&TypePrinter, MST.
getMachine());
4629 }
else if (isa<InlineAsm>(
this) || isa<Argument>(
this)) {
4641 if (V.
hasName() || isa<GlobalValue>(V) ||
4642 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4643 AsmWriterContext WriterCtx(
nullptr,
Machine,
M);
4652 TypePrinting TypePrinter(MST.
getModule());
4672 M, isa<MetadataAsValue>(
this));
4688 AsmWriterContext &WriterCtx) {
4692 auto *
N = dyn_cast<MDNode>(&MD);
4693 if (!
N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
4701 struct MDTreeAsmWriterContext :
public AsmWriterContext {
4704 using EntryTy = std::pair<unsigned, std::string>;
4714 : AsmWriterContext(TP,
ST,
M),
Level(0U), Visited({InitMD}), MainOS(OS) {}
4716 void onWriteMetadataAsOperand(
const Metadata *MD)
override {
4717 if (Visited.
count(MD))
4727 unsigned InsertIdx = Buffer.size() - 1;
4734 ~MDTreeAsmWriterContext() {
4735 for (
const auto &Entry : Buffer) {
4737 unsigned NumIndent = Entry.first * 2U;
4738 MainOS.
indent(NumIndent) << Entry.second;
4746 bool OnlyAsOperand,
bool PrintAsTree =
false) {
4749 TypePrinting TypePrinter(
M);
4751 std::unique_ptr<AsmWriterContext> WriterCtx;
4752 if (PrintAsTree && !OnlyAsOperand)
4753 WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
4757 std::make_unique<AsmWriterContext>(&TypePrinter, MST.
getMachine(),
M);
4761 auto *
N = dyn_cast<MDNode>(&MD);
4762 if (OnlyAsOperand || !
N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
4786 const Module *M,
bool )
const {
4805 AssemblyWriter
W(OS, SlotTable,
this, IsForDebug);
4806 W.printModuleSummaryIndex();
4810 unsigned UB)
const {
4816 if (
I.second >= LB &&
I.second < UB)
4817 L.push_back(std::make_pair(
I.second,
I.first));
4820 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)