31 #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();
232 for (
size_t I = 0,
E =
List.size();
I !=
E; ++
I)
240 for (
const auto &Pair : OM) {
241 const Value *V = Pair.first;
245 std::vector<unsigned>
Shuffle =
251 if (
auto *
I = dyn_cast<Instruction>(V))
252 F =
I->getFunction();
253 if (
auto *A = dyn_cast<Argument>(V))
255 if (
auto *
BB = dyn_cast<BasicBlock>(V))
263 if (
const Argument *MA = dyn_cast<Argument>(V))
264 return MA->getParent() ? MA->getParent()->getParent() :
nullptr;
267 return BB->getParent() ?
BB->getParent()->getParent() :
nullptr;
270 const Function *
M =
I->getParent() ?
I->getParent()->getParent() :
nullptr;
271 return M ?
M->getParent() :
nullptr;
274 if (
const GlobalValue *GV = dyn_cast<GlobalValue>(V))
275 return GV->getParent();
277 if (
const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
279 if (isa<Instruction>(U))
290 default: Out <<
"cc" << cc;
break;
312 Out <<
"aarch64_sve_vector_pcs";
315 Out <<
"aarch64_sme_preservemost_from_x0";
318 Out <<
"aarch64_sme_preservemost_from_x2";
355 assert(!Name.empty() &&
"Cannot get empty name!");
358 bool NeedsQuotes = isdigit(
static_cast<unsigned char>(Name[0]));
360 for (
unsigned char C : Name) {
365 if (!isalnum(
static_cast<unsigned char>(
C)) &&
C !=
'-' &&
C !=
'.' &&
382 printEscapedString(Name, OS);
418 if (isa<ScalableVectorType>(Ty))
420 Out <<
Mask.size() <<
" x i32> ";
421 bool FirstElt =
true;
422 if (
all_of(
Mask, [](
int Elt) {
return Elt == 0; })) {
423 Out <<
"zeroinitializer";
428 for (
int Elt :
Mask) {
447 TypePrinting(
const Module *M =
nullptr) : DeferredM(
M) {}
449 TypePrinting(
const TypePrinting &) =
delete;
450 TypePrinting &operator=(
const TypePrinting &) =
delete;
456 std::vector<StructType *> &getNumberedTypes();
465 void incorporateTypes();
475 std::vector<StructType *> NumberedTypes;
485 std::vector<StructType *> &TypePrinting::getNumberedTypes() {
491 if (NumberedTypes.size() == Type2Number.size())
492 return NumberedTypes;
494 NumberedTypes.resize(Type2Number.size());
495 for (
const auto &
P : Type2Number) {
496 assert(
P.second < NumberedTypes.size() &&
"Didn't get a dense numbering?");
497 assert(!NumberedTypes[
P.second] &&
"Didn't get a unique numbering?");
498 NumberedTypes[
P.second] =
P.first;
500 return NumberedTypes;
503 bool TypePrinting::empty() {
505 return NamedTypes.empty() && Type2Number.empty();
508 void TypePrinting::incorporateTypes() {
512 NamedTypes.run(*DeferredM,
false);
517 unsigned NextNumber = 0;
519 std::vector<StructType *>::iterator NextToUse = NamedTypes.begin();
522 if (STy->isLiteral())
525 if (STy->getName().empty())
526 Type2Number[STy] = NextNumber++;
531 NamedTypes.erase(NextToUse, NamedTypes.end());
552 OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
573 return printStructBody(STy, OS);
579 const auto I = Type2Number.find(STy);
580 if (
I != Type2Number.end())
581 OS <<
'%' <<
I->second;
583 OS <<
"%\"type " << STy <<
'\"';
614 OS <<
EC.getKnownMinValue() <<
" x ";
619 case Type::TypedPointerTyID: {
620 TypedPointerType *TPTy = cast<TypedPointerType>(Ty);
621 OS << "typedptr(" << *TPTy->getElementType() << ", "
622 << TPTy->getAddressSpace() << ")";
625 case Type::TargetExtTyID:
626 TargetExtType *TETy = cast<TargetExtType>(Ty);
628 printEscapedString(Ty->getTargetExtName(), OS);
630 for (Type *Inner : TETy->type_params())
631 OS << ", " << *Inner;
632 for (unsigned IntParam : TETy->int_params())
633 OS << ", " << IntParam;
637 llvm_unreachable("Invalid TypeID");
640 void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
641 if (STy->isOpaque()) {
649 if (STy->getNumElements() == 0) {
654 for (Type *Ty : STy->elements()) {
665 AbstractSlotTrackerStorage::~AbstractSlotTrackerStorage() = default;
669 //===----------------------------------------------------------------------===//
670 // SlotTracker Class: Enumerate slot numbers for unnamed values
671 //===----------------------------------------------------------------------===//
674 class SlotTracker : public AbstractSlotTrackerStorage {
677 using ValueMap = DenseMap<const Value *, unsigned>;
681 const Module* TheModule;
684 const Function* TheFunction = nullptr;
685 bool FunctionProcessed = false;
686 bool ShouldInitializeAllMetadata;
688 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
690 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
691 ProcessFunctionHookFn;
694 const ModuleSummaryIndex *TheIndex = nullptr;
705 DenseMap<const MDNode*, unsigned> mdnMap;
706 unsigned mdnNext = 0;
709 DenseMap<AttributeSet, unsigned> asMap;
713 StringMap<unsigned> ModulePathMap;
714 unsigned ModulePathNext = 0;
717 DenseMap<GlobalValue::GUID, unsigned> GUIDMap;
718 unsigned GUIDNext = 0;
721 StringMap<unsigned> TypeIdMap;
722 unsigned TypeIdNext = 0;
730 explicit SlotTracker(const Module *M,
731 bool ShouldInitializeAllMetadata = false);
738 explicit SlotTracker(const Function *F,
739 bool ShouldInitializeAllMetadata = false);
742 explicit SlotTracker(const ModuleSummaryIndex *Index);
744 SlotTracker(const SlotTracker &) = delete;
745 SlotTracker &operator=(const SlotTracker &) = delete;
747 ~SlotTracker() = default;
750 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>);
751 void setProcessHook(std::function<void(AbstractSlotTrackerStorage *,
752 const Function *, bool)>);
754 unsigned getNextMetadataSlot() override { return mdnNext; }
756 void createMetadataSlot(const MDNode *N) override;
760 int getLocalSlot(const Value *V);
761 int getGlobalSlot(const GlobalValue *V);
762 int getMetadataSlot(const MDNode *N) override;
763 int getAttributeGroupSlot(AttributeSet AS);
764 int getModulePathSlot(StringRef Path);
765 int getGUIDSlot(GlobalValue::GUID GUID);
766 int getTypeIdSlot(StringRef Id);
770 void incorporateFunction(const Function *F) {
772 FunctionProcessed = false;
775 const Function *getFunction() const { return TheFunction; }
780 void purgeFunction();
783 using mdn_iterator = DenseMap<const MDNode*, unsigned>::iterator;
785 mdn_iterator mdn_begin() { return mdnMap.begin(); }
786 mdn_iterator mdn_end() { return mdnMap.end(); }
787 unsigned mdn_size() const { return mdnMap.size(); }
788 bool mdn_empty() const { return mdnMap.empty(); }
791 using as_iterator = DenseMap<AttributeSet, unsigned>::iterator;
793 as_iterator as_begin() { return asMap.begin(); }
794 as_iterator as_end() { return asMap.end(); }
795 unsigned as_size() const { return asMap.size(); }
796 bool as_empty() const { return asMap.empty(); }
799 using guid_iterator = DenseMap<GlobalValue::GUID, unsigned>::iterator;
802 inline void initializeIfNeeded();
803 int initializeIndexIfNeeded();
805 // Implementation Details
808 void CreateModuleSlot(const GlobalValue *V);
811 void CreateMetadataSlot(const MDNode *N);
814 void CreateFunctionSlot(const Value *V);
817 void CreateAttributeSetSlot(AttributeSet AS);
819 inline void CreateModulePathSlot(StringRef Path);
820 void CreateGUIDSlot(GlobalValue::GUID GUID);
821 void CreateTypeIdSlot(StringRef Id);
825 void processModule();
826 // Returns number of allocated slots
830 void processFunction();
833 void processGlobalObjectMetadata(const GlobalObject &GO);
836 void processFunctionMetadata(const Function &F);
839 void processInstructionMetadata(const Instruction &I);
842 } // end namespace llvm
844 ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
846 : M(M), F(F), Machine(&Machine) {}
848 ModuleSlotTracker::ModuleSlotTracker(const Module *M,
849 bool ShouldInitializeAllMetadata)
850 : ShouldCreateStorage(M),
851 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), M(M) {}
853 ModuleSlotTracker::~ModuleSlotTracker() = default;
855 SlotTracker *ModuleSlotTracker::getMachine() {
856 if (!ShouldCreateStorage)
859 ShouldCreateStorage = false;
861 std::make_unique<SlotTracker>(M, ShouldInitializeAllMetadata);
862 Machine = MachineStorage.get();
863 if (ProcessModuleHookFn)
864 Machine->setProcessHook(ProcessModuleHookFn);
865 if (ProcessFunctionHookFn)
866 Machine->setProcessHook(ProcessFunctionHookFn);
870 void ModuleSlotTracker::incorporateFunction(const Function &F) {
871 // Using getMachine() may lazily create the slot tracker.
875 // Nothing to do if this is the right function already.
879 Machine->purgeFunction();
880 Machine->incorporateFunction(&F);
884 int ModuleSlotTracker::getLocalSlot(const Value *V) {
885 assert(F && "No function incorporated");
886 return Machine->getLocalSlot(V);
889 void ModuleSlotTracker::setProcessHook(
890 std::function<void(AbstractSlotTrackerStorage *, const Module *, bool)>
892 ProcessModuleHookFn = Fn;
895 void ModuleSlotTracker::setProcessHook(
896 std::function<void(AbstractSlotTrackerStorage *, const Function *, bool)>
898 ProcessFunctionHookFn = Fn;
901 static SlotTracker *createSlotTracker(const Value *V) {
902 if (const Argument *FA = dyn_cast<Argument>(V))
903 return new SlotTracker(FA->getParent());
905 if (const Instruction *I = dyn_cast<Instruction>(V))
907 return new SlotTracker(I->getParent()->getParent());
909 if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
910 return new SlotTracker(BB->getParent());
912 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
913 return new SlotTracker(GV->getParent());
915 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
916 return new SlotTracker(GA->getParent());
918 if (const GlobalIFunc *GIF = dyn_cast<GlobalIFunc>(V))
919 return new SlotTracker(GIF->getParent());
921 if (const Function *Func = dyn_cast<Function>(V))
922 return new SlotTracker(Func);
928 #define ST_DEBUG(X) dbgs() << X
933 // Module level constructor. Causes the contents of the Module (sans functions)
934 // to be added to the slot table.
935 SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
936 : TheModule(M), ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
938 // Function level constructor. Causes the contents of the Module and the one
939 // function provided to be added to the slot table.
940 SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
941 : TheModule(F ? F->getParent() : nullptr), TheFunction(F),
942 ShouldInitializeAllMetadata(ShouldInitializeAllMetadata) {}
944 SlotTracker::SlotTracker(const ModuleSummaryIndex *Index)
945 : TheModule(nullptr), ShouldInitializeAllMetadata(false), TheIndex(Index) {}
947 inline void SlotTracker::initializeIfNeeded() {
950 TheModule = nullptr; ///< Prevent re-processing next time we're
called.
953 if (TheFunction && !FunctionProcessed)
960 int NumSlots = processIndex();
967 void SlotTracker::processModule() {
973 CreateModuleSlot(&Var);
974 processGlobalObjectMetadata(Var);
976 if (
Attrs.hasAttributes())
977 CreateAttributeSetSlot(
Attrs);
982 CreateModuleSlot(&A);
987 CreateModuleSlot(&
I);
992 for (
unsigned i = 0,
e = NMD.getNumOperands();
i !=
e; ++
i)
993 CreateMetadataSlot(NMD.getOperand(
i));
999 CreateModuleSlot(&
F);
1001 if (ShouldInitializeAllMetadata)
1002 processFunctionMetadata(
F);
1008 CreateAttributeSetSlot(FnAttrs);
1011 if (ProcessModuleHookFn)
1012 ProcessModuleHookFn(
this, TheModule, ShouldInitializeAllMetadata);
1018 void SlotTracker::processFunction() {
1019 ST_DEBUG(
"begin processFunction!\n");
1023 if (!ShouldInitializeAllMetadata)
1024 processFunctionMetadata(*TheFunction);
1028 AE = TheFunction->
arg_end(); AI != AE; ++AI)
1030 CreateFunctionSlot(&*AI);
1032 ST_DEBUG(
"Inserting Instructions:\n");
1035 for (
auto &
BB : *TheFunction) {
1037 CreateFunctionSlot(&
BB);
1039 for (
auto &
I :
BB) {
1040 if (!
I.getType()->isVoidTy() && !
I.hasName())
1041 CreateFunctionSlot(&
I);
1045 if (
const auto *Call = dyn_cast<CallBase>(&
I)) {
1048 if (
Attrs.hasAttributes())
1049 CreateAttributeSetSlot(
Attrs);
1054 if (ProcessFunctionHookFn)
1055 ProcessFunctionHookFn(
this, TheFunction, ShouldInitializeAllMetadata);
1057 FunctionProcessed =
true;
1059 ST_DEBUG(
"end processFunction!\n");
1063 int SlotTracker::processIndex() {
1070 std::map<uint64_t, StringRef> ModuleIdToPathMap;
1071 for (
auto &[ModPath, ModId] : TheIndex->
modulePaths())
1072 ModuleIdToPathMap[ModId.first] = ModPath;
1073 for (
auto &ModPair : ModuleIdToPathMap)
1074 CreateModulePathSlot(ModPair.second);
1077 GUIDNext = ModulePathNext;
1079 for (
auto &GlobalList : *TheIndex)
1080 CreateGUIDSlot(GlobalList.first);
1082 for (
auto &TId : TheIndex->typeIdCompatibleVtableMap())
1086 TypeIdNext = GUIDNext;
1087 for (
const auto &TID : TheIndex->typeIds())
1088 CreateTypeIdSlot(TID.second.first);
1094 void SlotTracker::processGlobalObjectMetadata(
const GlobalObject &GO) {
1097 for (
auto &MD : MDs)
1098 CreateMetadataSlot(MD.second);
1101 void SlotTracker::processFunctionMetadata(
const Function &
F) {
1102 processGlobalObjectMetadata(
F);
1103 for (
auto &
BB :
F) {
1105 processInstructionMetadata(
I);
1109 void SlotTracker::processInstructionMetadata(
const Instruction &
I) {
1111 if (
const CallInst *CI = dyn_cast<CallInst>(&
I))
1112 if (
Function *
F = CI->getCalledFunction())
1113 if (
F->isIntrinsic())
1114 for (
auto &
Op :
I.operands())
1115 if (
auto *V = dyn_cast_or_null<MetadataAsValue>(
Op))
1116 if (
MDNode *
N = dyn_cast<MDNode>(V->getMetadata()))
1117 CreateMetadataSlot(
N);
1121 I.getAllMetadata(MDs);
1122 for (
auto &MD : MDs)
1123 CreateMetadataSlot(MD.second);
1130 ST_DEBUG(
"begin purgeFunction!\n");
1132 TheFunction =
nullptr;
1133 FunctionProcessed =
false;
1144 return MI == mMap.
end() ? -1 : (
int)
MI->second;
1150 ProcessModuleHookFn = Fn;
1156 ProcessFunctionHookFn = Fn;
1169 return MI == mdnMap.end() ? -1 : (
int)
MI->second;
1174 assert(!isa<Constant>(V) &&
"Can't get a constant or global slot with this!");
1180 return FI == fMap.
end() ? -1 : (
int)FI->second;
1189 return AI == asMap.end() ? -1 : (
int)AI->second;
1197 auto I = ModulePathMap.
find(Path);
1198 return I == ModulePathMap.
end() ? -1 : (
int)
I->second;
1207 return I == GUIDMap.end() ? -1 : (
int)
I->second;
1216 return I == TypeIdMap.
end() ? -1 : (
int)
I->second;
1220 void SlotTracker::CreateModuleSlot(
const GlobalValue *V) {
1221 assert(V &&
"Can't insert a null Value into SlotTracker!");
1225 unsigned DestSlot = mNext++;
1228 ST_DEBUG(
" Inserting value [" << V->
getType() <<
"] = " << V <<
" slot=" <<
1231 ST_DEBUG((isa<GlobalVariable>(V) ?
'G' :
1232 (isa<Function>(V) ?
'F' :
1233 (isa<GlobalAlias>(V) ?
'A' :
1234 (isa<GlobalIFunc>(V) ?
'I' :
'o')))) <<
"]\n");
1238 void SlotTracker::CreateFunctionSlot(
const Value *V) {
1241 unsigned DestSlot = fNext++;
1245 ST_DEBUG(
" Inserting value [" << V->
getType() <<
"] = " << V <<
" slot=" <<
1246 DestSlot <<
" [o]\n");
1250 void SlotTracker::CreateMetadataSlot(
const MDNode *
N) {
1251 assert(
N &&
"Can't insert a null Value into SlotTracker!");
1255 if (isa<DIExpression>(
N) || isa<DIArgList>(
N))
1258 unsigned DestSlot = mdnNext;
1259 if (!mdnMap.insert(std::make_pair(
N, DestSlot)).second)
1264 for (
unsigned i = 0,
e =
N->getNumOperands();
i !=
e; ++
i)
1265 if (
const MDNode *
Op = dyn_cast_or_null<MDNode>(
N->getOperand(
i)))
1266 CreateMetadataSlot(
Op);
1269 void SlotTracker::CreateAttributeSetSlot(
AttributeSet AS) {
1273 if (
I != asMap.end())
1276 unsigned DestSlot = asNext++;
1277 asMap[AS] = DestSlot;
1281 void SlotTracker::CreateModulePathSlot(
StringRef Path) {
1282 ModulePathMap[
Path] = ModulePathNext++;
1287 GUIDMap[GUID] = GUIDNext++;
1291 void SlotTracker::CreateTypeIdSlot(
StringRef Id) {
1292 TypeIdMap[
Id] = TypeIdNext++;
1297 struct AsmWriterContext {
1298 TypePrinting *TypePrinter =
nullptr;
1305 static AsmWriterContext &getEmpty() {
1306 static AsmWriterContext EmptyCtx(
nullptr,
nullptr);
1312 virtual void onWriteMetadataAsOperand(
const Metadata *) {}
1314 virtual ~AsmWriterContext() =
default;
1323 AsmWriterContext &WriterCtx);
1326 AsmWriterContext &WriterCtx,
1327 bool FromValue =
false);
1330 if (
const FPMathOperator *FPO = dyn_cast<const FPMathOperator>(U))
1331 Out << FPO->getFastMathFlags();
1334 dyn_cast<OverflowingBinaryOperator>(U)) {
1335 if (OBO->hasNoUnsignedWrap())
1337 if (OBO->hasNoSignedWrap())
1340 dyn_cast<PossiblyExactOperator>(U)) {
1344 if (
GEP->isInBounds())
1350 AsmWriterContext &WriterCtx) {
1351 if (
const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1352 if (CI->getType()->isIntegerTy(1)) {
1353 Out << (CI->getZExtValue() ?
"true" :
"false");
1356 Out << CI->getValue();
1360 if (
const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
1361 const APFloat &APF = CFP->getValueAPF();
1372 bool isNaN = APF.
isNaN();
1373 if (!isInf && !isNaN) {
1383 "[-+]?[0-9] regex does not match!");
1394 static_assert(
sizeof(
double) ==
sizeof(
uint64_t),
1395 "assuming that double is 64 bits!");
1452 if (isa<ConstantAggregateZero>(CV) || isa<ConstantTargetNone>(CV)) {
1453 Out <<
"zeroinitializer";
1457 if (
const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
1458 Out <<
"blockaddress(";
1466 if (
const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) {
1467 Out <<
"dso_local_equivalent ";
1472 if (
const auto *
NC = dyn_cast<NoCFIValue>(CV)) {
1478 if (
const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
1479 Type *ETy = CA->getType()->getElementType();
1481 WriterCtx.TypePrinter->print(ETy, Out);
1484 for (
unsigned i = 1,
e = CA->getNumOperands();
i !=
e; ++
i) {
1486 WriterCtx.TypePrinter->print(ETy, Out);
1497 if (CA->isString()) {
1499 printEscapedString(CA->getAsString(), Out);
1504 Type *ETy = CA->getType()->getElementType();
1506 WriterCtx.TypePrinter->print(ETy, Out);
1509 for (
unsigned i = 1,
e = CA->getNumElements();
i !=
e; ++
i) {
1511 WriterCtx.TypePrinter->print(ETy, Out);
1520 if (CS->getType()->isPacked())
1523 unsigned N = CS->getNumOperands();
1526 WriterCtx.TypePrinter->print(CS->getOperand(0)->getType(), Out);
1531 for (
unsigned i = 1;
i <
N;
i++) {
1533 WriterCtx.TypePrinter->print(CS->getOperand(
i)->getType(), Out);
1542 if (CS->getType()->isPacked())
1547 if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
1548 auto *CVVTy = cast<FixedVectorType>(CV->getType());
1549 Type *ETy = CVVTy->getElementType();
1551 WriterCtx.TypePrinter->print(ETy, Out);
1553 WriteAsOperandInternal(Out, CV->getAggregateElement(0U), WriterCtx);
1554 for (unsigned i = 1, e = CVVTy->getNumElements(); i != e; ++i) {
1556 WriterCtx.TypePrinter->print(ETy, Out);
1558 WriteAsOperandInternal(Out, CV->getAggregateElement(i), WriterCtx);
1564 if (isa<ConstantPointerNull>(CV)) {
1569 if (isa<ConstantTokenNone>(CV)) {
1574 if (isa<PoisonValue>(CV)) {
1579 if (isa<UndefValue>(CV)) {
1584 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
1585 Out << CE->getOpcodeName();
1586 WriteOptimizationInfo(Out, CE);
1587 if (CE->isCompare())
1588 Out << ' ' << CmpInst::getPredicateName(
1589 static_cast<CmpInst::Predicate>(CE->getPredicate()));
1592 std::optional<unsigned> InRangeOp;
1593 if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
1594 WriterCtx.TypePrinter->print(GEP->getSourceElementType(), Out);
1596 InRangeOp = GEP->getInRangeIndex();
1601 for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
1602 if (InRangeOp && unsigned(OI - CE->op_begin()) == *InRangeOp)
1604 WriterCtx.TypePrinter->print((*OI)->getType(), Out);
1606 WriteAsOperandInternal(Out, *OI, WriterCtx);
1607 if (OI+1 != CE->op_end())
1613 WriterCtx.TypePrinter->print(CE->getType(), Out);
1616 if (CE->getOpcode() == Instruction::ShuffleVector)
1617 PrintShuffleMask(Out, CE->getType(), CE->getShuffleMask());
1623 Out << "<placeholder or erroneous Constant>";
1626 static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
1627 AsmWriterContext &WriterCtx) {
1629 for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
1630 const Metadata *MD = Node->getOperand(mi);
1633 else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
1634 Value *V = MDV->getValue();
1635 WriterCtx.TypePrinter->print(V->getType(), Out);
1637 WriteAsOperandInternal(Out, V, WriterCtx);
1639 WriteAsOperandInternal(Out, MD, WriterCtx);
1640 WriterCtx.onWriteMetadataAsOperand(MD);
1651 struct FieldSeparator {
1655 FieldSeparator(const char *Sep = ", ") : Sep(Sep) {}
1658 raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
1663 return OS << FS.Sep;
1666 struct MDFieldPrinter {
1669 AsmWriterContext &WriterCtx;
1671 explicit MDFieldPrinter(raw_ostream &Out)
1672 : Out(Out), WriterCtx(AsmWriterContext::getEmpty()) {}
1673 MDFieldPrinter(raw_ostream &Out, AsmWriterContext &Ctx)
1674 : Out(Out), WriterCtx(Ctx) {}
1676 void printTag(const DINode *N);
1677 void printMacinfoType(const DIMacroNode *N);
1678 void printChecksum(const DIFile::ChecksumInfo<StringRef> &N);
1679 void printString(StringRef Name, StringRef Value,
1680 bool ShouldSkipEmpty = true);
1681 void printMetadata(StringRef Name, const Metadata *MD,
1682 bool ShouldSkipNull = true);
1683 template <class IntTy>
1684 void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
1685 void printAPInt(StringRef Name, const APInt &Int, bool IsUnsigned,
1686 bool ShouldSkipZero);
1687 void printBool(StringRef Name, bool Value,
1688 std::optional<bool> Default = std::nullopt);
1689 void printDIFlags(StringRef Name, DINode::DIFlags Flags);
1690 void printDISPFlags(StringRef Name, DISubprogram::DISPFlags Flags);
1691 template <class IntTy, class Stringifier>
1692 void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
1693 bool ShouldSkipZero = true);
1694 void printEmissionKind(StringRef Name, DICompileUnit::DebugEmissionKind EK);
1695 void printNameTableKind(StringRef Name,
1696 DICompileUnit::DebugNameTableKind NTK);
1699 } // end anonymous namespace
1701 void MDFieldPrinter::printTag(const DINode *N) {
1702 Out << FS << "tag: ";
1703 auto Tag = dwarf::TagString(N->getTag());
1710 void MDFieldPrinter::printMacinfoType(const DIMacroNode *N) {
1711 Out << FS << "type: ";
1712 auto Type = dwarf::MacinfoString(N->getMacinfoType());
1716 Out << N->getMacinfoType();
1719 void MDFieldPrinter::printChecksum(
1720 const DIFile::ChecksumInfo<StringRef> &Checksum) {
1721 Out << FS << "checksumkind: " << Checksum.getKindAsString();
1722 printString("checksum", Checksum.Value, /* ShouldSkipEmpty */ false);
1725 void MDFieldPrinter::printString(StringRef Name, StringRef Value,
1726 bool ShouldSkipEmpty) {
1727 if (ShouldSkipEmpty && Value.empty())
1730 Out << FS << Name << ": \"";
1731 printEscapedString(Value, Out);
1735 static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
1736 AsmWriterContext &WriterCtx) {
1741 WriteAsOperandInternal(Out, MD, WriterCtx);
1742 WriterCtx.onWriteMetadataAsOperand(MD);
1745 void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
1746 bool ShouldSkipNull) {
1747 if (ShouldSkipNull && !MD)
1750 Out << FS << Name << ": ";
1751 writeMetadataAsOperand(Out, MD, WriterCtx);
1754 template <class IntTy>
1755 void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
1756 if (ShouldSkipZero && !Int)
1759 Out << FS << Name << ": " << Int;
1762 void MDFieldPrinter::printAPInt(StringRef Name, const APInt &Int,
1763 bool IsUnsigned, bool ShouldSkipZero) {
1764 if (ShouldSkipZero && Int.isZero())
1767 Out << FS << Name << ": ";
1768 Int.print(Out, !IsUnsigned);
1771 void MDFieldPrinter::printBool(StringRef Name, bool Value,
1772 std::optional<bool> Default) {
1773 if (Default && Value == *Default)
1775 Out << FS << Name << ": " << (Value ? "true" : "false");
1778 void MDFieldPrinter::printDIFlags(StringRef Name, DINode::DIFlags Flags) {
1782 Out << FS << Name << ": ";
1784 SmallVector<DINode::DIFlags, 8> SplitFlags;
1785 auto Extra = DINode::splitFlags(Flags, SplitFlags);
1787 FieldSeparator FlagsFS(" | ");
1788 for (auto F : SplitFlags) {
1789 auto StringF = DINode::getFlagString(F);
1790 assert(!StringF.empty() && "Expected valid flag");
1791 Out << FlagsFS << StringF;
1793 if (Extra || SplitFlags.empty())
1794 Out << FlagsFS << Extra;
1797 void MDFieldPrinter::printDISPFlags(StringRef Name,
1798 DISubprogram::DISPFlags Flags) {
1799 // Always print this field, because no flags in the IR at all will be
1800 // interpreted as old-style isDefinition: true.
1801 Out << FS << Name << ": ";
1808 SmallVector<DISubprogram::DISPFlags, 8> SplitFlags;
1809 auto Extra = DISubprogram::splitFlags(Flags, SplitFlags);
1811 FieldSeparator FlagsFS(" | ");
1812 for (auto F : SplitFlags) {
1813 auto StringF = DISubprogram::getFlagString(F);
1814 assert(!StringF.empty() && "Expected valid flag");
1815 Out << FlagsFS << StringF;
1817 if (Extra || SplitFlags.empty())
1818 Out << FlagsFS << Extra;
1821 void MDFieldPrinter::printEmissionKind(StringRef Name,
1822 DICompileUnit::DebugEmissionKind EK) {
1823 Out << FS << Name << ": " << DICompileUnit::emissionKindString(EK);
1826 void MDFieldPrinter::printNameTableKind(StringRef Name,
1827 DICompileUnit::DebugNameTableKind NTK) {
1828 if (NTK == DICompileUnit::DebugNameTableKind::Default)
1830 Out << FS << Name << ": " << DICompileUnit::nameTableKindString(NTK);
1833 template <class IntTy, class Stringifier>
1834 void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
1835 Stringifier toString, bool ShouldSkipZero) {
1839 Out << FS << Name << ": ";
1840 auto S = toString(Value);
1847 static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
1848 AsmWriterContext &WriterCtx) {
1849 Out << "!GenericDINode(";
1850 MDFieldPrinter Printer(Out, WriterCtx);
1851 Printer.printTag(N);
1852 Printer.printString("header", N->getHeader());
1853 if (N->getNumDwarfOperands()) {
1854 Out << Printer.FS << "operands: {";
1856 for (auto &I : N->dwarf_operands()) {
1858 writeMetadataAsOperand(Out, I, WriterCtx);
1865 static void writeDILocation(raw_ostream &Out, const DILocation *DL,
1866 AsmWriterContext &WriterCtx) {
1867 Out << "!DILocation(";
1868 MDFieldPrinter Printer(Out, WriterCtx);
1869 // Always output the line, since 0 is a relevant and important value for it.
1870 Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
1871 Printer.printInt("column", DL->getColumn());
1872 Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
1873 Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
1874 Printer.printBool("isImplicitCode", DL->isImplicitCode(),
1875 /* Default */ false);
1879 static void writeDIAssignID(raw_ostream &Out, const DIAssignID *DL,
1880 AsmWriterContext &WriterCtx) {
1881 Out << "!DIAssignID()";
1882 MDFieldPrinter Printer(Out, WriterCtx);
1885 static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
1886 AsmWriterContext &WriterCtx) {
1887 Out << "!DISubrange(";
1888 MDFieldPrinter Printer(Out, WriterCtx);
1890 auto *Count = N->getRawCountNode();
1891 if (auto *CE = dyn_cast_or_null<ConstantAsMetadata>(Count)) {
1892 auto *CV = cast<ConstantInt>(CE->getValue());
1893 Printer.printInt("count", CV->getSExtValue(),
1894 /* ShouldSkipZero */ false);
1896 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1898 // A lowerBound of constant 0 should not be skipped, since it is different
1899 // from an unspecified lower bound (= nullptr).
1900 auto *LBound = N->getRawLowerBound();
1901 if (auto *LE = dyn_cast_or_null<ConstantAsMetadata>(LBound)) {
1902 auto *LV = cast<ConstantInt>(LE->getValue());
1903 Printer.printInt("lowerBound", LV->getSExtValue(),
1904 /* ShouldSkipZero */ false);
1906 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1908 auto *UBound = N->getRawUpperBound();
1909 if (auto *UE = dyn_cast_or_null<ConstantAsMetadata>(UBound)) {
1910 auto *UV = cast<ConstantInt>(UE->getValue());
1911 Printer.printInt("upperBound", UV->getSExtValue(),
1912 /* ShouldSkipZero */ false);
1914 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1916 auto *Stride = N->getRawStride();
1917 if (auto *SE = dyn_cast_or_null<ConstantAsMetadata>(Stride)) {
1918 auto *SV = cast<ConstantInt>(SE->getValue());
1919 Printer.printInt("stride", SV->getSExtValue(), /* ShouldSkipZero */ false);
1921 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1926 static void writeDIGenericSubrange(raw_ostream &Out, const DIGenericSubrange *N,
1927 AsmWriterContext &WriterCtx) {
1928 Out << "!DIGenericSubrange(";
1929 MDFieldPrinter Printer(Out, WriterCtx);
1931 auto IsConstant = [&](Metadata *Bound) -> bool {
1932 if (auto *BE = dyn_cast_or_null<DIExpression>(Bound)) {
1933 return BE->isConstant() &&
1934 DIExpression::SignedOrUnsignedConstant::SignedConstant ==
1940 auto GetConstant = [&](Metadata *Bound) -> int64_t {
1941 assert(IsConstant(Bound) && "Expected constant");
1942 auto *BE = dyn_cast_or_null<DIExpression>(Bound);
1943 return static_cast<int64_t>(BE->getElement(1));
1946 auto *Count = N->getRawCountNode();
1947 if (IsConstant(Count))
1948 Printer.printInt("count", GetConstant(Count),
1949 /* ShouldSkipZero */ false);
1951 Printer.printMetadata("count", Count, /*ShouldSkipNull */ true);
1953 auto *LBound = N->getRawLowerBound();
1954 if (IsConstant(LBound))
1955 Printer.printInt("lowerBound", GetConstant(LBound),
1956 /* ShouldSkipZero */ false);
1958 Printer.printMetadata("lowerBound", LBound, /*ShouldSkipNull */ true);
1960 auto *UBound = N->getRawUpperBound();
1961 if (IsConstant(UBound))
1962 Printer.printInt("upperBound", GetConstant(UBound),
1963 /* ShouldSkipZero */ false);
1965 Printer.printMetadata("upperBound", UBound, /*ShouldSkipNull */ true);
1967 auto *Stride = N->getRawStride();
1968 if (IsConstant(Stride))
1969 Printer.printInt("stride", GetConstant(Stride),
1970 /* ShouldSkipZero */ false);
1972 Printer.printMetadata("stride", Stride, /*ShouldSkipNull */ true);
1977 static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
1978 AsmWriterContext &) {
1979 Out << "!DIEnumerator(";
1980 MDFieldPrinter Printer(Out);
1981 Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
1982 Printer.printAPInt("value", N->getValue(), N->isUnsigned(),
1983 /*ShouldSkipZero=*/false);
1984 if (N->isUnsigned())
1985 Printer.printBool("isUnsigned", true);
1989 static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
1990 AsmWriterContext &) {
1991 Out << "!DIBasicType(";
1992 MDFieldPrinter Printer(Out);
1993 if (N->getTag() != dwarf::DW_TAG_base_type)
1994 Printer.printTag(N);
1995 Printer.printString("name", N->getName());
1996 Printer.printInt("size", N->getSizeInBits());
1997 Printer.printInt("align", N->getAlignInBits());
1998 Printer.printDwarfEnum("encoding", N->getEncoding(),
1999 dwarf::AttributeEncodingString);
2000 Printer.printDIFlags("flags", N->getFlags());
2004 static void writeDIStringType(raw_ostream &Out, const DIStringType *N,
2005 AsmWriterContext &WriterCtx) {
2006 Out << "!DIStringType(";
2007 MDFieldPrinter Printer(Out, WriterCtx);
2008 if (N->getTag() != dwarf::DW_TAG_string_type)
2009 Printer.printTag(N);
2010 Printer.printString("name", N->getName());
2011 Printer.printMetadata("stringLength", N->getRawStringLength());
2012 Printer.printMetadata("stringLengthExpression", N->getRawStringLengthExp());
2013 Printer.printMetadata("stringLocationExpression",
2014 N->getRawStringLocationExp());
2015 Printer.printInt("size", N->getSizeInBits());
2016 Printer.printInt("align", N->getAlignInBits());
2017 Printer.printDwarfEnum("encoding", N->getEncoding(),
2018 dwarf::AttributeEncodingString);
2022 static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
2023 AsmWriterContext &WriterCtx) {
2024 Out << "!DIDerivedType(";
2025 MDFieldPrinter Printer(Out, WriterCtx);
2026 Printer.printTag(N);
2027 Printer.printString("name", N->getName());
2028 Printer.printMetadata("scope", N->getRawScope());
2029 Printer.printMetadata("file", N->getRawFile());
2030 Printer.printInt("line", N->getLine());
2031 Printer.printMetadata("baseType", N->getRawBaseType(),
2032 /* ShouldSkipNull */ false);
2033 Printer.printInt("size", N->getSizeInBits());
2034 Printer.printInt("align", N->getAlignInBits());
2035 Printer.printInt("offset", N->getOffsetInBits());
2036 Printer.printDIFlags("flags", N->getFlags());
2037 Printer.printMetadata("extraData", N->getRawExtraData());
2038 if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
2039 Printer.printInt("dwarfAddressSpace", *DWARFAddressSpace,
2040 /* ShouldSkipZero */ false);
2041 Printer.printMetadata("annotations", N->getRawAnnotations());
2045 static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
2046 AsmWriterContext &WriterCtx) {
2047 Out << "!DICompositeType(";
2048 MDFieldPrinter Printer(Out, WriterCtx);
2049 Printer.printTag(N);
2050 Printer.printString("name", N->getName());
2051 Printer.printMetadata("scope", N->getRawScope());
2052 Printer.printMetadata("file", N->getRawFile());
2053 Printer.printInt("line", N->getLine());
2054 Printer.printMetadata("baseType", N->getRawBaseType());
2055 Printer.printInt("size", N->getSizeInBits());
2056 Printer.printInt("align", N->getAlignInBits());
2057 Printer.printInt("offset", N->getOffsetInBits());
2058 Printer.printDIFlags("flags", N->getFlags());
2059 Printer.printMetadata("elements", N->getRawElements());
2060 Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
2061 dwarf::LanguageString);
2062 Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
2063 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2064 Printer.printString("identifier", N->getIdentifier());
2065 Printer.printMetadata("discriminator", N->getRawDiscriminator());
2066 Printer.printMetadata("dataLocation", N->getRawDataLocation());
2067 Printer.printMetadata("associated", N->getRawAssociated());
2068 Printer.printMetadata("allocated", N->getRawAllocated());
2069 if (auto *RankConst = N->getRankConst())
2070 Printer.printInt("rank", RankConst->getSExtValue(),
2071 /* ShouldSkipZero */ false);
2073 Printer.printMetadata("rank", N->getRawRank(), /*ShouldSkipNull */ true);
2074 Printer.printMetadata("annotations", N->getRawAnnotations());
2078 static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
2079 AsmWriterContext &WriterCtx) {
2080 Out << "!DISubroutineType(";
2081 MDFieldPrinter Printer(Out, WriterCtx);
2082 Printer.printDIFlags("flags", N->getFlags());
2083 Printer.printDwarfEnum("cc", N->getCC(), dwarf::ConventionString);
2084 Printer.printMetadata("types", N->getRawTypeArray(),
2085 /* ShouldSkipNull */ false);
2089 static void writeDIFile(raw_ostream &Out, const DIFile *N, AsmWriterContext &) {
2091 MDFieldPrinter Printer(Out);
2092 Printer.printString("filename", N->getFilename(),
2093 /* ShouldSkipEmpty */ false);
2094 Printer.printString("directory", N->getDirectory(),
2095 /* ShouldSkipEmpty */ false);
2096 // Print all values for checksum together, or not at all.
2097 if (N->getChecksum())
2098 Printer.printChecksum(*N->getChecksum());
2099 Printer.printString("source", N->getSource().value_or(StringRef()),
2100 /* ShouldSkipEmpty */ true);
2104 static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
2105 AsmWriterContext &WriterCtx) {
2106 Out << "!DICompileUnit(";
2107 MDFieldPrinter Printer(Out, WriterCtx);
2108 Printer.printDwarfEnum("language", N->getSourceLanguage(),
2109 dwarf::LanguageString, /* ShouldSkipZero */ false);
2110 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2111 Printer.printString("producer", N->getProducer());
2112 Printer.printBool("isOptimized", N->isOptimized());
2113 Printer.printString("flags", N->getFlags());
2114 Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
2115 /* ShouldSkipZero */ false);
2116 Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
2117 Printer.printEmissionKind("emissionKind", N->getEmissionKind());
2118 Printer.printMetadata("enums", N->getRawEnumTypes());
2119 Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
2120 Printer.printMetadata("globals", N->getRawGlobalVariables());
2121 Printer.printMetadata("imports", N->getRawImportedEntities());
2122 Printer.printMetadata("macros", N->getRawMacros());
2123 Printer.printInt("dwoId", N->getDWOId());
2124 Printer.printBool("splitDebugInlining", N->getSplitDebugInlining(), true);
2125 Printer.printBool("debugInfoForProfiling", N->getDebugInfoForProfiling(),
2127 Printer.printNameTableKind("nameTableKind", N->getNameTableKind());
2128 Printer.printBool("rangesBaseAddress", N->getRangesBaseAddress(), false);
2129 Printer.printString("sysroot", N->getSysRoot());
2130 Printer.printString("sdk", N->getSDK());
2134 static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
2135 AsmWriterContext &WriterCtx) {
2136 Out << "!DISubprogram(";
2137 MDFieldPrinter Printer(Out, WriterCtx);
2138 Printer.printString("name", N->getName());
2139 Printer.printString("linkageName", N->getLinkageName());
2140 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2141 Printer.printMetadata("file", N->getRawFile());
2142 Printer.printInt("line", N->getLine());
2143 Printer.printMetadata("type", N->getRawType());
2144 Printer.printInt("scopeLine", N->getScopeLine());
2145 Printer.printMetadata("containingType", N->getRawContainingType());
2146 if (N->getVirtuality() != dwarf::DW_VIRTUALITY_none ||
2147 N->getVirtualIndex() != 0)
2148 Printer.printInt("virtualIndex", N->getVirtualIndex(), false);
2149 Printer.printInt("thisAdjustment", N->getThisAdjustment());
2150 Printer.printDIFlags("flags", N->getFlags());
2151 Printer.printDISPFlags("spFlags", N->getSPFlags());
2152 Printer.printMetadata("unit", N->getRawUnit());
2153 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2154 Printer.printMetadata("declaration", N->getRawDeclaration());
2155 Printer.printMetadata("retainedNodes", N->getRawRetainedNodes());
2156 Printer.printMetadata("thrownTypes", N->getRawThrownTypes());
2157 Printer.printMetadata("annotations", N->getRawAnnotations());
2158 Printer.printString("targetFuncName", N->getTargetFuncName());
2162 static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
2163 AsmWriterContext &WriterCtx) {
2164 Out << "!DILexicalBlock(";
2165 MDFieldPrinter Printer(Out, WriterCtx);
2166 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2167 Printer.printMetadata("file", N->getRawFile());
2168 Printer.printInt("line", N->getLine());
2169 Printer.printInt("column", N->getColumn());
2173 static void writeDILexicalBlockFile(raw_ostream &Out,
2174 const DILexicalBlockFile *N,
2175 AsmWriterContext &WriterCtx) {
2176 Out << "!DILexicalBlockFile(";
2177 MDFieldPrinter Printer(Out, WriterCtx);
2178 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2179 Printer.printMetadata("file", N->getRawFile());
2180 Printer.printInt("discriminator", N->getDiscriminator(),
2181 /* ShouldSkipZero */ false);
2185 static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
2186 AsmWriterContext &WriterCtx) {
2187 Out << "!DINamespace(";
2188 MDFieldPrinter Printer(Out, WriterCtx);
2189 Printer.printString("name", N->getName());
2190 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2191 Printer.printBool("exportSymbols", N->getExportSymbols(), false);
2195 static void writeDICommonBlock(raw_ostream &Out, const DICommonBlock *N,
2196 AsmWriterContext &WriterCtx) {
2197 Out << "!DICommonBlock(";
2198 MDFieldPrinter Printer(Out, WriterCtx);
2199 Printer.printMetadata("scope", N->getRawScope(), false);
2200 Printer.printMetadata("declaration", N->getRawDecl(), false);
2201 Printer.printString("name", N->getName());
2202 Printer.printMetadata("file", N->getRawFile());
2203 Printer.printInt("line", N->getLineNo());
2207 static void writeDIMacro(raw_ostream &Out, const DIMacro *N,
2208 AsmWriterContext &WriterCtx) {
2210 MDFieldPrinter Printer(Out, WriterCtx);
2211 Printer.printMacinfoType(N);
2212 Printer.printInt("line", N->getLine());
2213 Printer.printString("name", N->getName());
2214 Printer.printString("value", N->getValue());
2218 static void writeDIMacroFile(raw_ostream &Out, const DIMacroFile *N,
2219 AsmWriterContext &WriterCtx) {
2220 Out << "!DIMacroFile(";
2221 MDFieldPrinter Printer(Out, WriterCtx);
2222 Printer.printInt("line", N->getLine());
2223 Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
2224 Printer.printMetadata("nodes", N->getRawElements());
2228 static void writeDIModule(raw_ostream &Out, const DIModule *N,
2229 AsmWriterContext &WriterCtx) {
2230 Out << "!DIModule(";
2231 MDFieldPrinter Printer(Out, WriterCtx);
2232 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2233 Printer.printString("name", N->getName());
2234 Printer.printString("configMacros", N->getConfigurationMacros());
2235 Printer.printString("includePath", N->getIncludePath());
2236 Printer.printString("apinotes", N->getAPINotesFile());
2237 Printer.printMetadata("file", N->getRawFile());
2238 Printer.printInt("line", N->getLineNo());
2239 Printer.printBool("isDecl", N->getIsDecl(), /* Default */ false);
2243 static void writeDITemplateTypeParameter(raw_ostream &Out,
2244 const DITemplateTypeParameter *N,
2245 AsmWriterContext &WriterCtx) {
2246 Out << "!DITemplateTypeParameter(";
2247 MDFieldPrinter Printer(Out, WriterCtx);
2248 Printer.printString("name", N->getName());
2249 Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
2250 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2254 static void writeDITemplateValueParameter(raw_ostream &Out,
2255 const DITemplateValueParameter *N,
2256 AsmWriterContext &WriterCtx) {
2257 Out << "!DITemplateValueParameter(";
2258 MDFieldPrinter Printer(Out, WriterCtx);
2259 if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
2260 Printer.printTag(N);
2261 Printer.printString("name", N->getName());
2262 Printer.printMetadata("type", N->getRawType());
2263 Printer.printBool("defaulted", N->isDefault(), /* Default= */ false);
2264 Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
2268 static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
2269 AsmWriterContext &WriterCtx) {
2270 Out << "!DIGlobalVariable(";
2271 MDFieldPrinter Printer(Out, WriterCtx);
2272 Printer.printString("name", N->getName());
2273 Printer.printString("linkageName", N->getLinkageName());
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.printBool("isLocal", N->isLocalToUnit());
2279 Printer.printBool("isDefinition", N->isDefinition());
2280 Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
2281 Printer.printMetadata("templateParams", N->getRawTemplateParams());
2282 Printer.printInt("align", N->getAlignInBits());
2283 Printer.printMetadata("annotations", N->getRawAnnotations());
2287 static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
2288 AsmWriterContext &WriterCtx) {
2289 Out << "!DILocalVariable(";
2290 MDFieldPrinter Printer(Out, WriterCtx);
2291 Printer.printString("name", N->getName());
2292 Printer.printInt("arg", N->getArg());
2293 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2294 Printer.printMetadata("file", N->getRawFile());
2295 Printer.printInt("line", N->getLine());
2296 Printer.printMetadata("type", N->getRawType());
2297 Printer.printDIFlags("flags", N->getFlags());
2298 Printer.printInt("align", N->getAlignInBits());
2299 Printer.printMetadata("annotations", N->getRawAnnotations());
2303 static void writeDILabel(raw_ostream &Out, const DILabel *N,
2304 AsmWriterContext &WriterCtx) {
2306 MDFieldPrinter Printer(Out, WriterCtx);
2307 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2308 Printer.printString("name", N->getName());
2309 Printer.printMetadata("file", N->getRawFile());
2310 Printer.printInt("line", N->getLine());
2314 static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
2315 AsmWriterContext &WriterCtx) {
2316 Out << "!DIExpression(";
2319 for (const DIExpression::ExprOperand &Op : N->expr_ops()) {
2320 auto OpStr = dwarf::OperationEncodingString(Op.getOp());
2321 assert(!OpStr.empty() && "Expected valid opcode");
2324 if (Op.getOp() == dwarf::DW_OP_LLVM_convert) {
2325 Out << FS << Op.getArg(0);
2326 Out << FS << dwarf::AttributeEncodingString(Op.getArg(1));
2328 for (unsigned A = 0, AE = Op.getNumArgs(); A != AE; ++A)
2329 Out << FS << Op.getArg(A);
2333 for (const auto &I : N->getElements())
2339 static void writeDIArgList(raw_ostream &Out, const DIArgList *N,
2340 AsmWriterContext &WriterCtx,
2341 bool FromValue = false) {
2343 "Unexpected DIArgList metadata outside of value argument");
2344 Out << "!DIArgList(";
2346 MDFieldPrinter Printer(Out, WriterCtx);
2347 for (Metadata *Arg : N->getArgs()) {
2349 WriteAsOperandInternal(Out, Arg, WriterCtx, true);
2354 static void writeDIGlobalVariableExpression(raw_ostream &Out,
2355 const DIGlobalVariableExpression *N,
2356 AsmWriterContext &WriterCtx) {
2357 Out << "!DIGlobalVariableExpression(";
2358 MDFieldPrinter Printer(Out, WriterCtx);
2359 Printer.printMetadata("var", N->getVariable());
2360 Printer.printMetadata("expr", N->getExpression());
2364 static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
2365 AsmWriterContext &WriterCtx) {
2366 Out << "!DIObjCProperty(";
2367 MDFieldPrinter Printer(Out, WriterCtx);
2368 Printer.printString("name", N->getName());
2369 Printer.printMetadata("file", N->getRawFile());
2370 Printer.printInt("line", N->getLine());
2371 Printer.printString("setter", N->getSetterName());
2372 Printer.printString("getter", N->getGetterName());
2373 Printer.printInt("attributes", N->getAttributes());
2374 Printer.printMetadata("type", N->getRawType());
2378 static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
2379 AsmWriterContext &WriterCtx) {
2380 Out << "!DIImportedEntity(";
2381 MDFieldPrinter Printer(Out, WriterCtx);
2382 Printer.printTag(N);
2383 Printer.printString("name", N->getName());
2384 Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
2385 Printer.printMetadata("entity", N->getRawEntity());
2386 Printer.printMetadata("file", N->getRawFile());
2387 Printer.printInt("line", N->getLine());
2388 Printer.printMetadata("elements", N->getRawElements());
2392 static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
2393 AsmWriterContext &Ctx) {
2394 if (Node->isDistinct())
2396 else if (Node->isTemporary())
2397 Out << "<temporary!> "; // Handle broken code.
2399 switch (Node->getMetadataID()) {
2401 llvm_unreachable("Expected uniquable MDNode");
2402 #define HANDLE_MDNODE_LEAF(CLASS) \
2403 case Metadata::CLASS##Kind: \
2404 write##CLASS(Out, cast<CLASS>(Node), Ctx); \
2406 #include "llvm/IR/Metadata.def"
2410 // Full implementation of printing a Value as an operand with support for
2411 // TypePrinting, etc.
2412 static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
2413 AsmWriterContext &WriterCtx) {
2415 PrintLLVMName(Out, V);
2419 const Constant *CV = dyn_cast<Constant>(V);
2420 if (CV && !isa<GlobalValue>(CV)) {
2421 assert(WriterCtx.TypePrinter && "Constants require TypePrinting!");
2422 WriteConstantInternal(Out, CV, WriterCtx);
2426 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2428 if (IA->hasSideEffects())
2429 Out << "sideeffect ";
2430 if (IA->isAlignStack())
2431 Out << "alignstack ";
2433 if (IA->getDialect() == InlineAsm::AD_Intel)
2434 Out << "inteldialect ";
2438 printEscapedString(IA->getAsmString(), Out);
2440 printEscapedString(
IA->getConstraintString(), Out);
2445 if (
auto *MD = dyn_cast<MetadataAsValue>(V)) {
2453 auto *
Machine = WriterCtx.Machine;
2456 if (
const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2473 if (
const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2492 AsmWriterContext &WriterCtx,
2496 if (
const DIExpression *Expr = dyn_cast<DIExpression>(MD)) {
2500 if (
const DIArgList *ArgList = dyn_cast<DIArgList>(MD)) {
2505 if (
const MDNode *
N = dyn_cast<MDNode>(MD)) {
2506 std::unique_ptr<SlotTracker> MachineStorage;
2508 if (!WriterCtx.Machine) {
2509 MachineStorage = std::make_unique<SlotTracker>(WriterCtx.Context);
2510 WriterCtx.Machine = MachineStorage.get();
2512 int Slot = WriterCtx.Machine->getMetadataSlot(
N);
2514 if (
const DILocation *Loc = dyn_cast<DILocation>(
N)) {
2520 Out <<
"<" <<
N <<
">";
2526 if (
const MDString *MDS = dyn_cast<MDString>(MD)) {
2528 printEscapedString(MDS->getString(), Out);
2533 auto *V = cast<ValueAsMetadata>(MD);
2534 assert(WriterCtx.TypePrinter &&
"TypePrinter required for metadata values");
2535 assert((FromValue || !isa<LocalAsMetadata>(V)) &&
2536 "Unexpected function-local metadata outside of value argument");
2538 WriterCtx.TypePrinter->print(V->getValue()->
getType(), Out);
2545 class AssemblyWriter {
2547 const Module *TheModule =
nullptr;
2549 std::unique_ptr<SlotTracker> SlotTrackerStorage;
2551 TypePrinting TypePrinter;
2555 bool ShouldPreserveUseListOrder;
2566 bool ShouldPreserveUseListOrder =
false);
2571 AsmWriterContext getContext() {
2572 return AsmWriterContext(&TypePrinter, &
Machine, TheModule);
2575 void printMDNodeBody(
const MDNode *MD);
2578 void printModule(
const Module *M);
2580 void writeOperand(
const Value *
Op,
bool PrintType);
2582 void writeOperandBundles(
const CallBase *Call);
2593 void writeAllMDNodes();
2594 void writeMDNode(
unsigned Slot,
const MDNode *Node);
2595 void writeAttribute(
const Attribute &Attr,
bool InAttrGroup =
false);
2596 void writeAttributeSet(
const AttributeSet &AttrSet,
bool InAttrGroup =
false);
2597 void writeAllAttributeGroups();
2599 void printTypeIdentities();
2603 void printComdat(
const Comdat *
C);
2610 void printUseListOrder(
const Value *V,
const std::vector<unsigned> &Shuffle);
2613 void printModuleSummaryIndex();
2614 void printSummaryInfo(
unsigned Slot,
const ValueInfo &
VI);
2622 void printArgs(
const std::vector<uint64_t> &
Args);
2627 printNonConstVCalls(
const std::vector<FunctionSummary::VFuncId> &VCallList,
2630 printConstVCalls(
const std::vector<FunctionSummary::ConstVCall> &VCallList,
2635 void printMetadataAttachments(
2641 void printInfoComment(
const Value &V);
2652 bool IsForDebug,
bool ShouldPreserveUseListOrder)
2653 : Out(o), TheModule(
M),
Machine(Mac), TypePrinter(
M), AnnotationWriter(AAW),
2654 IsForDebug(IsForDebug),
2655 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
2658 for (
const GlobalObject &GO : TheModule->global_objects())
2665 : Out(o), TheIndex(
Index),
Machine(Mac), TypePrinter(nullptr),
2666 IsForDebug(IsForDebug), ShouldPreserveUseListOrder(
false) {}
2668 void AssemblyWriter::writeOperand(
const Value *Operand,
bool PrintType) {
2670 Out <<
"<null operand!>";
2674 TypePrinter.print(Operand->
getType(), Out);
2677 auto WriterCtx = getContext();
2691 Out <<
" syncscope(\"";
2692 printEscapedString(SSNs[SSID], Out);
2702 if (Ordering == AtomicOrdering::NotAtomic)
2705 writeSyncScope(
Context, SSID);
2713 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
2714 FailureOrdering != AtomicOrdering::NotAtomic);
2716 writeSyncScope(
Context, SSID);
2721 void AssemblyWriter::writeParamOperand(
const Value *Operand,
2724 Out <<
"<null operand!>";
2729 TypePrinter.print(Operand->
getType(), Out);
2731 if (
Attrs.hasAttributes()) {
2733 writeAttributeSet(
Attrs);
2737 auto WriterCtx = getContext();
2741 void AssemblyWriter::writeOperandBundles(
const CallBase *
Call) {
2742 if (!
Call->hasOperandBundles())
2747 bool FirstBundle =
true;
2748 for (
unsigned i = 0,
e =
Call->getNumOperandBundles();
i !=
e; ++
i) {
2753 FirstBundle =
false;
2761 bool FirstInput =
true;
2762 auto WriterCtx = getContext();
2763 for (
const auto &Input : BU.
Inputs) {
2768 if (Input ==
nullptr)
2769 Out <<
"<null operand bundle!>";
2771 TypePrinter.print(Input->getType(), Out);
2783 void AssemblyWriter::printModule(
const Module *
M) {
2786 if (ShouldPreserveUseListOrder)
2789 if (!
M->getModuleIdentifier().empty() &&
2792 M->getModuleIdentifier().find(
'\n') == std::string::npos)
2793 Out <<
"; ModuleID = '" <<
M->getModuleIdentifier() <<
"'\n";
2795 if (!
M->getSourceFileName().empty()) {
2796 Out <<
"source_filename = \"";
2797 printEscapedString(
M->getSourceFileName(), Out);
2801 const std::string &
DL =
M->getDataLayoutStr();
2803 Out <<
"target datalayout = \"" <<
DL <<
"\"\n";
2804 if (!
M->getTargetTriple().empty())
2805 Out <<
"target triple = \"" <<
M->getTargetTriple() <<
"\"\n";
2807 if (!
M->getModuleInlineAsm().empty()) {
2814 std::tie(Front,
Asm) =
Asm.split(
'\n');
2818 Out <<
"module asm \"";
2819 printEscapedString(Front, Out);
2821 }
while (!
Asm.empty());
2824 printTypeIdentities();
2827 if (!Comdats.empty())
2829 for (
const Comdat *
C : Comdats) {
2831 if (
C != Comdats.back())
2836 if (!
M->global_empty()) Out <<
'\n';
2838 printGlobal(&GV); Out <<
'\n';
2842 if (!
M->alias_empty()) Out <<
"\n";
2847 if (!
M->ifunc_empty()) Out <<
"\n";
2858 printUseLists(
nullptr);
2863 writeAllAttributeGroups();
2867 if (!
M->named_metadata_empty()) Out <<
'\n';
2870 printNamedMDNode(&Node);
2879 void AssemblyWriter::printModuleSummaryIndex() {
2881 int NumSlots =
Machine.initializeIndexIfNeeded();
2887 std::vector<std::pair<std::string, ModuleHash>> moduleVec;
2888 std::string RegularLTOModuleName =
2889 ModuleSummaryIndex::getRegularLTOModuleName();
2890 moduleVec.resize(TheIndex->modulePaths().size());
2891 for (
auto &[ModPath, ModId] : TheIndex->modulePaths())
2892 moduleVec[
Machine.getModulePathSlot(ModPath)] = std::make_pair(
2895 ModId.first == -1u ? RegularLTOModuleName : std::string(ModPath),
2899 for (
auto &ModPair : moduleVec) {
2900 Out <<
"^" <<
i++ <<
" = module: (";
2902 printEscapedString(ModPair.first, Out);
2903 Out <<
"\", hash: (";
2905 for (
auto Hash : ModPair.second)
2912 for (
auto &GlobalList : *TheIndex) {
2913 auto GUID = GlobalList.first;
2914 for (
auto &Summary : GlobalList.second.SummaryList)
2915 SummaryToGUIDMap[
Summary.get()] = GUID;
2919 for (
auto &GlobalList : *TheIndex) {
2920 auto GUID = GlobalList.first;
2921 auto VI = TheIndex->getValueInfo(GlobalList);
2922 printSummaryInfo(
Machine.getGUIDSlot(GUID),
VI);
2926 for (
const auto &TID : TheIndex->typeIds()) {
2927 Out <<
"^" <<
Machine.getTypeIdSlot(TID.second.first)
2928 <<
" = typeid: (name: \"" << TID.second.first <<
"\"";
2929 printTypeIdSummary(TID.second.second);
2930 Out <<
") ; guid = " << TID.first <<
"\n";
2934 for (
auto &TId : TheIndex->typeIdCompatibleVtableMap()) {
2935 auto GUID = GlobalValue::getGUID(TId.first);
2936 Out <<
"^" <<
Machine.getGUIDSlot(GUID)
2937 <<
" = typeidCompatibleVTable: (name: \"" << TId.first <<
"\"";
2938 printTypeIdCompatibleVtableSummary(TId.second);
2939 Out <<
") ; guid = " << GUID <<
"\n";
2943 if (TheIndex->getFlags()) {
2944 Out <<
"^" << NumSlots <<
" = flags: " << TheIndex->getFlags() <<
"\n";
2948 Out <<
"^" << NumSlots <<
" = blockcount: " << TheIndex->getBlockCount()
2955 case WholeProgramDevirtResolution::Indir:
2957 case WholeProgramDevirtResolution::SingleImpl:
2958 return "singleImpl";
2959 case WholeProgramDevirtResolution::BranchFunnel:
2960 return "branchFunnel";
2968 case WholeProgramDevirtResolution::ByArg::Indir:
2970 case WholeProgramDevirtResolution::ByArg::UniformRetVal:
2971 return "uniformRetVal";
2972 case WholeProgramDevirtResolution::ByArg::UniqueRetVal:
2973 return "uniqueRetVal";
2974 case WholeProgramDevirtResolution::ByArg::VirtualConstProp:
2975 return "virtualConstProp";
2984 case TypeTestResolution::Unsat:
2986 case TypeTestResolution::ByteArray:
2988 case TypeTestResolution::Inline:
2992 case TypeTestResolution::AllOnes:
3005 Out <<
", alignLog2: " << TTRes.
AlignLog2;
3007 Out <<
", sizeM1: " << TTRes.
SizeM1;
3010 Out <<
", bitMask: " << (unsigned)TTRes.
BitMask;
3017 void AssemblyWriter::printTypeIdSummary(
const TypeIdSummary &TIS) {
3018 Out <<
", summary: (";
3019 printTypeTestResolution(TIS.
TTRes);
3020 if (!TIS.
WPDRes.empty()) {
3021 Out <<
", wpdResolutions: (";
3023 for (
auto &WPDRes : TIS.
WPDRes) {
3025 Out <<
"(offset: " << WPDRes.first <<
", ";
3026 printWPDRes(WPDRes.second);
3034 void AssemblyWriter::printTypeIdCompatibleVtableSummary(
3036 Out <<
", summary: (";
3038 for (
auto &
P : TI) {
3040 Out <<
"(offset: " <<
P.AddressPointOffset <<
", ";
3041 Out <<
"^" <<
Machine.getGUIDSlot(
P.VTableVI.getGUID());
3047 void AssemblyWriter::printArgs(
const std::vector<uint64_t> &
Args) {
3050 for (
auto arg :
Args) {
3058 Out <<
"wpdRes: (kind: ";
3061 if (WPDRes.
TheKind == WholeProgramDevirtResolution::SingleImpl)
3065 Out <<
", resByArg: (";
3067 for (
auto &ResByArg : WPDRes.
ResByArg) {
3069 printArgs(ResByArg.first);
3070 Out <<
", byArg: (kind: ";
3072 if (ResByArg.second.TheKind ==
3073 WholeProgramDevirtResolution::ByArg::UniformRetVal ||
3074 ResByArg.second.TheKind ==
3075 WholeProgramDevirtResolution::ByArg::UniqueRetVal)
3076 Out <<
", info: " << ResByArg.second.Info;
3080 if (ResByArg.second.Byte || ResByArg.second.Bit)
3081 Out <<
", byte: " << ResByArg.second.Byte
3082 <<
", bit: " << ResByArg.second.Bit;
3093 case GlobalValueSummary::AliasKind:
3095 case GlobalValueSummary::FunctionKind:
3097 case GlobalValueSummary::GlobalVarKind:
3103 void AssemblyWriter::printAliasSummary(
const AliasSummary *AS) {
3104 Out <<
", aliasee: ";
3115 auto VTableFuncs =
GS->vTableFuncs();
3116 Out <<
", varFlags: (readonly: " <<
GS->VarFlags.MaybeReadOnly <<
", "
3117 <<
"writeonly: " <<
GS->VarFlags.MaybeWriteOnly <<
", "
3118 <<
"constant: " <<
GS->VarFlags.Constant;
3119 if (!VTableFuncs.empty())
3121 <<
"vcall_visibility: " <<
GS->VarFlags.VCallVisibility;
3124 if (!VTableFuncs.empty()) {
3125 Out <<
", vTableFuncs: (";
3127 for (
auto &
P : VTableFuncs) {
3129 Out <<
"(virtFunc: ^" <<
Machine.getGUIDSlot(
P.FuncVI.getGUID())
3130 <<
", offset: " <<
P.VTableOffset;
3139 case GlobalValue::ExternalLinkage:
3141 case GlobalValue::PrivateLinkage:
3143 case GlobalValue::InternalLinkage:
3145 case GlobalValue::LinkOnceAnyLinkage:
3147 case GlobalValue::LinkOnceODRLinkage:
3148 return "linkonce_odr";
3149 case GlobalValue::WeakAnyLinkage:
3151 case GlobalValue::WeakODRLinkage:
3153 case GlobalValue::CommonLinkage:
3155 case GlobalValue::AppendingLinkage:
3157 case GlobalValue::ExternalWeakLinkage:
3158 return "extern_weak";
3159 case GlobalValue::AvailableExternallyLinkage:
3160 return "available_externally";
3169 if (
LT == GlobalValue::ExternalLinkage)
3176 case GlobalValue::DefaultVisibility:
3178 case GlobalValue::HiddenVisibility:
3180 case GlobalValue::ProtectedVisibility:
3187 Out <<
", insts: " <<
FS->instCount();
3188 if (
FS->fflags().anyFlagSet())
3189 Out <<
", " <<
FS->fflags();
3191 if (!
FS->calls().empty()) {
3192 Out <<
", calls: (";
3194 for (
auto &
Call :
FS->calls()) {
3196 Out <<
"(callee: ^" <<
Machine.getGUIDSlot(
Call.first.getGUID());
3199 else if (
Call.second.RelBlockFreq)
3200 Out <<
", relbf: " <<
Call.second.RelBlockFreq;
3206 if (
const auto *TIdInfo =
FS->getTypeIdInfo())
3207 printTypeIdInfo(*TIdInfo);
3214 auto AllocTypeName = [](uint8_t
Type) ->
const char * {
3218 case (uint8_t)AllocationType::NotCold:
3223 return "notcoldandcold";
3228 if (!
FS->allocs().empty()) {
3229 Out <<
", allocs: (";
3231 for (
auto &AI :
FS->allocs()) {
3233 Out <<
"(versions: (";
3235 for (
auto V : AI.Versions) {
3237 Out << AllocTypeName(V);
3239 Out <<
"), memProf: (";
3240 FieldSeparator MIBFS;
3241 for (
auto &MIB : AI.MIBs) {
3243 Out <<
"(type: " << AllocTypeName((uint8_t)MIB.AllocType);
3244 Out <<
", stackIds: (";
3245 FieldSeparator SIDFS;
3246 for (
auto Id : MIB.StackIdIndices) {
3248 Out << TheIndex->getStackIdAtIndex(
Id);
3257 if (!
FS->callsites().empty()) {
3258 Out <<
", callsites: (";
3259 FieldSeparator SNFS;
3260 for (
auto &CI :
FS->callsites()) {
3263 Out <<
"(callee: ^" <<
Machine.getGUIDSlot(CI.Callee.getGUID());
3265 Out <<
"(callee: null";
3266 Out <<
", clones: (";
3268 for (
auto V : CI.Clones) {
3272 Out <<
"), stackIds: (";
3273 FieldSeparator SIDFS;
3274 for (
auto Id : CI.StackIdIndices) {
3276 Out << TheIndex->getStackIdAtIndex(
Id);
3284 Out <<
"[" <<
Range.getSignedMin() <<
", " <<
Range.getSignedMax() <<
"]";
3287 if (!
FS->paramAccesses().empty()) {
3288 Out <<
", params: (";
3290 for (
auto &PS :
FS->paramAccesses()) {
3292 Out <<
"(param: " << PS.ParamNo;
3293 Out <<
", offset: ";
3295 if (!PS.Calls.empty()) {
3296 Out <<
", calls: (";
3298 for (
auto &
Call : PS.Calls) {
3300 Out <<
"(callee: ^" <<
Machine.getGUIDSlot(
Call.Callee.getGUID());
3301 Out <<
", param: " <<
Call.ParamNo;
3302 Out <<
", offset: ";
3303 PrintRange(
Call.Offsets);
3314 void AssemblyWriter::printTypeIdInfo(
3316 Out <<
", typeIdInfo: (";
3317 FieldSeparator TIDFS;
3320 Out <<
"typeTests: (";
3323 auto TidIter = TheIndex->typeIds().equal_range(GUID);
3324 if (TidIter.first == TidIter.second) {
3330 for (
auto It = TidIter.first; It != TidIter.second; ++It) {
3332 auto Slot =
Machine.getTypeIdSlot(It->second.first);
3350 "typeTestAssumeConstVCalls");
3355 "typeCheckedLoadConstVCalls");
3361 auto TidIter = TheIndex->typeIds().equal_range(VFId.
GUID);
3362 if (TidIter.first == TidIter.second) {
3363 Out <<
"vFuncId: (";
3364 Out <<
"guid: " << VFId.
GUID;
3365 Out <<
", offset: " << VFId.
Offset;
3371 for (
auto It = TidIter.first; It != TidIter.second; ++It) {
3373 Out <<
"vFuncId: (";
3374 auto Slot =
Machine.getTypeIdSlot(It->second.first);
3377 Out <<
", offset: " << VFId.
Offset;
3382 void AssemblyWriter::printNonConstVCalls(
3383 const std::vector<FunctionSummary::VFuncId> &VCallList,
const char *
Tag) {
3384 Out <<
Tag <<
": (";
3386 for (
auto &VFuncId : VCallList) {
3388 printVFuncId(VFuncId);
3393 void AssemblyWriter::printConstVCalls(
3394 const std::vector<FunctionSummary::ConstVCall> &VCallList,
3396 Out <<
Tag <<
": (";
3398 for (
auto &ConstVCall : VCallList) {
3401 printVFuncId(ConstVCall.VFunc);
3402 if (!ConstVCall.Args.empty()) {
3404 printArgs(ConstVCall.Args);
3415 Out <<
"(module: ^" <<
Machine.getModulePathSlot(
Summary.modulePath())
3418 Out <<
", visibility: "
3421 Out <<
", live: " << GVFlags.
Live;
3422 Out <<
", dsoLocal: " << GVFlags.
DSOLocal;
3426 if (
Summary.getSummaryKind() == GlobalValueSummary::AliasKind)
3427 printAliasSummary(cast<AliasSummary>(&Summary));
3428 else if (
Summary.getSummaryKind() == GlobalValueSummary::FunctionKind)
3429 printFunctionSummary(cast<FunctionSummary>(&Summary));
3431 printGlobalVarSummary(cast<GlobalVarSummary>(&Summary));
3433 auto RefList =
Summary.refs();
3434 if (!RefList.empty()) {
3437 for (
auto &Ref : RefList) {
3439 if (
Ref.isReadOnly())
3441 else if (
Ref.isWriteOnly())
3442 Out <<
"writeonly ";
3443 Out <<
"^" <<
Machine.getGUIDSlot(
Ref.getGUID());
3451 void AssemblyWriter::printSummaryInfo(
unsigned Slot,
const ValueInfo &
VI) {
3452 Out <<
"^" <<
Slot <<
" = gv: (";
3453 if (!
VI.name().empty())
3454 Out <<
"name: \"" <<
VI.name() <<
"\"";
3456 Out <<
"guid: " <<
VI.getGUID();
3457 if (!
VI.getSummaryList().empty()) {
3458 Out <<
", summaries: (";
3460 for (
auto &Summary :
VI.getSummaryList()) {
3462 printSummary(*Summary);
3467 if (!
VI.name().empty())
3468 Out <<
" ; guid = " <<
VI.getGUID();
3475 Out <<
"<empty name> ";
3477 if (isalpha(
static_cast<unsigned char>(
Name[0])) ||
Name[0] ==
'-' ||
3481 Out <<
'\\' << hexdigit(
Name[0] >> 4) << hexdigit(
Name[0] & 0x0F);
3482 for (
unsigned i = 1,
e =
Name.size();
i !=
e; ++
i) {
3483 unsigned char C =
Name[
i];
3484 if (isalnum(
static_cast<unsigned char>(
C)) ||
C ==
'-' ||
C ==
'$' ||
3485 C ==
'.' ||
C ==
'_')
3488 Out <<
'\\' << hexdigit(
C >> 4) << hexdigit(
C & 0x0F);
3493 void AssemblyWriter::printNamedMDNode(
const NamedMDNode *NMD) {
3505 "DIArgLists should not appear in NamedMDNodes");
3506 if (
auto *Expr = dyn_cast<DIExpression>(
Op)) {
3523 case GlobalValue::DefaultVisibility:
break;
3524 case GlobalValue::HiddenVisibility: Out <<
"hidden ";
break;
3525 case GlobalValue::ProtectedVisibility: Out <<
"protected ";
break;
3532 Out <<
"dso_local ";
3538 case GlobalValue::DefaultStorageClass:
break;
3539 case GlobalValue::DLLImportStorageClass: Out <<
"dllimport ";
break;
3540 case GlobalValue::DLLExportStorageClass: Out <<
"dllexport ";
break;
3547 case GlobalVariable::NotThreadLocal:
3549 case GlobalVariable::GeneralDynamicTLSModel:
3550 Out <<
"thread_local ";
3552 case GlobalVariable::LocalDynamicTLSModel:
3553 Out <<
"thread_local(localdynamic) ";
3555 case GlobalVariable::InitialExecTLSModel:
3556 Out <<
"thread_local(initialexec) ";
3558 case GlobalVariable::LocalExecTLSModel:
3559 Out <<
"thread_local(localexec) ";
3568 case GlobalVariable::UnnamedAddr::Local:
3569 return "local_unnamed_addr";
3570 case GlobalVariable::UnnamedAddr::Global:
3571 return "unnamed_addr";
3582 if (isa<GlobalVariable>(GO))
3596 Out <<
"; Materializable\n";
3617 Out << (GV->
isConstant() ?
"constant " :
"global ");
3626 Out <<
", section \"";
3631 Out <<
", partition \"";
3640 Out <<
", no_sanitize_address";
3642 Out <<
", no_sanitize_hwaddress";
3644 Out <<
", sanitize_memtag";
3646 Out <<
", sanitize_address_dyninit";
3651 Out <<
", align " <<
A->value();
3655 printMetadataAttachments(MDs,
", ");
3658 if (
Attrs.hasAttributes())
3661 printInfoComment(*GV);
3664 void AssemblyWriter::printAlias(
const GlobalAlias *GA) {
3666 Out <<
"; Materializable\n";
3687 writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
3689 TypePrinter.print(GA->
getType(), Out);
3690 Out <<
" <<NULL ALIASEE>>";
3694 Out <<
", partition \"";
3699 printInfoComment(*GA);
3703 void AssemblyWriter::printIFunc(
const GlobalIFunc *GI) {
3705 Out <<
"; Materializable\n";
3723 TypePrinter.print(GI->
getType(), Out);
3724 Out <<
" <<NULL RESOLVER>>";
3728 Out <<
", partition \"";
3733 printInfoComment(*GI);
3737 void AssemblyWriter::printComdat(
const Comdat *
C) {
3741 void AssemblyWriter::printTypeIdentities() {
3742 if (TypePrinter.empty())
3748 auto &NumberedTypes = TypePrinter.getNumberedTypes();
3749 for (
unsigned I = 0,
E = NumberedTypes.size();
I !=
E; ++
I) {
3750 Out <<
'%' <<
I <<
" = type ";
3754 TypePrinter.printStructBody(NumberedTypes[
I], Out);
3758 auto &NamedTypes = TypePrinter.getNamedTypes();
3765 TypePrinter.printStructBody(NamedType, Out);
3771 void AssemblyWriter::printFunction(
const Function *
F) {
3772 if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(
F, Out);
3774 if (
F->isMaterializable())
3775 Out <<
"; Materializable\n";
3778 if (
Attrs.hasFnAttrs()) {
3780 std::string AttrStr;
3783 if (!Attr.isStringAttribute()) {
3784 if (!AttrStr.empty()) AttrStr +=
' ';
3785 AttrStr += Attr.getAsString();
3789 if (!AttrStr.empty())
3790 Out <<
"; Function Attrs: " << AttrStr <<
'\n';
3795 if (
F->isDeclaration()) {
3798 F->getAllMetadata(MDs);
3799 printMetadataAttachments(MDs,
" ");
3816 if (
Attrs.hasRetAttrs())
3817 Out <<
Attrs.getAsString(AttributeList::ReturnIndex) <<
' ';
3818 TypePrinter.
print(
F->getReturnType(), Out);
3819 AsmWriterContext WriterCtx(&TypePrinter, &
Machine,
F->getParent());
3825 if (
F->isDeclaration() && !IsForDebug) {
3837 writeAttributeSet(ArgAttrs);
3844 if (
Arg.getArgNo() != 0)
3846 printArgument(&
Arg,
Attrs.getParamAttrs(
Arg.getArgNo()));
3863 if (
F->getAddressSpace() != 0 || !
Mod ||
3865 Out <<
" addrspace(" <<
F->getAddressSpace() <<
")";
3866 if (
Attrs.hasFnAttrs())
3867 Out <<
" #" <<
Machine.getAttributeGroupSlot(
Attrs.getFnAttrs());
3868 if (
F->hasSection()) {
3869 Out <<
" section \"";
3870 printEscapedString(
F->getSection(), Out);
3873 if (
F->hasPartition()) {
3874 Out <<
" partition \"";
3875 printEscapedString(
F->getPartition(), Out);
3880 Out <<
" align " <<
A->value();
3882 Out <<
" gc \"" <<
F->getGC() <<
'"';
3883 if (
F->hasPrefixData()) {
3885 writeOperand(
F->getPrefixData(),
true);
3887 if (
F->hasPrologueData()) {
3888 Out <<
" prologue ";
3889 writeOperand(
F->getPrologueData(),
true);
3891 if (
F->hasPersonalityFn()) {
3892 Out <<
" personality ";
3893 writeOperand(
F->getPersonalityFn(),
true);
3896 if (
F->isDeclaration()) {
3900 F->getAllMetadata(MDs);
3901 printMetadataAttachments(MDs,
" ");
3906 printBasicBlock(&
BB);
3921 TypePrinter.print(
Arg->getType(), Out);
3924 if (
Attrs.hasAttributes()) {
3926 writeAttributeSet(
Attrs);
3930 if (
Arg->hasName()) {
3935 assert(Slot != -1 &&
"expect argument in function here");
3936 Out <<
" %" <<
Slot;
3941 void AssemblyWriter::printBasicBlock(
const BasicBlock *
BB) {
3942 bool IsEntryBlock =
BB->getParent() &&
BB->isEntryBlock();
3943 if (
BB->hasName()) {
3947 }
else if (!IsEntryBlock) {
3956 if (!IsEntryBlock) {
3958 Out.PadToColumn(50);
3963 Out <<
" No predecessors!";
3966 writeOperand(*PI,
false);
3967 for (++PI; PI != PE; ++PI) {
3969 writeOperand(*PI,
false);
3976 if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(
BB, Out);
3980 printInstructionLine(
I);
3983 if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(
BB, Out);
3987 void AssemblyWriter::printInstructionLine(
const Instruction &
I) {
3988 printInstruction(
I);
3994 void AssemblyWriter::printGCRelocateComment(
const GCRelocateInst &Relocate) {
4004 void AssemblyWriter::printInfoComment(
const Value &V) {
4005 if (
const auto *Relocate = dyn_cast<GCRelocateInst>(&V))
4006 printGCRelocateComment(*Relocate);
4008 if (AnnotationWriter)
4009 AnnotationWriter->printInfoComment(V, Out);
4015 if (Operand ==
nullptr) {
4016 Out <<
" <cannot get addrspace!>";
4020 bool PrintAddrSpace = CallAddrSpace != 0;
4021 if (!PrintAddrSpace) {
4027 PrintAddrSpace =
true;
4030 Out <<
" addrspace(" << CallAddrSpace <<
")";
4034 void AssemblyWriter::printInstruction(
const Instruction &
I) {
4035 if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&
I, Out);
4044 }
else if (!
I.getType()->isVoidTy()) {
4046 int SlotNum =
Machine.getLocalSlot(&
I);
4048 Out <<
"<badref> = ";
4050 Out <<
'%' << SlotNum <<
" = ";
4053 if (
const CallInst *CI = dyn_cast<CallInst>(&
I)) {
4054 if (CI->isMustTailCall())
4056 else if (CI->isTailCall())
4058 else if (CI->isNoTailCall())
4063 Out <<
I.getOpcodeName();
4066 if ((isa<LoadInst>(
I) && cast<LoadInst>(
I).isAtomic()) ||
4067 (isa<StoreInst>(
I) && cast<StoreInst>(
I).isAtomic()))
4070 if (isa<AtomicCmpXchgInst>(
I) && cast<AtomicCmpXchgInst>(
I).isWeak())
4074 if ((isa<LoadInst>(
I) && cast<LoadInst>(
I).isVolatile()) ||
4075 (isa<StoreInst>(
I) && cast<StoreInst>(
I).isVolatile()) ||
4076 (isa<AtomicCmpXchgInst>(
I) && cast<AtomicCmpXchgInst>(
I).isVolatile()) ||
4077 (isa<AtomicRMWInst>(
I) && cast<AtomicRMWInst>(
I).isVolatile()))
4084 if (
const CmpInst *CI = dyn_cast<CmpInst>(&
I))
4085 Out <<
' ' << CmpInst::getPredicateName(CI->getPredicate());
4089 Out <<
' ' << AtomicRMWInst::getOperationName(RMWI->getOperation());
4092 const Value *Operand =
I.getNumOperands() ?
I.getOperand(0) :
nullptr;
4095 if (isa<BranchInst>(
I) && cast<BranchInst>(
I).isConditional()) {
4098 writeOperand(BI.getCondition(),
true);
4100 writeOperand(BI.getSuccessor(0),
true);
4102 writeOperand(BI.getSuccessor(1),
true);
4104 }
else if (isa<SwitchInst>(
I)) {
4108 writeOperand(
SI.getCondition(),
true);
4110 writeOperand(
SI.getDefaultDest(),
true);
4112 for (
auto Case :
SI.cases()) {
4114 writeOperand(Case.getCaseValue(),
true);
4116 writeOperand(Case.getCaseSuccessor(),
true);
4119 }
else if (isa<IndirectBrInst>(
I)) {
4122 writeOperand(Operand,
true);
4125 for (
unsigned i = 1,
e =
I.getNumOperands();
i !=
e; ++
i) {
4128 writeOperand(
I.getOperand(
i),
true);
4131 }
else if (
const PHINode *PN = dyn_cast<PHINode>(&
I)) {
4133 TypePrinter.print(
I.getType(), Out);
4136 for (
unsigned op = 0, Eop = PN->getNumIncomingValues();
op < Eop; ++
op) {
4137 if (
op) Out <<
", ";
4139 writeOperand(PN->getIncomingValue(
op),
false); Out <<
", ";
4140 writeOperand(PN->getIncomingBlock(
op),
false); Out <<
" ]";
4144 writeOperand(
I.getOperand(0),
true);
4145 for (
unsigned i : EVI->indices())
4149 writeOperand(
I.getOperand(0),
true); Out <<
", ";
4150 writeOperand(
I.getOperand(1),
true);
4151 for (
unsigned i : IVI->indices())
4153 }
else if (
const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&
I)) {
4155 TypePrinter.print(
I.getType(), Out);
4156 if (LPI->isCleanup() || LPI->getNumClauses() != 0)
4159 if (LPI->isCleanup())
4162 for (
unsigned i = 0,
e = LPI->getNumClauses();
i !=
e; ++
i) {
4163 if (
i != 0 || LPI->isCleanup()) Out <<
"\n";
4164 if (LPI->isCatch(
i))
4169 writeOperand(LPI->getClause(
i),
true);
4171 }
else if (
const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(&
I)) {
4173 writeOperand(CatchSwitch->getParentPad(),
false);
4176 for (
const BasicBlock *PadBB : CatchSwitch->handlers()) {
4179 writeOperand(PadBB,
true);
4183 if (
const BasicBlock *UnwindDest = CatchSwitch->getUnwindDest())
4184 writeOperand(UnwindDest,
true);
4187 }
else if (
const auto *FPI = dyn_cast<FuncletPadInst>(&
I)) {
4189 writeOperand(FPI->getParentPad(),
false);
4191 for (
unsigned Op = 0, NumOps = FPI->arg_size();
Op < NumOps; ++
Op) {
4194 writeOperand(FPI->getArgOperand(
Op),
true);
4197 }
else if (isa<ReturnInst>(
I) && !Operand) {
4199 }
else if (
const auto *CRI = dyn_cast<CatchReturnInst>(&
I)) {
4201 writeOperand(CRI->getOperand(0),
false);
4204 writeOperand(CRI->getOperand(1),
true);
4205 }
else if (
const auto *CRI = dyn_cast<CleanupReturnInst>(&
I)) {
4207 writeOperand(CRI->getOperand(0),
false);
4210 if (CRI->hasUnwindDest())
4211 writeOperand(CRI->getOperand(1),
true);
4214 }
else if (
const CallInst *CI = dyn_cast<CallInst>(&
I)) {
4221 Operand = CI->getCalledOperand();
4227 Out <<
' ' << PAL.
getAsString(AttributeList::ReturnIndex);
4236 TypePrinter.print(FTy->
isVarArg() ? FTy : RetTy, Out);
4238 writeOperand(Operand,
false);
4240 for (
unsigned op = 0, Eop = CI->arg_size();
op < Eop; ++
op) {
4248 if (CI->isMustTailCall() && CI->getParent() &&
4249 CI->getParent()->getParent() &&
4250 CI->getParent()->getParent()->isVarArg()) {
4251 if (CI->arg_size() > 0)
4260 writeOperandBundles(CI);
4261 }
else if (
const InvokeInst *II = dyn_cast<InvokeInst>(&
I)) {
4262 Operand = II->getCalledOperand();
4274 Out <<
' ' << PAL.
getAsString(AttributeList::ReturnIndex);
4284 TypePrinter.print(FTy->
isVarArg() ? FTy : RetTy, Out);
4286 writeOperand(Operand,
false);
4288 for (
unsigned op = 0, Eop = II->arg_size();
op < Eop; ++
op) {
4298 writeOperandBundles(II);
4301 writeOperand(II->getNormalDest(),
true);
4303 writeOperand(II->getUnwindDest(),
true);
4304 }
else if (
const CallBrInst *CBI = dyn_cast<CallBrInst>(&
I)) {
4305 Operand = CBI->getCalledOperand();
4317 Out <<
' ' << PAL.
getAsString(AttributeList::ReturnIndex);
4324 TypePrinter.print(FTy->
isVarArg() ? FTy : RetTy, Out);
4326 writeOperand(Operand,
false);
4328 for (
unsigned op = 0, Eop = CBI->arg_size();
op < Eop; ++
op) {
4338 writeOperandBundles(CBI);
4341 writeOperand(CBI->getDefaultDest(),
true);
4343 for (
unsigned i = 0,
e = CBI->getNumIndirectDests();
i !=
e; ++
i) {
4346 writeOperand(CBI->getIndirectDest(
i),
true);
4349 }
else if (
const AllocaInst *AI = dyn_cast<AllocaInst>(&
I)) {
4351 if (AI->isUsedWithInAlloca())
4353 if (AI->isSwiftError())
4354 Out <<
"swifterror ";
4355 TypePrinter.print(AI->getAllocatedType(), Out);
4361 if (!AI->getArraySize() || AI->isArrayAllocation() ||
4362 !AI->getArraySize()->getType()->isIntegerTy(32)) {
4364 writeOperand(AI->getArraySize(),
true);
4367 Out <<
", align " <<
A->value();
4370 unsigned AddrSpace = AI->getAddressSpace();
4371 if (AddrSpace != 0) {
4372 Out <<
", addrspace(" << AddrSpace <<
')';
4374 }
else if (isa<CastInst>(
I)) {
4377 writeOperand(Operand,
true);
4380 TypePrinter.print(
I.getType(), Out);
4381 }
else if (isa<VAArgInst>(
I)) {
4384 writeOperand(Operand,
true);
4387 TypePrinter.print(
I.getType(), Out);
4388 }
else if (Operand) {
4389 if (
const auto *
GEP = dyn_cast<GetElementPtrInst>(&
I)) {
4391 TypePrinter.print(
GEP->getSourceElementType(), Out);
4393 }
else if (
const auto *LI = dyn_cast<LoadInst>(&
I)) {
4395 TypePrinter.print(LI->getType(), Out);
4402 bool PrintAllTypes =
false;
4407 if (isa<SelectInst>(
I) || isa<StoreInst>(
I) || isa<ShuffleVectorInst>(
I) ||
4408 isa<ReturnInst>(
I) || isa<AtomicCmpXchgInst>(
I) ||
4409 isa<AtomicRMWInst>(
I)) {
4410 PrintAllTypes =
true;
4412 for (
unsigned i = 1,
E =
I.getNumOperands();
i !=
E; ++
i) {
4413 Operand =
I.getOperand(
i);
4416 if (Operand && Operand->
getType() != TheType) {
4417 PrintAllTypes =
true;
4423 if (!PrintAllTypes) {
4425 TypePrinter.print(TheType, Out);
4429 for (
unsigned i = 0,
E =
I.getNumOperands();
i !=
E; ++
i) {
4431 writeOperand(
I.getOperand(
i), PrintAllTypes);
4436 if (
const LoadInst *LI = dyn_cast<LoadInst>(&
I)) {
4438 writeAtomic(LI->getContext(), LI->getOrdering(), LI->getSyncScopeID());
4440 Out <<
", align " <<
A->value();
4441 }
else if (
const StoreInst *
SI = dyn_cast<StoreInst>(&
I)) {
4443 writeAtomic(
SI->getContext(),
SI->getOrdering(),
SI->getSyncScopeID());
4445 Out <<
", align " <<
A->value();
4447 writeAtomicCmpXchg(CXI->getContext(), CXI->getSuccessOrdering(),
4448 CXI->getFailureOrdering(), CXI->getSyncScopeID());
4449 Out <<
", align " << CXI->getAlign().value();
4450 }
else if (
const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&
I)) {
4451 writeAtomic(RMWI->getContext(), RMWI->getOrdering(),
4452 RMWI->getSyncScopeID());
4453 Out <<
", align " << RMWI->getAlign().value();
4454 }
else if (
const FenceInst *FI = dyn_cast<FenceInst>(&
I)) {
4455 writeAtomic(FI->getContext(), FI->getOrdering(), FI->getSyncScopeID());
4462 I.getAllMetadata(InstMD);
4463 printMetadataAttachments(InstMD,
", ");
4466 printInfoComment(
I);
4469 void AssemblyWriter::printMetadataAttachments(
4475 if (MDNames.empty())
4476 MDs[0].second->getContext().getMDKindNames(MDNames);
4478 auto WriterCtx = getContext();
4479 for (
const auto &
I : MDs) {
4480 unsigned Kind =
I.first;
4482 if (
Kind < MDNames.size()) {
4486 Out <<
"!<unknown kind #" <<
Kind <<
">";
4492 void AssemblyWriter::writeMDNode(
unsigned Slot,
const MDNode *Node) {
4493 Out <<
'!' <<
Slot <<
" = ";
4494 printMDNodeBody(Node);
4498 void AssemblyWriter::writeAllMDNodes() {
4502 Nodes[
I.second] = cast<MDNode>(
I.first);
4504 for (
unsigned i = 0,
e = Nodes.size();
i !=
e; ++
i) {
4505 writeMDNode(
i, Nodes[
i]);
4509 void AssemblyWriter::printMDNodeBody(
const MDNode *Node) {
4510 auto WriterCtx = getContext();
4514 void AssemblyWriter::writeAttribute(
const Attribute &Attr,
bool InAttrGroup) {
4520 Out << Attribute::getNameFromAttrKind(Attr.
getKindAsEnum());
4523 TypePrinter.print(Ty, Out);
4528 void AssemblyWriter::writeAttributeSet(
const AttributeSet &AttrSet,
4530 bool FirstAttr =
true;
4531 for (
const auto &Attr : AttrSet) {
4534 writeAttribute(Attr, InAttrGroup);
4539 void AssemblyWriter::writeAllAttributeGroups() {
4540 std::vector<std::pair<AttributeSet, unsigned>> asVec;
4541 asVec.resize(
Machine.as_size());
4544 asVec[
I.second] =
I;
4546 for (
const auto &
I : asVec)
4547 Out <<
"attributes #" <<
I.second <<
" = { "
4548 <<
I.first.getAsString(
true) <<
" }\n";
4551 void AssemblyWriter::printUseListOrder(
const Value *V,
4552 const std::vector<unsigned> &Shuffle) {
4553 bool IsInFunction =
Machine.getFunction();
4557 Out <<
"uselistorder";
4558 if (
const BasicBlock *
BB = IsInFunction ?
nullptr : dyn_cast<BasicBlock>(V)) {
4560 writeOperand(
BB->getParent(),
false);
4562 writeOperand(
BB,
false);
4565 writeOperand(V,
true);
4576 void AssemblyWriter::printUseLists(
const Function *
F) {
4577 auto It = UseListOrders.find(
F);
4578 if (It == UseListOrders.end())
4581 Out <<
"\n; uselistorder directives\n";
4582 for (
const auto &Pair : It->second)
4583 printUseListOrder(Pair.first, Pair.second);
4591 bool ShouldPreserveUseListOrder,
4592 bool IsForDebug)
const {
4595 AssemblyWriter
W(OS, SlotTable, this->
getParent(), AAW,
4597 ShouldPreserveUseListOrder);
4598 W.printFunction(
this);
4602 bool ShouldPreserveUseListOrder,
4603 bool IsForDebug)
const {
4606 AssemblyWriter
W(OS, SlotTable, this->
getModule(), AAW,
4608 ShouldPreserveUseListOrder);
4609 W.printBasicBlock(
this);
4613 bool ShouldPreserveUseListOrder,
bool IsForDebug)
const {
4616 AssemblyWriter
W(OS, SlotTable,
this, AAW, IsForDebug,
4617 ShouldPreserveUseListOrder);
4618 W.printModule(
this);
4624 AssemblyWriter
W(OS, SlotTable,
getParent(),
nullptr, IsForDebug);
4625 W.printNamedMDNode(
this);
4629 bool IsForDebug)
const {
4630 std::optional<SlotTracker> LocalST;
4636 SlotTable = &*LocalST;
4640 AssemblyWriter
W(OS, *SlotTable,
getParent(),
nullptr, IsForDebug);
4641 W.printNamedMDNode(
this);
4646 ROS <<
" = comdat ";
4653 ROS <<
"exactmatch";
4659 ROS <<
"nodeduplicate";
4671 TP.print(
const_cast<Type*
>(
this), OS);
4677 if (
StructType *STy = dyn_cast<StructType>(
const_cast<Type*
>(
this)))
4680 TP.printStructBody(STy, OS);
4685 if (
const auto *CI = dyn_cast<CallInst>(&
I))
4686 if (
Function *
F = CI->getCalledFunction())
4687 if (
F->isIntrinsic())
4688 for (
auto &
Op :
I.operands())
4689 if (
auto *V = dyn_cast_or_null<MetadataAsValue>(
Op))
4696 bool ShouldInitializeAllMetadata =
false;
4697 if (
auto *
I = dyn_cast<Instruction>(
this))
4699 else if (isa<Function>(
this) || isa<MetadataAsValue>(
this))
4700 ShouldInitializeAllMetadata =
true;
4703 print(ROS, MST, IsForDebug);
4707 bool IsForDebug)
const {
4712 auto incorporateFunction = [&](
const Function *
F) {
4717 if (
const Instruction *
I = dyn_cast<Instruction>(
this)) {
4718 incorporateFunction(
I->getParent() ?
I->getParent()->getParent() :
nullptr);
4720 W.printInstruction(*
I);
4721 }
else if (
const BasicBlock *
BB = dyn_cast<BasicBlock>(
this)) {
4722 incorporateFunction(
BB->getParent());
4724 W.printBasicBlock(
BB);
4725 }
else if (
const GlobalValue *GV = dyn_cast<GlobalValue>(
this)) {
4726 AssemblyWriter
W(OS, SlotTable, GV->
getParent(),
nullptr, IsForDebug);
4729 else if (
const Function *
F = dyn_cast<Function>(GV))
4731 else if (
const GlobalAlias *A = dyn_cast<GlobalAlias>(GV))
4733 else if (
const GlobalIFunc *
I = dyn_cast<GlobalIFunc>(GV))
4737 }
else if (
const MetadataAsValue *V = dyn_cast<MetadataAsValue>(
this)) {
4739 }
else if (
const Constant *
C = dyn_cast<Constant>(
this)) {
4740 TypePrinting TypePrinter;
4741 TypePrinter.print(
C->getType(), OS);
4743 AsmWriterContext WriterCtx(&TypePrinter, MST.
getMachine());
4745 }
else if (isa<InlineAsm>(
this) || isa<Argument>(
this)) {
4757 if (V.
hasName() || isa<GlobalValue>(V) ||
4758 (!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
4759 AsmWriterContext WriterCtx(
nullptr,
Machine,
M);
4768 TypePrinting TypePrinter(MST.
getModule());
4788 M, isa<MetadataAsValue>(
this));
4804 AsmWriterContext &WriterCtx) {
4808 auto *
N = dyn_cast<MDNode>(&MD);
4809 if (!
N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
4817 struct MDTreeAsmWriterContext :
public AsmWriterContext {
4820 using EntryTy = std::pair<unsigned, std::string>;
4830 : AsmWriterContext(TP,
ST,
M),
Level(0U), Visited({InitMD}), MainOS(OS) {}
4832 void onWriteMetadataAsOperand(
const Metadata *MD)
override {
4833 if (!Visited.
insert(MD).second)
4842 unsigned InsertIdx = Buffer.size() - 1;
4849 ~MDTreeAsmWriterContext() {
4850 for (
const auto &Entry : Buffer) {
4852 unsigned NumIndent = Entry.first * 2U;
4853 MainOS.
indent(NumIndent) << Entry.second;
4861 bool OnlyAsOperand,
bool PrintAsTree =
false) {
4864 TypePrinting TypePrinter(
M);
4866 std::unique_ptr<AsmWriterContext> WriterCtx;
4867 if (PrintAsTree && !OnlyAsOperand)
4868 WriterCtx = std::make_unique<MDTreeAsmWriterContext>(
4872 std::make_unique<AsmWriterContext>(&TypePrinter, MST.
getMachine(),
M);
4876 auto *
N = dyn_cast<MDNode>(&MD);
4877 if (OnlyAsOperand || !
N || isa<DIExpression>(MD) || isa<DIArgList>(MD))
4901 const Module *M,
bool )
const {
4920 AssemblyWriter
W(OS, SlotTable,
this, IsForDebug);
4921 W.printModuleSummaryIndex();
4925 unsigned UB)
const {
4931 if (
I.second >= LB &&
I.second < UB)
4932 L.push_back(std::make_pair(
I.second,
I.first));
4935 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)