25#include "llvm/Config/llvm-config.h"
55#include "llvm/IR/IntrinsicsAArch64.h"
56#include "llvm/IR/IntrinsicsARM.h"
89#include <system_error>
99 "Print the global id for each value when reading the module summary"));
104 SWITCH_INST_MAGIC = 0x4B5
117 "file too small to contain bitcode header");
118 for (
unsigned C : {
'B',
'C'})
122 "file doesn't start with bitcode header");
124 return Res.takeError();
125 for (
unsigned C : {0x0, 0xC, 0xE, 0xD})
129 "file doesn't start with bitcode header");
131 return Res.takeError();
136 const unsigned char *BufPtr = (
const unsigned char *)Buffer.
getBufferStart();
137 const unsigned char *BufEnd = BufPtr + Buffer.
getBufferSize();
140 return error(
"Invalid bitcode signature");
146 return error(
"Invalid bitcode wrapper header");
150 return std::move(Err);
152 return std::move(Stream);
156template <
typename StrTy>
169 if (
F.isMaterializable())
172 I.setMetadata(LLVMContext::MD_tbaa,
nullptr);
180 return std::move(Err);
185 std::string ProducerIdentification;
192 switch (Entry.Kind) {
195 return error(
"Malformed block");
197 return ProducerIdentification;
208 switch (MaybeBitCode.
get()) {
210 return error(
"Invalid value");
218 Twine(
"Incompatible epoch: Bitcode '") +
Twine(epoch) +
237 switch (Entry.Kind) {
240 return error(
"Malformed block");
248 return std::move(Err);
260 return std::move(Err);
271 switch (Entry.Kind) {
274 return error(
"Malformed block");
286 switch (MaybeRecord.
get()) {
292 return error(
"Invalid section name record");
297 Segment = Segment.trim();
298 Section = Section.trim();
300 if (Segment ==
"__DATA" && Section.starts_with(
"__objc_catlist"))
302 if (Segment ==
"__OBJC" && Section.starts_with(
"__category"))
304 if (Segment ==
"__TEXT" && Section.starts_with(
"__swift"))
322 switch (Entry.Kind) {
324 return error(
"Malformed block");
334 return std::move(Err);
347 return std::move(Err);
360 switch (Entry.Kind) {
363 return error(
"Malformed block");
375 switch (MaybeRecord.
get()) {
380 return error(
"Invalid triple record");
399 switch (Entry.Kind) {
401 return error(
"Malformed block");
411 return std::move(Err);
418 return Skipped.takeError();
425class BitcodeReaderBase {
427 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
428 : Stream(std::
move(Stream)), Strtab(Strtab) {
429 this->Stream.setBlockInfo(&BlockInfo);
432 BitstreamBlockInfo BlockInfo;
433 BitstreamCursor Stream;
438 bool UseStrtab =
false;
440 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
445 std::pair<StringRef, ArrayRef<uint64_t>>
446 readNameFromStrtab(ArrayRef<uint64_t> Record);
448 Error readBlockInfo();
451 std::string ProducerIdentification;
458Error BitcodeReaderBase::error(
const Twine &Message) {
459 std::string FullMsg = Message.
str();
460 if (!ProducerIdentification.empty())
461 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
462 LLVM_VERSION_STRING
"')";
463 return ::error(FullMsg);
467BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
469 return error(
"Invalid version record");
470 unsigned ModuleVersion =
Record[0];
471 if (ModuleVersion > 2)
472 return error(
"Invalid value");
473 UseStrtab = ModuleVersion >= 2;
474 return ModuleVersion;
477std::pair<StringRef, ArrayRef<uint64_t>>
478BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
485 if (
Record.size() < 2 || Record[0] > Strtab.
size() ||
486 Record[1] > Strtab.
size() - Record[0])
488 return {StringRef(Strtab.
data() + Record[0], Record[1]),
Record.slice(2)};
499class BitcodeConstant final :
public Value,
500 TrailingObjects<BitcodeConstant, unsigned> {
501 friend TrailingObjects;
504 static constexpr uint8_t SubclassID = 255;
512 static constexpr uint8_t ConstantStructOpcode = 255;
513 static constexpr uint8_t ConstantArrayOpcode = 254;
514 static constexpr uint8_t ConstantVectorOpcode = 253;
515 static constexpr uint8_t NoCFIOpcode = 252;
516 static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
517 static constexpr uint8_t BlockAddressOpcode = 250;
518 static constexpr uint8_t ConstantPtrAuthOpcode = 249;
519 static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
526 unsigned BlockAddressBB = 0;
527 Type *SrcElemTy =
nullptr;
528 std::optional<ConstantRange>
InRange;
530 ExtraInfo(uint8_t Opcode, uint8_t Flags = 0,
Type *SrcElemTy =
nullptr,
531 std::optional<ConstantRange>
InRange = std::nullopt)
532 : Opcode(Opcode),
Flags(
Flags), SrcElemTy(SrcElemTy),
535 ExtraInfo(uint8_t Opcode, uint8_t Flags,
unsigned BlockAddressBB)
536 : Opcode(Opcode),
Flags(
Flags), BlockAddressBB(BlockAddressBB) {}
541 unsigned NumOperands;
542 unsigned BlockAddressBB;
544 std::optional<ConstantRange>
InRange;
547 BitcodeConstant(
Type *Ty,
const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
549 NumOperands(OpIDs.
size()), BlockAddressBB(
Info.BlockAddressBB),
554 BitcodeConstant &operator=(
const BitcodeConstant &) =
delete;
558 const ExtraInfo &Info,
559 ArrayRef<unsigned> OpIDs) {
560 void *Mem =
A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.
size()),
561 alignof(BitcodeConstant));
562 return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
565 static bool classof(
const Value *
V) {
return V->getValueID() == SubclassID; }
567 ArrayRef<unsigned> getOperandIDs()
const {
568 return ArrayRef(getTrailingObjects(), NumOperands);
571 std::optional<ConstantRange> getInRange()
const {
572 assert(Opcode == Instruction::GetElementPtr);
581class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
582 const BitReaderOptions &Opts;
584 Module *TheModule =
nullptr;
585 std::optional<Triple> TargetTriple;
590 bool SeenValueSymbolTable =
false;
593 std::vector<std::string> SectionTable;
594 std::vector<std::string> GCTable;
596 std::vector<Type *> TypeList;
600 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
607 DenseMap<std::pair<Type *, unsigned>,
unsigned> VirtualTypeIDs;
608 DenseMap<Function *, unsigned> FunctionTypeIDs;
613 BitcodeReaderValueList ValueList;
614 std::optional<MetadataLoader> MDLoader;
615 std::vector<Comdat *> ComdatList;
616 DenseSet<GlobalObject *> ImplicitComdatObjects;
619 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
620 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
622 struct FunctionOperandInfo {
624 unsigned PersonalityFn;
628 std::vector<FunctionOperandInfo> FunctionOperands;
632 std::vector<AttributeList> MAttributes;
635 std::map<unsigned, AttributeList> MAttributeGroups;
639 std::vector<BasicBlock*> FunctionBBs;
643 std::vector<Function*> FunctionsWithBodies;
647 DenseMap<Function *, Function *> UpgradedIntrinsics;
652 bool SeenFirstFunctionBody =
false;
656 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
661 std::vector<uint64_t> DeferredMetadataInfo;
666 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
667 std::deque<Function *> BasicBlockFwdRefQueue;
674 std::vector<Function *> BackwardRefFunctions;
682 bool UseRelativeIDs =
false;
686 bool WillMaterializeAllForwardRefs =
false;
690 bool SeenDebugIntrinsic =
false;
691 bool SeenDebugRecord =
false;
694 TBAAVerifier TBAAVerifyHelper;
696 std::vector<std::string> BundleTags;
699 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
702 std::vector<GlobalValue::GUID> GUIDList;
708 bool SeenGUIDList =
false;
711 bool UpgradedGUIDs =
false;
717 bool SkipDebugIntrinsicUpgrade =
false;
720 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
721 StringRef ProducerIdentification, LLVMContext &
Context);
723 Error materializeForwardReferencedFunctions();
725 Error materialize(GlobalValue *GV)
override;
726 Error materializeModule()
override;
727 std::vector<StructType *> getIdentifiedStructTypes()
const override;
731 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
732 bool IsImporting, ParserCallbacks Callbacks = {});
737 Error materializeMetadata()
override;
739 void setStripDebugInfo()
override;
742 std::vector<StructType *> IdentifiedStructTypes;
743 StructType *createIdentifiedStructType(LLVMContext &
Context, StringRef Name);
744 StructType *createIdentifiedStructType(LLVMContext &
Context);
746 static constexpr unsigned InvalidTypeID = ~0
u;
748 Type *getTypeByID(
unsigned ID);
749 Type *getPtrElementTypeByID(
unsigned ID);
750 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
751 unsigned getVirtualTypeID(
Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
754 Expected<Value *> materializeValue(
unsigned ValID, BasicBlock *InsertBB);
755 Expected<Constant *> getValueForInitializer(
unsigned ID);
757 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
758 BasicBlock *ConstExprInsertBB) {
764 Metadata *getFnMetadataByID(
unsigned ID) {
765 return MDLoader->getMetadataFwdRefOrLoad(ID);
768 BasicBlock *getBasicBlock(
unsigned ID)
const {
769 if (ID >= FunctionBBs.size())
return nullptr;
770 return FunctionBBs[
ID];
774 if (i-1 < MAttributes.size())
775 return MAttributes[i-1];
776 return AttributeList();
782 bool getValueTypePair(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
783 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
784 BasicBlock *ConstExprInsertBB) {
785 if (Slot ==
Record.size())
return true;
786 unsigned ValNo = (unsigned)Record[Slot++];
789 ValNo = InstNum - ValNo;
790 if (ValNo < InstNum) {
794 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
796 "Incorrect type ID stored for value");
797 return ResVal ==
nullptr;
799 if (Slot ==
Record.size())
802 TypeID = (unsigned)Record[Slot++];
803 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
805 return ResVal ==
nullptr;
808 bool getValueOrMetadata(
const SmallVectorImpl<uint64_t> &Record,
809 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
810 BasicBlock *ConstExprInsertBB) {
811 if (Slot ==
Record.size())
816 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
819 if (Slot ==
Record.size())
821 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
829 bool popValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
830 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
831 BasicBlock *ConstExprInsertBB) {
832 if (
getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
840 bool getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
841 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
842 BasicBlock *ConstExprInsertBB) {
843 ResVal =
getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
844 return ResVal ==
nullptr;
849 Value *
getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
850 unsigned InstNum,
Type *Ty,
unsigned TyID,
851 BasicBlock *ConstExprInsertBB) {
852 if (Slot ==
Record.size())
return nullptr;
853 unsigned ValNo = (unsigned)Record[Slot];
856 ValNo = InstNum - ValNo;
857 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
861 Value *getValueSigned(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
862 unsigned InstNum,
Type *Ty,
unsigned TyID,
863 BasicBlock *ConstExprInsertBB) {
864 if (Slot ==
Record.size())
return nullptr;
865 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
868 ValNo = InstNum - ValNo;
869 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
872 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
875 if (
Record.size() - OpNum < 2)
876 return error(
"Too few records for range");
878 unsigned LowerActiveWords =
Record[OpNum];
879 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
880 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
881 return error(
"Too few records for range");
884 OpNum += LowerActiveWords;
887 OpNum += UpperActiveWords;
890 int64_t
Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
891 int64_t
End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
892 return ConstantRange(APInt(
BitWidth, Start,
true),
897 Expected<ConstantRange>
898 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,
unsigned &OpNum) {
899 if (
Record.size() - OpNum < 1)
900 return error(
"Too few records for range");
902 return readConstantRange(Record, OpNum,
BitWidth);
906 const Triple &getTargetTriple() {
908 BitstreamCursor TripleStream(Stream.getBitcodeBytes());
909 if (Expected<std::string> TripleStr =
readTriple(TripleStream))
910 TargetTriple.emplace(std::move(*TripleStr));
913 TargetTriple.emplace();
916 return *TargetTriple;
922 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
928 Error parseAttrKind(
uint64_t Code, Attribute::AttrKind *Kind);
930 ParserCallbacks Callbacks = {});
932 Error parseComdatRecord(ArrayRef<uint64_t> Record);
933 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
934 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
935 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
936 ArrayRef<uint64_t> Record);
938 Error parseAttributeBlock();
939 Error parseAttributeGroupBlock();
940 Error parseTypeTable();
941 Error parseTypeTableBody();
942 Error parseOperandBundleTags();
943 Error parseSyncScopeNames();
945 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
946 unsigned NameIndex, Triple &TT);
947 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
Function *
F,
948 ArrayRef<uint64_t> Record);
950 Error parseGlobalValueSymbolTable();
951 Error parseConstants();
952 Error rememberAndSkipFunctionBodies();
953 Error rememberAndSkipFunctionBody();
955 Error rememberAndSkipMetadata();
958 Error globalCleanup();
960 void attachUpgradedGUIDMetadata(GlobalObject &GO);
961 Error resolveGlobalAndIndirectSymbolInits();
962 Error parseUseLists();
963 Error findFunctionInStream(
965 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
972class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
974 ModuleSummaryIndex &TheIndex;
978 bool SeenGlobalValSummary =
false;
981 bool SeenValueSymbolTable =
false;
995 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
996 ValueIdToValueInfoMap;
1002 DenseMap<uint64_t, StringRef> ModuleIdMap;
1005 std::string SourceFileName;
1009 StringRef ModulePath;
1013 std::function<bool(StringRef)> IsPrevailing =
nullptr;
1016 std::function<void(ValueInfo)> OnValueInfo =
nullptr;
1020 std::vector<uint64_t> StackIds;
1024 std::vector<uint64_t> RadixArray;
1029 std::vector<unsigned> StackIdToIndex;
1032 std::vector<uint64_t> DefinedGUIDs;
1035 ModuleSummaryIndexBitcodeReader(
1036 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
1037 StringRef ModulePath,
1038 std::function<
bool(StringRef)> IsPrevailing =
nullptr,
1039 std::function<
void(ValueInfo)> OnValueInfo =
nullptr);
1046 StringRef SourceFileName);
1047 Error parseValueSymbolTable(
1049 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1052 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1053 bool HasProfile,
bool HasRelBF);
1054 Error parseEntireSummary(
unsigned ID);
1055 Error parseModuleStringTable();
1056 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1057 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1059 std::vector<FunctionSummary::ParamAccess>
1060 parseParamAccesses(ArrayRef<uint64_t> Record);
1061 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1065 static constexpr unsigned UninitializedStackIdIndex =
1066 std::numeric_limits<unsigned>::max();
1068 unsigned getStackIdIndex(
unsigned LocalIndex) {
1069 unsigned &
Index = StackIdToIndex[LocalIndex];
1072 if (Index == UninitializedStackIdIndex)
1077 template <
bool AllowNullValueInfo = false>
1078 std::pair<ValueInfo, GlobalValue::GUID>
1079 getValueInfoFromValueId(
unsigned ValueId);
1081 void addThisModule();
1097 return std::error_code();
1103 : BitcodeReaderBase(
std::
move(Stream), Strtab),
1105 ValueList(this->Stream.SizeInBytes(),
1107 return materializeValue(
ValID, InsertBB);
1109 this->ProducerIdentification = std::string(ProducerIdentification);
1112Error BitcodeReader::materializeForwardReferencedFunctions() {
1113 if (WillMaterializeAllForwardRefs)
1117 WillMaterializeAllForwardRefs =
true;
1119 while (!BasicBlockFwdRefQueue.empty()) {
1120 Function *
F = BasicBlockFwdRefQueue.front();
1121 BasicBlockFwdRefQueue.pop_front();
1122 assert(
F &&
"Expected valid function");
1123 if (!BasicBlockFwdRefs.
count(
F))
1131 if (!
F->isMaterializable())
1132 return error(
"Never resolved function from blockaddress");
1135 if (
Error Err = materialize(
F))
1138 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1140 for (
Function *
F : BackwardRefFunctions)
1141 if (
Error Err = materialize(
F))
1143 BackwardRefFunctions.clear();
1146 WillMaterializeAllForwardRefs =
false;
1211 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1212 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1213 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1214 Flags.NoInline = (RawFlags >> 4) & 0x1;
1215 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1216 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1217 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1218 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1219 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1220 Flags.HasEscapingBlockAddress = (RawFlags >> 10) & 0x1;
1236 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1);
1237 RawFlags = RawFlags >> 4;
1238 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1242 bool Live = (RawFlags & 0x2) || Version < 3;
1243 bool Local = (RawFlags & 0x4);
1244 bool AutoHide = (RawFlags & 0x8);
1247 Live,
Local, AutoHide, IK,
1248 NoRenameOnPromotion);
1254 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1255 (RawFlags & 0x4) ?
true :
false,
1262 bool HasTailCall = (RawFlags & 0x8);
1263 bool HasIndirectCall = (RawFlags & 0x10);
1264 return CalleeInfo(Hotness, HasTailCall, HasIndirectCall);
1269 bool &HasTailCall) {
1270 static constexpr unsigned RelBlockFreqBits = 28;
1271 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1272 RelBF = RawFlags & RelBlockFreqMask;
1273 HasTailCall = (RawFlags & (1 << RelBlockFreqBits));
1298 case 0:
return false;
1299 case 1:
return true;
1361 bool IsFP = Ty->isFPOrFPVectorTy();
1363 if (!IsFP && !Ty->isIntOrIntVectorTy())
1370 return IsFP ? Instruction::FNeg : -1;
1375 bool IsFP = Ty->isFPOrFPVectorTy();
1377 if (!IsFP && !Ty->isIntOrIntVectorTy())
1384 return IsFP ? Instruction::FAdd : Instruction::Add;
1386 return IsFP ? Instruction::FSub : Instruction::Sub;
1388 return IsFP ? Instruction::FMul : Instruction::Mul;
1390 return IsFP ? -1 : Instruction::UDiv;
1392 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1394 return IsFP ? -1 : Instruction::URem;
1396 return IsFP ? Instruction::FRem : Instruction::SRem;
1398 return IsFP ? -1 : Instruction::Shl;
1400 return IsFP ? -1 : Instruction::LShr;
1402 return IsFP ? -1 : Instruction::AShr;
1404 return IsFP ? -1 : Instruction::And;
1406 return IsFP ? -1 : Instruction::Or;
1408 return IsFP ? -1 : Instruction::Xor;
1413 bool &IsElementwise) {
1511Type *BitcodeReader::getTypeByID(
unsigned ID) {
1513 if (ID >= TypeList.size())
1516 if (
Type *Ty = TypeList[ID])
1521 return TypeList[
ID] = createIdentifiedStructType(
Context);
1524unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1525 auto It = ContainedTypeIDs.
find(ID);
1526 if (It == ContainedTypeIDs.
end())
1527 return InvalidTypeID;
1529 if (Idx >= It->second.size())
1530 return InvalidTypeID;
1532 return It->second[
Idx];
1535Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1536 if (ID >= TypeList.size())
1543 return getTypeByID(getContainedTypeID(ID, 0));
1546unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1547 ArrayRef<unsigned> ChildTypeIDs) {
1548 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1549 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1550 auto It = VirtualTypeIDs.
find(CacheKey);
1551 if (It != VirtualTypeIDs.
end()) {
1557 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1558 "Incorrect cached contained type IDs");
1562 unsigned TypeID = TypeList.size();
1563 TypeList.push_back(Ty);
1564 if (!ChildTypeIDs.
empty())
1582 const BitcodeConstant *BC) {
1586 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1591 if (Opts.expand_constant_exprs)
1600 if (Opcode == Instruction::GetElementPtr)
1604 case Instruction::FNeg:
1605 case Instruction::Select:
1606 case Instruction::ICmp:
1607 case Instruction::FCmp:
1614Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1615 BasicBlock *InsertBB) {
1617 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1619 return ValueList[StartValID];
1621 SmallDenseMap<unsigned, Value *> MaterializedValues;
1622 SmallVector<unsigned> Worklist;
1624 while (!Worklist.
empty()) {
1625 unsigned ValID = Worklist.
back();
1626 if (MaterializedValues.
count(ValID)) {
1632 if (ValID >= ValueList.
size() || !ValueList[ValID])
1633 return error(
"Invalid value ID");
1635 Value *
V = ValueList[ValID];
1638 MaterializedValues.
insert({ValID,
V});
1646 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1647 auto It = MaterializedValues.
find(OpID);
1648 if (It != MaterializedValues.
end())
1649 Ops.push_back(It->second);
1656 if (
Ops.size() != BC->getOperandIDs().size())
1658 std::reverse(
Ops.begin(),
Ops.end());
1675 switch (BC->Opcode) {
1676 case BitcodeConstant::ConstantPtrAuthOpcode: {
1679 return error(
"ptrauth key operand must be ConstantInt");
1683 return error(
"ptrauth disc operand must be ConstantInt");
1686 ConstOps.
size() > 4 ? ConstOps[4]
1691 "ptrauth deactivation symbol operand must be a pointer");
1694 DeactivationSymbol);
1697 case BitcodeConstant::NoCFIOpcode: {
1700 return error(
"no_cfi operand must be GlobalValue");
1704 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1707 return error(
"dso_local operand must be GlobalValue");
1711 case BitcodeConstant::BlockAddressOpcode: {
1714 return error(
"blockaddress operand must be a function");
1719 unsigned BBID = BC->BlockAddressBB;
1722 return error(
"Invalid ID");
1725 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1727 return error(
"Invalid ID");
1734 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1736 BasicBlockFwdRefQueue.push_back(Fn);
1737 if (FwdBBs.size() < BBID + 1)
1738 FwdBBs.resize(BBID + 1);
1746 case BitcodeConstant::ConstantStructOpcode: {
1748 if (
ST->getNumElements() != ConstOps.
size())
1749 return error(
"Invalid number of elements in struct initializer");
1751 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1752 if (
Op->getType() != Ty)
1753 return error(
"Incorrect type in struct initializer");
1758 case BitcodeConstant::ConstantArrayOpcode: {
1760 if (AT->getNumElements() != ConstOps.
size())
1761 return error(
"Invalid number of elements in array initializer");
1763 for (Constant *
Op : ConstOps)
1764 if (
Op->getType() != AT->getElementType())
1765 return error(
"Incorrect type in array initializer");
1770 case BitcodeConstant::ConstantVectorOpcode: {
1772 if (VT->getNumElements() != ConstOps.size())
1773 return error(
"Invalid number of elements in vector initializer");
1775 for (Constant *
Op : ConstOps)
1776 if (
Op->getType() != VT->getElementType())
1777 return error(
"Incorrect type in vector initializer");
1782 case Instruction::GetElementPtr:
1785 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1789 case Instruction::ExtractElement:
1792 case Instruction::InsertElement:
1796 case Instruction::ShuffleVector: {
1797 SmallVector<int, 16>
Mask;
1809 MaterializedValues.
insert({ValID,
C});
1815 return error(Twine(
"Value referenced by initializer is an unsupported "
1816 "constant expression of type ") +
1817 BC->getOpcodeName());
1823 BC->getType(),
"constexpr", InsertBB);
1826 "constexpr", InsertBB);
1829 Ops[1],
"constexpr", InsertBB);
1832 I->setHasNoSignedWrap();
1834 I->setHasNoUnsignedWrap();
1840 switch (BC->Opcode) {
1841 case BitcodeConstant::ConstantVectorOpcode: {
1842 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1845 Value *
Idx = ConstantInt::get(IdxTy, Pair.index());
1852 case BitcodeConstant::ConstantStructOpcode:
1853 case BitcodeConstant::ConstantArrayOpcode: {
1857 "constexpr.ins", InsertBB);
1861 case Instruction::ICmp:
1862 case Instruction::FCmp:
1865 "constexpr", InsertBB);
1867 case Instruction::GetElementPtr:
1873 case Instruction::Select:
1876 case Instruction::ExtractElement:
1879 case Instruction::InsertElement:
1883 case Instruction::ShuffleVector:
1884 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1892 MaterializedValues.
insert({ValID,
I});
1896 return MaterializedValues[StartValID];
1899Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1900 Expected<Value *> MaybeV = materializeValue(ID,
nullptr);
1908StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1911 IdentifiedStructTypes.push_back(Ret);
1915StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1917 IdentifiedStructTypes.push_back(Ret);
1931 case Attribute::ZExt:
return 1 << 0;
1932 case Attribute::SExt:
return 1 << 1;
1933 case Attribute::NoReturn:
return 1 << 2;
1934 case Attribute::InReg:
return 1 << 3;
1935 case Attribute::StructRet:
return 1 << 4;
1936 case Attribute::NoUnwind:
return 1 << 5;
1937 case Attribute::NoAlias:
return 1 << 6;
1938 case Attribute::ByVal:
return 1 << 7;
1939 case Attribute::Nest:
return 1 << 8;
1940 case Attribute::ReadNone:
return 1 << 9;
1941 case Attribute::ReadOnly:
return 1 << 10;
1942 case Attribute::NoInline:
return 1 << 11;
1943 case Attribute::AlwaysInline:
return 1 << 12;
1944 case Attribute::OptimizeForSize:
return 1 << 13;
1945 case Attribute::StackProtect:
return 1 << 14;
1946 case Attribute::StackProtectReq:
return 1 << 15;
1947 case Attribute::Alignment:
return 31 << 16;
1949 case Attribute::NoRedZone:
return 1 << 22;
1950 case Attribute::NoImplicitFloat:
return 1 << 23;
1951 case Attribute::Naked:
return 1 << 24;
1952 case Attribute::InlineHint:
return 1 << 25;
1953 case Attribute::StackAlignment:
return 7 << 26;
1954 case Attribute::ReturnsTwice:
return 1 << 29;
1955 case Attribute::UWTable:
return 1 << 30;
1956 case Attribute::NonLazyBind:
return 1U << 31;
1957 case Attribute::SanitizeAddress:
return 1ULL << 32;
1958 case Attribute::MinSize:
return 1ULL << 33;
1959 case Attribute::NoDuplicate:
return 1ULL << 34;
1960 case Attribute::StackProtectStrong:
return 1ULL << 35;
1961 case Attribute::SanitizeThread:
return 1ULL << 36;
1962 case Attribute::SanitizeMemory:
return 1ULL << 37;
1963 case Attribute::NoBuiltin:
return 1ULL << 38;
1964 case Attribute::Returned:
return 1ULL << 39;
1965 case Attribute::Cold:
return 1ULL << 40;
1966 case Attribute::Builtin:
return 1ULL << 41;
1967 case Attribute::OptimizeNone:
return 1ULL << 42;
1968 case Attribute::InAlloca:
return 1ULL << 43;
1969 case Attribute::NonNull:
return 1ULL << 44;
1970 case Attribute::JumpTable:
return 1ULL << 45;
1971 case Attribute::Convergent:
return 1ULL << 46;
1972 case Attribute::SafeStack:
return 1ULL << 47;
1973 case Attribute::NoRecurse:
return 1ULL << 48;
1976 case Attribute::SwiftSelf:
return 1ULL << 51;
1977 case Attribute::SwiftError:
return 1ULL << 52;
1978 case Attribute::WriteOnly:
return 1ULL << 53;
1979 case Attribute::Speculatable:
return 1ULL << 54;
1980 case Attribute::StrictFP:
return 1ULL << 55;
1981 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1982 case Attribute::NoCfCheck:
return 1ULL << 57;
1983 case Attribute::OptForFuzzing:
return 1ULL << 58;
1984 case Attribute::ShadowCallStack:
return 1ULL << 59;
1985 case Attribute::SpeculativeLoadHardening:
1987 case Attribute::ImmArg:
1989 case Attribute::WillReturn:
1991 case Attribute::NoFree:
2007 if (
I == Attribute::Alignment)
2008 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
2009 else if (
I == Attribute::StackAlignment)
2010 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
2012 B.addTypeAttr(
I,
nullptr);
2026 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
2028 "Alignment must be a power of two.");
2031 B.addAlignmentAttr(Alignment);
2033 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
2034 (EncodedAttrs & 0xffff);
2036 if (AttrIdx == AttributeList::FunctionIndex) {
2039 if (Attrs & (1ULL << 9)) {
2041 Attrs &= ~(1ULL << 9);
2044 if (Attrs & (1ULL << 10)) {
2046 Attrs &= ~(1ULL << 10);
2049 if (Attrs & (1ULL << 49)) {
2051 Attrs &= ~(1ULL << 49);
2054 if (Attrs & (1ULL << 50)) {
2056 Attrs &= ~(1ULL << 50);
2059 if (Attrs & (1ULL << 53)) {
2061 Attrs &= ~(1ULL << 53);
2065 B.addMemoryAttr(ME);
2069 if (Attrs & (1ULL << 21)) {
2070 Attrs &= ~(1ULL << 21);
2077Error BitcodeReader::parseAttributeBlock() {
2081 if (!MAttributes.empty())
2082 return error(
"Invalid multiple blocks");
2084 SmallVector<uint64_t, 64>
Record;
2093 BitstreamEntry
Entry = MaybeEntry.
get();
2095 switch (
Entry.Kind) {
2098 return error(
"Malformed block");
2111 switch (MaybeRecord.
get()) {
2117 return error(
"Invalid parameter attribute record");
2119 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2125 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2130 Attrs.push_back(MAttributeGroups[Val]);
2132 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2145 return Attribute::Alignment;
2147 return Attribute::AlwaysInline;
2149 return Attribute::Builtin;
2151 return Attribute::ByVal;
2153 return Attribute::InAlloca;
2155 return Attribute::Cold;
2157 return Attribute::Convergent;
2159 return Attribute::DisableSanitizerInstrumentation;
2161 return Attribute::ElementType;
2163 return Attribute::FnRetThunkExtern;
2165 return Attribute::Flatten;
2167 return Attribute::HybridPatchable;
2169 return Attribute::InlineHint;
2171 return Attribute::InReg;
2173 return Attribute::JumpTable;
2175 return Attribute::Memory;
2177 return Attribute::NoFPClass;
2179 return Attribute::MinSize;
2181 return Attribute::Naked;
2183 return Attribute::Nest;
2185 return Attribute::NoAlias;
2187 return Attribute::NoBuiltin;
2189 return Attribute::NoCallback;
2191 return Attribute::NoDivergenceSource;
2193 return Attribute::AlwaysUniform;
2195 return Attribute::NoDuplicate;
2197 return Attribute::NoFree;
2199 return Attribute::NoFreeObj;
2201 return Attribute::NoImplicitFloat;
2203 return Attribute::NoInline;
2205 return Attribute::NoRecurse;
2207 return Attribute::NoMerge;
2209 return Attribute::NonLazyBind;
2211 return Attribute::NonNull;
2213 return Attribute::Dereferenceable;
2215 return Attribute::DereferenceableOrNull;
2217 return Attribute::AllocAlign;
2219 return Attribute::AllocKind;
2221 return Attribute::AllocSize;
2223 return Attribute::AllocatedPointer;
2225 return Attribute::NoRedZone;
2227 return Attribute::NoReturn;
2229 return Attribute::NoSync;
2231 return Attribute::NoCfCheck;
2233 return Attribute::NoProfile;
2235 return Attribute::SkipProfile;
2237 return Attribute::NoUnwind;
2239 return Attribute::NoSanitizeBounds;
2241 return Attribute::NoSanitizeCoverage;
2243 return Attribute::NullPointerIsValid;
2245 return Attribute::OptimizeForDebugging;
2247 return Attribute::OptForFuzzing;
2249 return Attribute::OptimizeForSize;
2251 return Attribute::OptimizeNone;
2253 return Attribute::ReadNone;
2255 return Attribute::ReadOnly;
2257 return Attribute::Returned;
2259 return Attribute::ReturnsTwice;
2261 return Attribute::SExt;
2263 return Attribute::Speculatable;
2265 return Attribute::StackAlignment;
2267 return Attribute::StackProtect;
2269 return Attribute::StackProtectReq;
2271 return Attribute::StackProtectStrong;
2273 return Attribute::SafeStack;
2275 return Attribute::ShadowCallStack;
2277 return Attribute::StrictFP;
2279 return Attribute::StructRet;
2281 return Attribute::SanitizeAddress;
2283 return Attribute::SanitizeHWAddress;
2285 return Attribute::SanitizeThread;
2287 return Attribute::SanitizeConcurrency;
2289 return Attribute::SanitizeType;
2291 return Attribute::SanitizeMemory;
2293 return Attribute::SanitizeNumericalStability;
2295 return Attribute::SanitizeRealtime;
2297 return Attribute::SanitizeRealtimeBlocking;
2299 return Attribute::SanitizeAllocToken;
2301 return Attribute::SpeculativeLoadHardening;
2303 return Attribute::SwiftError;
2305 return Attribute::SwiftSelf;
2307 return Attribute::SwiftAsync;
2309 return Attribute::UWTable;
2311 return Attribute::VScaleRange;
2313 return Attribute::WillReturn;
2315 return Attribute::WriteOnly;
2317 return Attribute::ZExt;
2319 return Attribute::ImmArg;
2321 return Attribute::SanitizeMemTag;
2323 return Attribute::Preallocated;
2325 return Attribute::NoUndef;
2327 return Attribute::ByRef;
2329 return Attribute::MustProgress;
2331 return Attribute::Hot;
2333 return Attribute::PresplitCoroutine;
2335 return Attribute::Writable;
2337 return Attribute::CoroDestroyOnlyWhenComplete;
2339 return Attribute::DeadOnUnwind;
2341 return Attribute::Range;
2343 return Attribute::Initializes;
2345 return Attribute::CoroElideSafe;
2347 return Attribute::NoExt;
2349 return Attribute::Captures;
2351 return Attribute::DeadOnReturn;
2353 return Attribute::NoCreateUndefOrPoison;
2355 return Attribute::DenormalFPEnv;
2357 return Attribute::NoOutline;
2359 return Attribute::NoIPA;
2361 return Attribute::LikelyModuleLocal;
2366 MaybeAlign &Alignment) {
2369 if (
Exponent > Value::MaxAlignmentExponent + 1)
2370 return error(
"Invalid alignment value");
2375Error BitcodeReader::parseAttrKind(
uint64_t Code, Attribute::AttrKind *Kind) {
2377 if (*Kind == Attribute::None)
2378 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2383 switch (EncodedKind) {
2407Error BitcodeReader::parseAttributeGroupBlock() {
2411 if (!MAttributeGroups.empty())
2412 return error(
"Invalid multiple blocks");
2414 SmallVector<uint64_t, 64>
Record;
2421 BitstreamEntry
Entry = MaybeEntry.
get();
2423 switch (
Entry.Kind) {
2426 return error(
"Malformed block");
2439 switch (MaybeRecord.
get()) {
2444 return error(
"Invalid grp record");
2451 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2452 if (Record[i] == 0) {
2453 Attribute::AttrKind
Kind;
2455 if (Idx == AttributeList::FunctionIndex &&
2464 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2470 if (Kind == Attribute::ByVal)
2471 B.addByValAttr(
nullptr);
2472 else if (Kind == Attribute::StructRet)
2473 B.addStructRetAttr(
nullptr);
2474 else if (Kind == Attribute::InAlloca)
2475 B.addInAllocaAttr(
nullptr);
2476 else if (Kind == Attribute::UWTable)
2477 B.addUWTableAttr(UWTableKind::Default);
2478 else if (Kind == Attribute::DeadOnReturn)
2479 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2480 else if (Attribute::isEnumAttrKind(Kind))
2481 B.addAttribute(Kind);
2483 return error(
"Not an enum attribute");
2484 }
else if (Record[i] == 1) {
2485 Attribute::AttrKind
Kind;
2486 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2488 if (!Attribute::isIntAttrKind(Kind))
2489 return error(
"Not an int attribute");
2490 if (Kind == Attribute::Alignment)
2491 B.addAlignmentAttr(Record[++i]);
2492 else if (Kind == Attribute::StackAlignment)
2493 B.addStackAlignmentAttr(Record[++i]);
2494 else if (Kind == Attribute::Dereferenceable)
2495 B.addDereferenceableAttr(Record[++i]);
2496 else if (Kind == Attribute::DereferenceableOrNull)
2497 B.addDereferenceableOrNullAttr(Record[++i]);
2498 else if (Kind == Attribute::DeadOnReturn)
2499 B.addDeadOnReturnAttr(
2501 else if (Kind == Attribute::AllocSize)
2502 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2503 else if (Kind == Attribute::VScaleRange)
2504 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2505 else if (Kind == Attribute::UWTable)
2507 else if (Kind == Attribute::AllocKind)
2508 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2509 else if (Kind == Attribute::Memory) {
2511 const uint8_t
Version = (EncodedME >> 56);
2525 if (getTargetTriple().isAArch64())
2530 B.addMemoryAttr(ME);
2535 EncodedME & 0x00FFFFFFFFFFFFFFULL);
2538 if (
Version == 1 && getTargetTriple().isAArch64())
2540 IRMemLocation::TargetMem0,
2541 ME.
getModRef(IRMemLocation::InaccessibleMem)) |
2543 IRMemLocation::TargetMem1,
2544 ME.
getModRef(IRMemLocation::InaccessibleMem));
2545 B.addMemoryAttr(ME);
2547 }
else if (Kind == Attribute::Captures)
2549 else if (Kind == Attribute::NoFPClass)
2552 else if (Kind == Attribute::DenormalFPEnv) {
2553 B.addDenormalFPEnvAttr(
2556 }
else if (Record[i] == 3 || Record[i] == 4) {
2558 SmallString<64> KindStr;
2559 SmallString<64> ValStr;
2561 while (Record[i] != 0 && i != e)
2563 assert(Record[i] == 0 &&
"Kind string not null terminated");
2568 while (Record[i] != 0 && i != e)
2570 assert(Record[i] == 0 &&
"Value string not null terminated");
2573 B.addAttribute(KindStr.
str(), ValStr.
str());
2574 }
else if (Record[i] == 5 || Record[i] == 6) {
2575 bool HasType =
Record[i] == 6;
2576 Attribute::AttrKind
Kind;
2577 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2579 if (!Attribute::isTypeAttrKind(Kind))
2580 return error(
"Not a type attribute");
2582 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2583 }
else if (Record[i] == 7) {
2584 Attribute::AttrKind
Kind;
2587 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2589 if (!Attribute::isConstantRangeAttrKind(Kind))
2590 return error(
"Not a ConstantRange attribute");
2592 Expected<ConstantRange> MaybeCR =
2593 readBitWidthAndConstantRange(Record, i);
2598 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2599 }
else if (Record[i] == 8) {
2600 Attribute::AttrKind
Kind;
2603 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2605 if (!Attribute::isConstantRangeListAttrKind(Kind))
2606 return error(
"Not a constant range list attribute");
2610 return error(
"Too few records for constant range list");
2611 unsigned RangeSize =
Record[i++];
2613 for (
unsigned Idx = 0;
Idx < RangeSize; ++
Idx) {
2614 Expected<ConstantRange> MaybeCR =
2615 readConstantRange(Record, i,
BitWidth);
2623 return error(
"Invalid (unordered or overlapping) range list");
2624 B.addConstantRangeListAttr(Kind, Val);
2626 return error(
"Invalid attribute group entry");
2631 B.addMemoryAttr(ME);
2634 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2641Error BitcodeReader::parseTypeTable() {
2645 return parseTypeTableBody();
2648Error BitcodeReader::parseTypeTableBody() {
2649 if (!TypeList.empty())
2650 return error(
"Invalid multiple blocks");
2652 SmallVector<uint64_t, 64>
Record;
2653 unsigned NumRecords = 0;
2662 BitstreamEntry
Entry = MaybeEntry.
get();
2664 switch (
Entry.Kind) {
2667 return error(
"Malformed block");
2669 if (NumRecords != TypeList.size())
2670 return error(
"Malformed block");
2679 Type *ResultTy =
nullptr;
2680 SmallVector<unsigned> ContainedIDs;
2684 switch (MaybeRecord.
get()) {
2686 return error(
"Invalid value");
2691 return error(
"Invalid numentry record");
2692 TypeList.resize(Record[0]);
2695 ResultTy = Type::getVoidTy(
Context);
2698 ResultTy = Type::getHalfTy(
Context);
2701 ResultTy = Type::getBFloatTy(
Context);
2704 ResultTy = Type::getFloatTy(
Context);
2707 ResultTy = Type::getDoubleTy(
Context);
2710 ResultTy = Type::getX86_FP80Ty(
Context);
2713 ResultTy = Type::getFP128Ty(
Context);
2716 ResultTy = Type::getPPC_FP128Ty(
Context);
2719 ResultTy = Type::getLabelTy(
Context);
2722 ResultTy = Type::getMetadataTy(
Context);
2730 ResultTy = Type::getX86_AMXTy(
Context);
2733 ResultTy = Type::getTokenTy(
Context);
2737 return error(
"Invalid record");
2742 return error(
"Bitwidth for byte type out of range");
2748 return error(
"Invalid integer record");
2753 return error(
"Bitwidth for integer type out of range");
2760 return error(
"Invalid pointer record");
2764 ResultTy = getTypeByID(Record[0]);
2766 !PointerType::isValidElementType(ResultTy))
2767 return error(
"Invalid type");
2774 return error(
"Invalid opaque pointer record");
2783 return error(
"Invalid function record");
2785 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2786 if (
Type *
T = getTypeByID(Record[i]))
2792 ResultTy = getTypeByID(Record[2]);
2793 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2794 return error(
"Invalid type");
2797 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2803 return error(
"Invalid function record");
2805 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2806 if (
Type *
T = getTypeByID(Record[i])) {
2807 if (!FunctionType::isValidArgumentType(
T))
2808 return error(
"Invalid function argument type");
2815 ResultTy = getTypeByID(Record[1]);
2816 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2817 return error(
"Invalid type");
2820 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2825 return error(
"Invalid anon struct record");
2827 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2828 if (
Type *
T = getTypeByID(Record[i]))
2834 return error(
"Invalid type");
2841 return error(
"Invalid struct name record");
2846 return error(
"Invalid named struct record");
2848 if (NumRecords >= TypeList.size())
2849 return error(
"Invalid TYPE table");
2855 TypeList[NumRecords] =
nullptr;
2857 Res = createIdentifiedStructType(
Context, TypeName);
2861 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2862 if (
Type *
T = getTypeByID(Record[i]))
2868 return error(
"Invalid named struct record");
2877 return error(
"Invalid opaque type record");
2879 if (NumRecords >= TypeList.size())
2880 return error(
"Invalid TYPE table");
2886 TypeList[NumRecords] =
nullptr;
2888 Res = createIdentifiedStructType(
Context, TypeName);
2895 return error(
"Invalid target extension type record");
2897 if (NumRecords >= TypeList.size())
2898 return error(
"Invalid TYPE table");
2900 if (Record[0] >=
Record.size())
2901 return error(
"Too many type parameters");
2903 unsigned NumTys =
Record[0];
2905 SmallVector<unsigned, 8> IntParams;
2906 for (
unsigned i = 0; i < NumTys; i++) {
2907 if (
Type *
T = getTypeByID(Record[i + 1]))
2910 return error(
"Invalid type");
2913 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2914 if (Record[i] > UINT_MAX)
2915 return error(
"Integer parameter too large");
2920 if (
auto E = TTy.takeError())
2928 return error(
"Invalid array type record");
2929 ResultTy = getTypeByID(Record[1]);
2930 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2931 return error(
"Invalid type");
2933 ResultTy = ArrayType::get(ResultTy, Record[0]);
2938 return error(
"Invalid vector type record");
2940 return error(
"Invalid vector length");
2941 ResultTy = getTypeByID(Record[1]);
2942 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2943 return error(
"Invalid type");
2946 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2950 if (NumRecords >= TypeList.size())
2951 return error(
"Invalid TYPE table");
2952 if (TypeList[NumRecords])
2954 "Invalid TYPE table: Only named structs can be forward referenced");
2955 assert(ResultTy &&
"Didn't read a type?");
2956 TypeList[NumRecords] = ResultTy;
2957 if (!ContainedIDs.
empty())
2958 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2963Error BitcodeReader::parseOperandBundleTags() {
2967 if (!BundleTags.empty())
2968 return error(
"Invalid multiple blocks");
2970 SmallVector<uint64_t, 64>
Record;
2976 BitstreamEntry
Entry = MaybeEntry.
get();
2978 switch (
Entry.Kind) {
2981 return error(
"Malformed block");
2995 return error(
"Invalid operand bundle record");
2998 BundleTags.emplace_back();
3000 return error(
"Invalid operand bundle record");
3005Error BitcodeReader::parseSyncScopeNames() {
3010 return error(
"Invalid multiple synchronization scope names blocks");
3012 SmallVector<uint64_t, 64>
Record;
3017 BitstreamEntry
Entry = MaybeEntry.
get();
3019 switch (
Entry.Kind) {
3022 return error(
"Malformed block");
3025 return error(
"Invalid empty synchronization scope names block");
3039 return error(
"Invalid sync scope record");
3041 SmallString<16> SSN;
3043 return error(
"Invalid sync scope record");
3051Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
3052 unsigned NameIndex, Triple &TT) {
3055 return error(
"Invalid record");
3056 unsigned ValueID =
Record[0];
3057 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3058 return error(
"Invalid record");
3059 Value *
V = ValueList[ValueID];
3062 if (NameStr.contains(0))
3063 return error(
"Invalid value name");
3064 V->setName(NameStr);
3066 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
3079 return std::move(JumpFailed);
3085 return error(
"Expected value symbol table subblock");
3089void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
3091 ArrayRef<uint64_t> Record) {
3096 uint64_t FuncBitOffset = FuncWordOffset * 32;
3097 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3101 if (FuncBitOffset > LastFunctionBlockBit)
3102 LastFunctionBlockBit = FuncBitOffset;
3106Error BitcodeReader::parseGlobalValueSymbolTable() {
3107 unsigned FuncBitcodeOffsetDelta =
3113 SmallVector<uint64_t, 64>
Record;
3118 BitstreamEntry
Entry = MaybeEntry.
get();
3120 switch (
Entry.Kind) {
3123 return error(
"Malformed block");
3134 switch (MaybeRecord.
get()) {
3136 unsigned ValueID =
Record[0];
3137 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3138 return error(
"Invalid value reference in symbol table");
3139 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3156 if (!MaybeCurrentBit)
3158 CurrentBit = MaybeCurrentBit.
get();
3161 if (
Error Err = parseGlobalValueSymbolTable())
3182 unsigned FuncBitcodeOffsetDelta =
3188 SmallVector<uint64_t, 64>
Record;
3199 BitstreamEntry
Entry = MaybeEntry.
get();
3201 switch (
Entry.Kind) {
3204 return error(
"Malformed block");
3220 switch (MaybeRecord.
get()) {
3224 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3232 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3240 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3245 return error(
"Invalid bbentry record");
3248 return error(
"Invalid bbentry record");
3270Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3271 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3272 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3273 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3275 GlobalInitWorklist.swap(GlobalInits);
3276 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3277 FunctionOperandWorklist.swap(FunctionOperands);
3279 while (!GlobalInitWorklist.empty()) {
3280 unsigned ValID = GlobalInitWorklist.back().second;
3281 if (ValID >= ValueList.
size()) {
3283 GlobalInits.push_back(GlobalInitWorklist.back());
3285 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3288 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3290 GlobalInitWorklist.pop_back();
3293 while (!IndirectSymbolInitWorklist.empty()) {
3294 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3295 if (ValID >= ValueList.
size()) {
3296 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3298 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3302 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3305 return error(
"Alias and aliasee types don't match");
3310 return error(
"Expected an alias or an ifunc");
3313 IndirectSymbolInitWorklist.pop_back();
3316 while (!FunctionOperandWorklist.empty()) {
3317 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3318 if (
Info.PersonalityFn) {
3319 unsigned ValID =
Info.PersonalityFn - 1;
3320 if (ValID < ValueList.
size()) {
3321 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3324 Info.F->setPersonalityFn(MaybeC.
get());
3325 Info.PersonalityFn = 0;
3329 unsigned ValID =
Info.Prefix - 1;
3330 if (ValID < ValueList.
size()) {
3331 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3334 Info.F->setPrefixData(MaybeC.
get());
3338 if (
Info.Prologue) {
3339 unsigned ValID =
Info.Prologue - 1;
3340 if (ValID < ValueList.
size()) {
3341 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3344 Info.F->setPrologueData(MaybeC.
get());
3348 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3349 FunctionOperands.push_back(Info);
3350 FunctionOperandWorklist.pop_back();
3359 BitcodeReader::decodeSignRotatedValue);
3361 return APInt(TypeBits, Words);
3364Error BitcodeReader::parseConstants() {
3372 unsigned Int32TyID = getVirtualTypeID(CurTy);
3373 unsigned CurTyID = Int32TyID;
3374 Type *CurElemTy =
nullptr;
3375 unsigned NextCstNo = ValueList.
size();
3383 switch (Entry.Kind) {
3386 return error(
"Malformed block");
3388 if (NextCstNo != ValueList.
size())
3389 return error(
"Invalid constant reference");
3400 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
3403 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3413 return error(
"Invalid settype record");
3414 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3415 return error(
"Invalid settype record");
3416 if (TypeList[Record[0]] == VoidType)
3417 return error(
"Invalid constant type");
3419 CurTy = TypeList[CurTyID];
3420 CurElemTy = getPtrElementTypeByID(CurTyID);
3424 return error(
"Invalid type for a constant null value");
3427 return error(
"Invalid type for a constant null value");
3432 return error(
"Invalid integer const record");
3437 return error(
"Invalid wide integer const record");
3440 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3441 V = ConstantInt::get(CurTy, VInt);
3446 return error(
"Invalid byte const record");
3447 V = ConstantByte::get(CurTy, decodeSignRotatedValue(Record[0]),
3452 return error(
"Invalid wide byte const record");
3455 APInt VByte =
readWideAPInt(Record, ScalarTy->getBitWidth());
3456 V = ConstantByte::get(CurTy, VByte);
3461 return error(
"Invalid float const record");
3464 if (ScalarTy->isHalfTy())
3465 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3466 APInt(16, (uint16_t)Record[0])));
3467 else if (ScalarTy->isBFloatTy())
3468 V = ConstantFP::get(
3469 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3470 else if (ScalarTy->isFloatTy())
3471 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3472 APInt(32, (uint32_t)Record[0])));
3473 else if (ScalarTy->isDoubleTy())
3474 V = ConstantFP::get(
3475 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3476 else if (ScalarTy->isX86_FP80Ty()) {
3479 Rearrange[0] = (
Record[1] & 0xffffLL) | (Record[0] << 16);
3480 Rearrange[1] =
Record[0] >> 48;
3481 V = ConstantFP::get(
3482 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3483 }
else if (ScalarTy->isFP128Ty())
3484 V = ConstantFP::get(CurTy,
3485 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3486 else if (ScalarTy->isPPC_FP128Ty())
3487 V = ConstantFP::get(
3488 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3496 return error(
"Invalid aggregate record");
3498 SmallVector<unsigned, 16> Elts;
3502 V = BitcodeConstant::create(
3503 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3505 V = BitcodeConstant::create(
Alloc, CurTy,
3506 BitcodeConstant::ConstantArrayOpcode, Elts);
3508 V = BitcodeConstant::create(
3509 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3518 return error(
"Invalid string record");
3528 return error(
"Invalid data record");
3532 return error(
"Invalid type for value");
3535 SmallString<128> RawData;
3538 const char *Src =
reinterpret_cast<const char *
>(&Val);
3540 Src +=
sizeof(
uint64_t) - EltBytes;
3541 RawData.
append(Src, Src + EltBytes);
3546 : ConstantDataArray::getRaw(RawData.str(),
Record.
size(), EltTy);
3551 return error(
"Invalid unary op constexpr record");
3556 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3562 return error(
"Invalid binary op constexpr record");
3568 if (
Record.size() >= 4) {
3569 if (
Opc == Instruction::Add ||
3570 Opc == Instruction::Sub ||
3571 Opc == Instruction::Mul ||
3572 Opc == Instruction::Shl) {
3577 }
else if (
Opc == Instruction::SDiv ||
3578 Opc == Instruction::UDiv ||
3579 Opc == Instruction::LShr ||
3580 Opc == Instruction::AShr) {
3585 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3586 {(unsigned)Record[1], (
unsigned)
Record[2]});
3592 return error(
"Invalid cast constexpr record");
3597 unsigned OpTyID =
Record[1];
3598 Type *OpTy = getTypeByID(OpTyID);
3600 return error(
"Invalid cast constexpr record");
3601 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3613 return error(
"Constant GEP record must have at least two elements");
3615 Type *PointeeType =
nullptr;
3619 PointeeType = getTypeByID(Record[OpNum++]);
3622 std::optional<ConstantRange>
InRange;
3626 unsigned InRangeIndex =
Op >> 1;
3632 Expected<ConstantRange> MaybeInRange =
3633 readBitWidthAndConstantRange(Record, OpNum);
3642 SmallVector<unsigned, 16> Elts;
3643 unsigned BaseTypeID =
Record[OpNum];
3644 while (OpNum !=
Record.size()) {
3645 unsigned ElTyID =
Record[OpNum++];
3646 Type *ElTy = getTypeByID(ElTyID);
3648 return error(
"Invalid getelementptr constexpr record");
3652 if (Elts.
size() < 1)
3653 return error(
"Invalid gep with no operands");
3657 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3658 BaseType = getTypeByID(BaseTypeID);
3663 return error(
"GEP base operand must be pointer or vector of pointer");
3666 PointeeType = getPtrElementTypeByID(BaseTypeID);
3668 return error(
"Missing element type for old-style constant GEP");
3671 V = BitcodeConstant::create(
3673 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3679 return error(
"Invalid select constexpr record");
3681 V = BitcodeConstant::create(
3682 Alloc, CurTy, Instruction::Select,
3683 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3689 return error(
"Invalid extractelement constexpr record");
3690 unsigned OpTyID =
Record[0];
3694 return error(
"Invalid extractelement constexpr record");
3696 if (
Record.size() == 4) {
3697 unsigned IdxTyID =
Record[2];
3698 Type *IdxTy = getTypeByID(IdxTyID);
3700 return error(
"Invalid extractelement constexpr record");
3706 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3707 {(unsigned)Record[1], IdxRecord});
3713 if (
Record.size() < 3 || !OpTy)
3714 return error(
"Invalid insertelement constexpr record");
3716 if (
Record.size() == 4) {
3717 unsigned IdxTyID =
Record[2];
3718 Type *IdxTy = getTypeByID(IdxTyID);
3720 return error(
"Invalid insertelement constexpr record");
3726 V = BitcodeConstant::create(
3727 Alloc, CurTy, Instruction::InsertElement,
3728 {(unsigned)Record[0], (
unsigned)
Record[1], IdxRecord});
3733 if (
Record.size() < 3 || !OpTy)
3734 return error(
"Invalid shufflevector constexpr record");
3735 V = BitcodeConstant::create(
3736 Alloc, CurTy, Instruction::ShuffleVector,
3737 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3744 if (
Record.size() < 4 || !RTy || !OpTy)
3745 return error(
"Invalid shufflevector constexpr record");
3746 V = BitcodeConstant::create(
3747 Alloc, CurTy, Instruction::ShuffleVector,
3748 {(unsigned)Record[1], (
unsigned)
Record[2], (unsigned)Record[3]});
3753 return error(
"Invalid cmp constexpt record");
3754 unsigned OpTyID =
Record[0];
3755 Type *OpTy = getTypeByID(OpTyID);
3757 return error(
"Invalid cmp constexpr record");
3758 V = BitcodeConstant::create(
3761 : Instruction::ICmp),
3762 (uint8_t)Record[3]},
3763 {(unsigned)Record[1], (
unsigned)
Record[2]});
3770 return error(
"Invalid inlineasm record");
3771 std::string AsmStr, ConstrStr;
3772 bool HasSideEffects =
Record[0] & 1;
3773 bool IsAlignStack =
Record[0] >> 1;
3774 unsigned AsmStrSize =
Record[1];
3775 if (2+AsmStrSize >=
Record.size())
3776 return error(
"Invalid inlineasm record");
3777 unsigned ConstStrSize =
Record[2+AsmStrSize];
3778 if (3+AsmStrSize+ConstStrSize >
Record.size())
3779 return error(
"Invalid inlineasm record");
3781 for (
unsigned i = 0; i != AsmStrSize; ++i)
3782 AsmStr += (
char)
Record[2+i];
3783 for (
unsigned i = 0; i != ConstStrSize; ++i)
3784 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3787 return error(
"Missing element type for old-style inlineasm");
3789 HasSideEffects, IsAlignStack);
3796 return error(
"Invalid inlineasm record");
3797 std::string AsmStr, ConstrStr;
3798 bool HasSideEffects =
Record[0] & 1;
3799 bool IsAlignStack = (
Record[0] >> 1) & 1;
3800 unsigned AsmDialect =
Record[0] >> 2;
3801 unsigned AsmStrSize =
Record[1];
3802 if (2+AsmStrSize >=
Record.size())
3803 return error(
"Invalid inlineasm record");
3804 unsigned ConstStrSize =
Record[2+AsmStrSize];
3805 if (3+AsmStrSize+ConstStrSize >
Record.size())
3806 return error(
"Invalid inlineasm record");
3808 for (
unsigned i = 0; i != AsmStrSize; ++i)
3809 AsmStr += (
char)
Record[2+i];
3810 for (
unsigned i = 0; i != ConstStrSize; ++i)
3811 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3814 return error(
"Missing element type for old-style inlineasm");
3816 HasSideEffects, IsAlignStack,
3823 return error(
"Invalid inlineasm record");
3825 std::string AsmStr, ConstrStr;
3826 bool HasSideEffects =
Record[OpNum] & 1;
3827 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3828 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3829 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3831 unsigned AsmStrSize =
Record[OpNum];
3833 if (OpNum + AsmStrSize >=
Record.size())
3834 return error(
"Invalid inlineasm record");
3835 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3836 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3837 return error(
"Invalid inlineasm record");
3839 for (
unsigned i = 0; i != AsmStrSize; ++i)
3840 AsmStr += (
char)
Record[OpNum + i];
3842 for (
unsigned i = 0; i != ConstStrSize; ++i)
3843 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3846 return error(
"Missing element type for old-style inlineasm");
3848 HasSideEffects, IsAlignStack,
3855 return error(
"Invalid inlineasm record");
3860 return error(
"Invalid inlineasm record");
3861 std::string AsmStr, ConstrStr;
3862 bool HasSideEffects =
Record[OpNum] & 1;
3863 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3864 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3865 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3867 unsigned AsmStrSize =
Record[OpNum];
3869 if (OpNum + AsmStrSize >=
Record.size())
3870 return error(
"Invalid inlineasm record");
3871 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3872 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3873 return error(
"Invalid inlineasm record");
3875 for (
unsigned i = 0; i != AsmStrSize; ++i)
3876 AsmStr += (
char)
Record[OpNum + i];
3878 for (
unsigned i = 0; i != ConstStrSize; ++i)
3879 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3881 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3887 return error(
"Invalid blockaddress record");
3888 unsigned FnTyID =
Record[0];
3889 Type *FnTy = getTypeByID(FnTyID);
3891 return error(
"Invalid blockaddress record");
3892 V = BitcodeConstant::create(
3894 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3900 return error(
"Invalid dso_local record");
3901 unsigned GVTyID =
Record[0];
3902 Type *GVTy = getTypeByID(GVTyID);
3904 return error(
"Invalid dso_local record");
3905 V = BitcodeConstant::create(
3906 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3911 return error(
"Invalid no_cfi record");
3912 unsigned GVTyID =
Record[0];
3913 Type *GVTy = getTypeByID(GVTyID);
3915 return error(
"Invalid no_cfi record");
3916 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3922 return error(
"Invalid ptrauth record");
3924 V = BitcodeConstant::create(
Alloc, CurTy,
3925 BitcodeConstant::ConstantPtrAuthOpcode,
3926 {(unsigned)Record[0], (
unsigned)
Record[1],
3927 (unsigned)Record[2], (
unsigned)
Record[3]});
3932 return error(
"Invalid ptrauth record");
3934 V = BitcodeConstant::create(
3935 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3936 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2],
3937 (
unsigned)
Record[3], (unsigned)Record[4]});
3942 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3949Error BitcodeReader::parseUseLists() {
3954 SmallVector<uint64_t, 64>
Record;
3960 BitstreamEntry
Entry = MaybeEntry.
get();
3962 switch (
Entry.Kind) {
3965 return error(
"Malformed block");
3979 switch (MaybeRecord.
get()) {
3987 if (RecordLength < 3)
3989 return error(
"Invalid uselist record");
3990 unsigned ID =
Record.pop_back_val();
3994 assert(ID < FunctionBBs.size() &&
"Basic block not found");
3995 V = FunctionBBs[
ID];
3999 if (!
V->hasUseList())
4002 unsigned NumUses = 0;
4003 SmallDenseMap<const Use *, unsigned, 16> Order;
4004 for (
const Use &U :
V->materialized_uses()) {
4005 if (++NumUses >
Record.size())
4007 Order[&
U] =
Record[NumUses - 1];
4014 V->sortUseList([&](
const Use &L,
const Use &R) {
4025Error BitcodeReader::rememberAndSkipMetadata() {
4028 DeferredMetadataInfo.push_back(CurBit);
4036Error BitcodeReader::materializeMetadata() {
4037 for (
uint64_t BitPos : DeferredMetadataInfo) {
4041 if (
Error Err = MDLoader->parseModuleMetadata())
4050 NamedMDNode *LinkerOpts =
4052 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
4063 for (GlobalVariable &GV : TheModule->
globals())
4064 attachUpgradedGUIDMetadata(GV);
4066 DeferredMetadataInfo.clear();
4070void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
4074Error BitcodeReader::rememberAndSkipFunctionBody() {
4076 if (FunctionsWithBodies.empty())
4077 return error(
"Insufficient function protos");
4079 Function *Fn = FunctionsWithBodies.back();
4080 FunctionsWithBodies.pop_back();
4085 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4086 "Mismatch between VST and scanned function offsets");
4087 DeferredFunctionInfo[Fn] = CurBit;
4095Error BitcodeReader::globalCleanup() {
4097 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4099 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4100 return error(
"Malformed global initializer set");
4105 MDLoader->upgradeDebugIntrinsics(
F);
4109 !SkipDebugIntrinsicUpgrade))
4110 UpgradedIntrinsics[&
F] = NewFn;
4116 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4117 for (GlobalVariable &GV : TheModule->globals())
4119 UpgradedVariables.emplace_back(&GV, Upgraded);
4120 for (
auto &Pair : UpgradedVariables) {
4121 Pair.first->eraseFromParent();
4122 TheModule->insertGlobalVariable(Pair.second);
4125 for (
size_t ValueID = 0; ValueID < GUIDList.size(); ValueID++) {
4126 const auto GUID = GUIDList[ValueID];
4130 const auto *
Value = ValueList[ValueID];
4131 TheModule->insertGUID(
Value, GUID);
4140 if (!SeenGUIDList && !UpgradedGUIDs && (UseStrtab || SeenValueSymbolTable))
4145 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
4146 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4156void BitcodeReader::upgradeGUIDs() {
4157 assert(!SeenGUIDList && !UpgradedGUIDs);
4158 UpgradedGUIDs =
true;
4159 for (GlobalVariable &GV : TheModule->globals()) {
4164 for (
Function &
F : TheModule->functions()) {
4165 if (
F.isDeclaration())
4167 TheModule->insertGUID(&
F,
F.getGUIDOrFallback());
4176void BitcodeReader::attachUpgradedGUIDMetadata(GlobalObject &GO) {
4180 if (
auto GUID = TheModule->getGUID(&GO))
4182 LLVMContext::MD_guid,
4184 Type::getInt64Ty(
Context), *GUID))}));
4191Error BitcodeReader::rememberAndSkipFunctionBodies() {
4196 return error(
"Could not find function in stream");
4198 if (!SeenFirstFunctionBody)
4199 return error(
"Trying to materialize functions before seeing function blocks");
4203 assert(SeenValueSymbolTable);
4206 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4209 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4211 switch (
Entry.Kind) {
4213 return error(
"Expect SubBlock");
4217 return error(
"Expect function block");
4219 if (
Error Err = rememberAndSkipFunctionBody())
4228Error BitcodeReaderBase::readBlockInfo() {
4229 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4231 if (!MaybeNewBlockInfo)
4233 std::optional<BitstreamBlockInfo> NewBlockInfo =
4234 std::move(MaybeNewBlockInfo.
get());
4236 return error(
"Malformed block");
4237 BlockInfo = std::move(*NewBlockInfo);
4241Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4245 std::tie(Name, Record) = readNameFromStrtab(Record);
4248 return error(
"Invalid comdat record");
4250 std::string OldFormatName;
4253 return error(
"Invalid comdat record");
4254 unsigned ComdatNameSize =
Record[1];
4255 if (ComdatNameSize >
Record.size() - 2)
4256 return error(
"Comdat name size too large");
4257 OldFormatName.reserve(ComdatNameSize);
4258 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4259 OldFormatName += (
char)
Record[2 + i];
4260 Name = OldFormatName;
4262 Comdat *
C = TheModule->getOrInsertComdat(Name);
4263 C->setSelectionKind(SK);
4264 ComdatList.push_back(
C);
4278 Meta.NoAddress =
true;
4280 Meta.NoHWAddress =
true;
4284 Meta.IsDynInit =
true;
4288Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4296 std::tie(Name, Record) = readNameFromStrtab(Record);
4299 return error(
"Invalid global variable record");
4300 unsigned TyID =
Record[0];
4301 Type *Ty = getTypeByID(TyID);
4303 return error(
"Invalid global variable record");
4305 bool explicitType =
Record[1] & 2;
4311 return error(
"Invalid type for value");
4313 TyID = getContainedTypeID(TyID);
4314 Ty = getTypeByID(TyID);
4316 return error(
"Missing element type for old-style global");
4322 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4326 if (Record[5] - 1 >= SectionTable.size())
4327 return error(
"Invalid ID");
4336 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4344 bool ExternallyInitialized =
false;
4346 ExternallyInitialized =
Record[9];
4348 GlobalVariable *NewGV =
4358 if (
Record.size() > 10) {
4370 if (
unsigned InitID = Record[2])
4371 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4373 if (
Record.size() > 11) {
4374 if (
unsigned ComdatID = Record[11]) {
4375 if (ComdatID > ComdatList.size())
4376 return error(
"Invalid global variable comdat ID");
4377 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4380 ImplicitComdatObjects.
insert(NewGV);
4383 if (
Record.size() > 12) {
4388 if (
Record.size() > 13) {
4397 if (
Record.size() > 16 && Record[16]) {
4398 llvm::GlobalValue::SanitizerMetadata
Meta =
4403 if (
Record.size() > 17 && Record[17]) {
4407 return error(
"Invalid global variable code model");
4413void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4414 if (ValueTypeCallback) {
4415 (*ValueTypeCallback)(
4416 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4417 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4421Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4427 std::tie(Name, Record) = readNameFromStrtab(Record);
4430 return error(
"Invalid function record");
4431 unsigned FTyID =
Record[0];
4432 Type *FTy = getTypeByID(FTyID);
4434 return error(
"Invalid function record");
4436 FTyID = getContainedTypeID(FTyID, 0);
4437 FTy = getTypeByID(FTyID);
4439 return error(
"Missing element type for old-style function");
4443 return error(
"Invalid type for value");
4444 auto CC =
static_cast<CallingConv::ID
>(
Record[1]);
4445 if (
CC & ~CallingConv::MaxID)
4446 return error(
"Invalid calling convention ID");
4448 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4454 AddrSpace, Name, TheModule);
4457 "Incorrect fully specified type provided for function");
4458 FunctionTypeIDs[
Func] = FTyID;
4460 Func->setCallingConv(
CC);
4461 bool isProto =
Record[2];
4465 callValueTypeCallback(Func, FTyID);
4470 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4471 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4472 Attribute::InAlloca}) {
4473 if (!
Func->hasParamAttribute(i, Kind))
4476 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4479 Func->removeParamAttr(i, Kind);
4481 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4482 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4484 return error(
"Missing param element type for attribute upgrade");
4488 case Attribute::ByVal:
4489 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4491 case Attribute::StructRet:
4492 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4494 case Attribute::InAlloca:
4495 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4501 Func->addParamAttr(i, NewAttr);
4505 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4506 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4507 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4508 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4510 return error(
"Missing param element type for x86_intrcc upgrade");
4512 Func->addParamAttr(0, NewAttr);
4516 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4519 Func->setAlignment(*Alignment);
4521 if (Record[6] - 1 >= SectionTable.size())
4522 return error(
"Invalid ID");
4523 Func->setSection(SectionTable[Record[6] - 1]);
4527 if (!
Func->hasLocalLinkage())
4529 if (
Record.size() > 8 && Record[8]) {
4530 if (Record[8] - 1 >= GCTable.size())
4531 return error(
"Invalid ID");
4532 Func->setGC(GCTable[Record[8] - 1]);
4537 Func->setUnnamedAddr(UnnamedAddr);
4539 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4541 OperandInfo.Prologue =
Record[10];
4543 if (
Record.size() > 11) {
4545 if (!
Func->hasLocalLinkage()) {
4552 if (
Record.size() > 12) {
4553 if (
unsigned ComdatID = Record[12]) {
4554 if (ComdatID > ComdatList.size())
4555 return error(
"Invalid function comdat ID");
4556 Func->setComdat(ComdatList[ComdatID - 1]);
4559 ImplicitComdatObjects.
insert(Func);
4563 OperandInfo.Prefix =
Record[13];
4566 OperandInfo.PersonalityFn =
Record[14];
4568 if (
Record.size() > 15) {
4578 Record[17] + Record[18] <= Strtab.
size()) {
4579 Func->setPartition(StringRef(Strtab.
data() + Record[17], Record[18]));
4582 if (
Record.size() > 19) {
4583 MaybeAlign PrefAlignment;
4584 if (
Error Err = parseAlignmentValue(Record[19], PrefAlignment))
4586 Func->setPreferredAlignment(PrefAlignment);
4589 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4591 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4592 FunctionOperands.push_back(OperandInfo);
4597 Func->setIsMaterializable(
true);
4598 FunctionsWithBodies.push_back(Func);
4599 DeferredFunctionInfo[
Func] = 0;
4604Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4605 unsigned BitCode, ArrayRef<uint64_t> Record) {
4615 std::tie(Name, Record) = readNameFromStrtab(Record);
4618 if (
Record.size() < (3 + (
unsigned)NewRecord))
4619 return error(
"Invalid global indirect symbol record");
4624 return error(
"Invalid global indirect symbol record");
4630 return error(
"Invalid type for value");
4631 AddrSpace = PTy->getAddressSpace();
4633 Ty = getTypeByID(
TypeID);
4635 return error(
"Missing element type for old-style indirect symbol");
4637 AddrSpace =
Record[OpNum++];
4640 auto Val =
Record[OpNum++];
4649 nullptr, TheModule);
4653 if (OpNum !=
Record.size()) {
4654 auto VisInd = OpNum++;
4660 if (OpNum !=
Record.size()) {
4661 auto S =
Record[OpNum++];
4668 if (OpNum !=
Record.size())
4670 if (OpNum !=
Record.size())
4673 if (OpNum !=
Record.size())
4678 if (OpNum + 1 <
Record.size()) {
4680 if (Record[OpNum] + Record[OpNum + 1] > Strtab.
size())
4681 return error(
"Malformed partition, too large.");
4683 StringRef(Strtab.
data() + Record[OpNum], Record[OpNum + 1]));
4687 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4692 bool ShouldLazyLoadMetadata,
4693 ParserCallbacks Callbacks) {
4694 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4701 SmallVector<uint64_t, 64>
Record;
4705 bool ResolvedDataLayout =
false;
4710 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4713 Module::GlobalAsmProperties Props;
4715 auto ResolveDataLayout = [&]() ->
Error {
4716 if (ResolvedDataLayout)
4720 ResolvedDataLayout =
true;
4724 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4728 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4729 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4730 TentativeDataLayoutStr = *LayoutOverride;
4738 TheModule->setDataLayout(MaybeDL.
get());
4744 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4747 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4749 switch (
Entry.Kind) {
4751 return error(
"Malformed block");
4753 if (
Error Err = ResolveDataLayout())
4755 return globalCleanup();
4764 if (
Error Err = readBlockInfo())
4768 if (
Error Err = parseAttributeBlock())
4772 if (
Error Err = parseAttributeGroupBlock())
4776 if (
Error Err = parseTypeTable())
4780 if (!SeenValueSymbolTable) {
4786 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4787 if (
Error Err = parseValueSymbolTable())
4789 SeenValueSymbolTable =
true;
4799 if (
Error Err = parseConstants())
4801 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4805 if (ShouldLazyLoadMetadata) {
4806 if (
Error Err = rememberAndSkipMetadata())
4810 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4811 if (
Error Err = MDLoader->parseModuleMetadata())
4815 if (
Error Err = MDLoader->parseMetadataKinds())
4819 if (
Error Err = ResolveDataLayout())
4824 if (!SeenFirstFunctionBody) {
4825 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4826 if (
Error Err = globalCleanup())
4828 SeenFirstFunctionBody =
true;
4831 if (VSTOffset > 0) {
4835 if (!SeenValueSymbolTable) {
4836 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4838 SeenValueSymbolTable =
true;
4860 if (
Error Err = rememberAndSkipFunctionBody())
4867 if (SeenValueSymbolTable) {
4871 return globalCleanup();
4875 if (
Error Err = parseUseLists())
4879 if (
Error Err = parseOperandBundleTags())
4883 if (
Error Err = parseSyncScopeNames())
4895 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
4898 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4901 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4904 UseRelativeIDs = *VersionOrErr >= 1;
4908 if (ResolvedDataLayout)
4909 return error(
"target triple too late in module");
4912 return error(
"Invalid triple record");
4913 TheModule->setTargetTriple(Triple(std::move(S)));
4917 if (ResolvedDataLayout)
4918 return error(
"datalayout too late in module");
4920 return error(
"Invalid data layout record");
4926 return error(
"Invalid module asm record");
4927 size_t SepPos = Str.find(
'\0');
4928 if (SepPos == std::string::npos)
4929 return error(
"Invalid module asm record");
4930 if (!Props.
set(StringRef(Str.data(), SepPos), Str.substr(SepPos + 1)))
4931 return error(
"Unknown module asm property");
4937 return error(
"Invalid asm record");
4938 TheModule->appendModuleInlineAsm(Module::GlobalAsmFragment(S, Props));
4946 return error(
"Invalid deplib record");
4953 return error(
"Invalid section name record");
4954 SectionTable.push_back(S);
4960 return error(
"Invalid gcname record");
4961 GCTable.push_back(S);
4965 if (
Error Err = parseComdatRecord(Record))
4974 if (
Error Err = parseGlobalVarRecord(Record))
4978 if (
Error Err = ResolveDataLayout())
4980 if (
Error Err = parseFunctionRecord(Record))
4986 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4992 return error(
"Invalid vstoffset record");
4996 VSTOffset =
Record[0] - 1;
5001 SeenGUIDList =
true;
5002 GUIDList.reserve(GUIDList.size() +
Record.size() / 2);
5003 for (
size_t i = 0; i <
Record.size(); i += 2)
5004 GUIDList.push_back(Record[i] << 32 | Record[i + 1]);
5010 return error(
"Invalid source filename record");
5011 TheModule->setSourceFileName(
ValueName);
5017 this->ValueTypeCallback = std::nullopt;
5021Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
5023 ParserCallbacks Callbacks) {
5025 MetadataLoaderCallbacks MDCallbacks;
5026 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(ID); };
5028 return getContainedTypeID(
I, J);
5031 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
5033 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
5036Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
5038 return error(
"Load/Store operand is not a pointer type");
5039 if (!PointerType::isLoadableOrStorableType(ValType))
5040 return error(
"Cannot load/store from pointer");
5044Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
5045 ArrayRef<unsigned> ArgTyIDs) {
5047 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
5048 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
5049 Attribute::InAlloca}) {
5050 if (!
Attrs.hasParamAttr(i, Kind) ||
5051 Attrs.getParamAttr(i, Kind).getValueAsType())
5054 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
5056 return error(
"Missing element type for typed attribute upgrade");
5060 case Attribute::ByVal:
5061 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
5063 case Attribute::StructRet:
5064 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
5066 case Attribute::InAlloca:
5067 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
5080 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
5084 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
5085 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5087 return error(
"Missing element type for inline asm upgrade");
5090 Attribute::get(
Context, Attribute::ElementType, ElemTy));
5098 case Intrinsic::preserve_array_access_index:
5099 case Intrinsic::preserve_struct_access_index:
5100 case Intrinsic::aarch64_ldaxr:
5101 case Intrinsic::aarch64_ldxr:
5102 case Intrinsic::aarch64_stlxr:
5103 case Intrinsic::aarch64_stxr:
5104 case Intrinsic::arm_ldaex:
5105 case Intrinsic::arm_ldrex:
5106 case Intrinsic::arm_stlex:
5107 case Intrinsic::arm_strex: {
5110 case Intrinsic::aarch64_stlxr:
5111 case Intrinsic::aarch64_stxr:
5112 case Intrinsic::arm_stlex:
5113 case Intrinsic::arm_strex:
5120 if (!
Attrs.getParamElementType(ArgNo)) {
5121 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5123 return error(
"Missing element type for elementtype upgrade");
5143 if (MDLoader->hasFwdRefs())
5144 return error(
"Invalid function metadata: incoming forward references");
5146 InstructionList.
clear();
5147 unsigned ModuleValueListSize = ValueList.
size();
5148 unsigned ModuleMDLoaderSize = MDLoader->size();
5152 unsigned FTyID = FunctionTypeIDs[
F];
5153 for (Argument &
I :
F->args()) {
5154 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
5155 assert(
I.getType() == getTypeByID(ArgTyID) &&
5156 "Incorrect fully specified type for Function Argument");
5160 unsigned NextValueNo = ValueList.
size();
5162 unsigned CurBBNo = 0;
5167 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
5171 auto getLastInstruction = [&]() -> Instruction * {
5172 if (CurBB && !CurBB->
empty())
5173 return &CurBB->
back();
5174 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5175 !FunctionBBs[CurBBNo - 1]->
empty())
5176 return &FunctionBBs[CurBBNo - 1]->back();
5180 std::vector<OperandBundleDef> OperandBundles;
5183 SmallVector<uint64_t, 64>
Record;
5186 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
5189 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
5191 switch (
Entry.Kind) {
5193 return error(
"Malformed block");
5195 goto OutOfRecordLoop;
5204 if (
Error Err = parseConstants())
5206 NextValueNo = ValueList.
size();
5209 if (
Error Err = parseValueSymbolTable())
5213 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
5217 assert(DeferredMetadataInfo.empty() &&
5218 "Must read all module-level metadata before function-level");
5219 if (
Error Err = MDLoader->parseFunctionMetadata())
5223 if (
Error Err = parseUseLists())
5237 unsigned ResTypeID = InvalidTypeID;
5238 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
5241 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5243 return error(
"Invalid value");
5245 if (
Record.empty() || Record[0] == 0)
5246 return error(
"Invalid declareblocks record");
5248 FunctionBBs.resize(Record[0]);
5251 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5252 if (BBFRI == BasicBlockFwdRefs.
end()) {
5253 for (BasicBlock *&BB : FunctionBBs)
5256 auto &BBRefs = BBFRI->second;
5258 if (BBRefs.size() > FunctionBBs.size())
5259 return error(
"Invalid ID");
5260 assert(!BBRefs.empty() &&
"Unexpected empty array");
5261 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5262 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5264 if (
I < RE && BBRefs[
I]) {
5265 BBRefs[
I]->insertInto(
F);
5266 FunctionBBs[
I] = BBRefs[
I];
5272 BasicBlockFwdRefs.
erase(BBFRI);
5275 CurBB = FunctionBBs[0];
5282 return error(
"Invalid blockaddr users record");
5298 BackwardRefFunctions.push_back(
F);
5300 return error(
"Invalid blockaddr users record");
5307 I = getLastInstruction();
5310 return error(
"Invalid debug_loc_again record");
5311 I->setDebugLoc(LastLoc);
5316 I = getLastInstruction();
5318 return error(
"Invalid debug loc record");
5326 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5329 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5331 return error(
"Invalid debug loc record");
5335 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5337 return error(
"Invalid debug loc record");
5340 if (
Record.size() >= 8 && Record[7])
5341 IRLayers = MDLoader->getMetadataFwdRefOrLoad(Record[7] - 1);
5343 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5344 isImplicitCode, AtomGroup, AtomRank, IRLayers);
5345 I->setDebugLoc(LastLoc);
5353 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5355 return error(
"Invalid unary operator record");
5359 return error(
"Invalid unary operator record");
5363 if (OpNum <
Record.size()) {
5367 I->setFastMathFlags(FMF);
5376 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5380 return error(
"Invalid binary operator record");
5384 return error(
"Invalid binary operator record");
5388 if (OpNum <
Record.size()) {
5389 if (
Opc == Instruction::Add ||
5390 Opc == Instruction::Sub ||
5391 Opc == Instruction::Mul ||
5392 Opc == Instruction::Shl) {
5397 }
else if (
Opc == Instruction::SDiv ||
5398 Opc == Instruction::UDiv ||
5399 Opc == Instruction::LShr ||
5400 Opc == Instruction::AShr) {
5403 }
else if (
Opc == Instruction::Or) {
5409 I->setFastMathFlags(FMF);
5418 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5419 OpNum + 1 >
Record.size())
5420 return error(
"Invalid cast record");
5422 ResTypeID =
Record[OpNum++];
5423 Type *ResTy = getTypeByID(ResTypeID);
5426 if (
Opc == -1 || !ResTy)
5427 return error(
"Invalid cast record");
5432 assert(CurBB &&
"No current BB?");
5438 return error(
"Invalid cast");
5442 if (OpNum <
Record.size()) {
5443 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5446 }
else if (
Opc == Instruction::Trunc) {
5451 }
else if (
Opc == Instruction::AddrSpaceCast) {
5461 I->setFastMathFlags(FMF);
5480 Ty = getTypeByID(TyID);
5484 TyID = InvalidTypeID;
5489 unsigned BasePtrTypeID;
5490 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5492 return error(
"Invalid gep record");
5495 TyID = getContainedTypeID(BasePtrTypeID);
5496 if (
BasePtr->getType()->isVectorTy())
5497 TyID = getContainedTypeID(TyID);
5498 Ty = getTypeByID(TyID);
5501 SmallVector<Value*, 16> GEPIdx;
5502 while (OpNum !=
Record.size()) {
5505 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5506 return error(
"Invalid gep record");
5517 unsigned SubType = 0;
5518 if (GTI.isStruct()) {
5520 Idx->getType()->isVectorTy()
5525 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5532 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5533 if (
I->getType()->isVectorTy())
5534 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5537 GEP->setNoWrapFlags(NW);
5546 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5547 return error(
"Invalid extractvalue record");
5550 unsigned RecSize =
Record.size();
5551 if (OpNum == RecSize)
5552 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5554 SmallVector<unsigned, 4> EXTRACTVALIdx;
5555 ResTypeID = AggTypeID;
5556 for (; OpNum != RecSize; ++OpNum) {
5561 if (!IsStruct && !IsArray)
5562 return error(
"EXTRACTVAL: Invalid type");
5563 if ((
unsigned)Index != Index)
5564 return error(
"Invalid value");
5566 return error(
"EXTRACTVAL: Invalid struct index");
5568 return error(
"EXTRACTVAL: Invalid array index");
5569 EXTRACTVALIdx.
push_back((
unsigned)Index);
5573 ResTypeID = getContainedTypeID(ResTypeID, Index);
5576 ResTypeID = getContainedTypeID(ResTypeID);
5590 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5591 return error(
"Invalid insertvalue record");
5594 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5595 return error(
"Invalid insertvalue record");
5597 unsigned RecSize =
Record.size();
5598 if (OpNum == RecSize)
5599 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5601 SmallVector<unsigned, 4> INSERTVALIdx;
5603 for (; OpNum != RecSize; ++OpNum) {
5608 if (!IsStruct && !IsArray)
5609 return error(
"INSERTVAL: Invalid type");
5610 if ((
unsigned)Index != Index)
5611 return error(
"Invalid value");
5613 return error(
"INSERTVAL: Invalid struct index");
5615 return error(
"INSERTVAL: Invalid array index");
5617 INSERTVALIdx.
push_back((
unsigned)Index);
5625 return error(
"Inserted value type doesn't match aggregate type");
5628 ResTypeID = AggTypeID;
5640 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5642 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5644 popValue(Record, OpNum, NextValueNo, CondType,
5645 getVirtualTypeID(CondType),
Cond, CurBB))
5646 return error(
"Invalid select record");
5659 unsigned ValTypeID, CondTypeID;
5660 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5662 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5664 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5665 return error(
"Invalid vector select record");
5668 if (VectorType* vector_type =
5671 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5672 return error(
"Invalid type for value");
5676 return error(
"Invalid type for value");
5680 ResTypeID = ValTypeID;
5685 I->setFastMathFlags(FMF);
5693 unsigned VecTypeID, IdxTypeID;
5694 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5695 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5696 return error(
"Invalid extractelement record");
5698 return error(
"Invalid type for value");
5700 ResTypeID = getContainedTypeID(VecTypeID);
5708 unsigned VecTypeID, IdxTypeID;
5709 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5710 return error(
"Invalid insertelement record");
5712 return error(
"Invalid type for value");
5713 if (popValue(Record, OpNum, NextValueNo,
5715 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5716 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5717 return error(
"Invalid insert element record");
5719 ResTypeID = VecTypeID;
5727 unsigned BaseTypeID, ValTypeID, OffsetTypeID;
5728 if (getValueTypePair(Record, OpNum, NextValueNo,
Base, BaseTypeID,
5730 getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB) ||
5731 getValueTypePair(Record, OpNum, NextValueNo,
Offset, OffsetTypeID,
5733 return error(
"Invalid bitinsert record");
5734 if (
const char *Reason =
5736 return error(Reason);
5738 ResTypeID = BaseTypeID;
5746 return error(
"Record is empty for bitextract");
5750 return error(
"Invalid bitextract result type");
5752 unsigned SrcTypeID, OffsetTypeID;
5753 if (getValueTypePair(Record, OpNum, NextValueNo, Src, SrcTypeID, CurBB) ||
5754 getValueTypePair(Record, OpNum, NextValueNo,
Offset, OffsetTypeID,
5756 return error(
"Invalid bitextract record");
5757 if (
const char *Reason =
5759 return error(Reason);
5769 unsigned Vec1TypeID;
5770 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5772 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5774 return error(
"Invalid shufflevector record");
5776 unsigned MaskTypeID;
5777 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5778 return error(
"Invalid shufflevector record");
5780 return error(
"Invalid type for value");
5782 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5784 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5799 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5800 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5802 return error(
"Invalid comparison record");
5804 if (OpNum >=
Record.size())
5806 "Invalid record: operand number exceeded available operands");
5811 if (IsFP &&
Record.size() > OpNum+1)
5816 return error(
"Invalid fcmp predicate");
5817 I =
new FCmpInst(PredVal,
LHS,
RHS);
5820 return error(
"Invalid icmp predicate");
5821 I =
new ICmpInst(PredVal,
LHS,
RHS);
5822 if (
Record.size() > OpNum + 1 &&
5827 if (OpNum + 1 !=
Record.size())
5828 return error(
"Invalid comparison record");
5830 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5832 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5835 I->setFastMathFlags(FMF);
5852 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5853 return error(
"Invalid ret record");
5854 if (OpNum !=
Record.size())
5855 return error(
"Invalid ret record");
5863 return error(
"Invalid br record");
5864 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5866 return error(
"Invalid br record");
5868 if (
Record.size() == 1) {
5873 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5876 getVirtualTypeID(CondType), CurBB);
5877 if (!FalseDest || !
Cond)
5878 return error(
"Invalid br record");
5886 return error(
"Invalid cleanupret record");
5889 Value *CleanupPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5890 getVirtualTypeID(TokenTy), CurBB);
5892 return error(
"Invalid cleanupret record");
5894 if (
Record.size() == 2) {
5895 UnwindDest = getBasicBlock(Record[Idx++]);
5897 return error(
"Invalid cleanupret record");
5906 return error(
"Invalid catchret record");
5909 Value *CatchPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5910 getVirtualTypeID(TokenTy), CurBB);
5912 return error(
"Invalid catchret record");
5913 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5915 return error(
"Invalid catchret record");
5924 return error(
"Invalid catchswitch record");
5929 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5930 getVirtualTypeID(TokenTy), CurBB);
5932 return error(
"Invalid catchswitch record");
5937 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5938 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5940 return error(
"Invalid catchswitch record");
5945 if (Idx + 1 ==
Record.size()) {
5946 UnwindDest = getBasicBlock(Record[Idx++]);
5948 return error(
"Invalid catchswitch record");
5951 if (
Record.size() != Idx)
5952 return error(
"Invalid catchswitch record");
5956 for (BasicBlock *Handler : Handlers)
5957 CatchSwitch->addHandler(Handler);
5959 ResTypeID = getVirtualTypeID(
I->getType());
5967 return error(
"Invalid catchpad/cleanuppad record");
5972 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5973 getVirtualTypeID(TokenTy), CurBB);
5975 return error(
"Invalid catchpad/cleanuppad record");
5977 unsigned NumArgOperands =
Record[
Idx++];
5979 SmallVector<Value *, 2>
Args;
5980 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5983 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5984 return error(
"Invalid catchpad/cleanuppad record");
5985 Args.push_back(Val);
5988 if (
Record.size() != Idx)
5989 return error(
"Invalid catchpad/cleanuppad record");
5995 ResTypeID = getVirtualTypeID(
I->getType());
6001 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
6007 unsigned OpTyID =
Record[1];
6008 Type *OpTy = getTypeByID(OpTyID);
6014 return error(
"Invalid switch record");
6016 unsigned NumCases =
Record[4];
6021 unsigned CurIdx = 5;
6022 for (
unsigned i = 0; i != NumCases; ++i) {
6024 unsigned NumItems =
Record[CurIdx++];
6025 for (
unsigned ci = 0; ci != NumItems; ++ci) {
6026 bool isSingleNumber =
Record[CurIdx++];
6029 unsigned ActiveWords = 1;
6030 if (ValueBitWidth > 64)
6031 ActiveWords =
Record[CurIdx++];
6034 CurIdx += ActiveWords;
6036 if (!isSingleNumber) {
6038 if (ValueBitWidth > 64)
6039 ActiveWords =
Record[CurIdx++];
6042 CurIdx += ActiveWords;
6053 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
6054 for (ConstantInt *Cst : CaseVals)
6055 SI->addCase(Cst, DestBB);
6064 return error(
"Invalid switch record");
6065 unsigned OpTyID =
Record[0];
6066 Type *OpTy = getTypeByID(OpTyID);
6070 return error(
"Invalid switch record");
6071 unsigned NumCases = (
Record.size()-3)/2;
6074 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
6076 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
6077 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
6078 if (!CaseVal || !DestBB) {
6080 return error(
"Invalid switch record");
6082 SI->addCase(CaseVal, DestBB);
6089 return error(
"Invalid indirectbr record");
6090 unsigned OpTyID =
Record[0];
6091 Type *OpTy = getTypeByID(OpTyID);
6094 return error(
"Invalid indirectbr record");
6095 unsigned NumDests =
Record.size()-2;
6098 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
6099 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
6103 return error(
"Invalid indirectbr record");
6113 return error(
"Invalid invoke record");
6116 unsigned CCInfo =
Record[OpNum++];
6117 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
6118 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
6120 unsigned FTyID = InvalidTypeID;
6121 FunctionType *FTy =
nullptr;
6122 if ((CCInfo >> 13) & 1) {
6126 return error(
"Explicit invoke type is not a function type");
6130 unsigned CalleeTypeID;
6131 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6133 return error(
"Invalid invoke record");
6137 return error(
"Callee is not a pointer");
6139 FTyID = getContainedTypeID(CalleeTypeID);
6142 return error(
"Callee is not of pointer to function type");
6144 if (
Record.size() < FTy->getNumParams() + OpNum)
6145 return error(
"Insufficient operands to call");
6147 SmallVector<Value*, 16>
Ops;
6148 SmallVector<unsigned, 16> ArgTyIDs;
6149 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6150 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6151 Ops.push_back(
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6155 return error(
"Invalid invoke record");
6158 if (!FTy->isVarArg()) {
6159 if (
Record.size() != OpNum)
6160 return error(
"Invalid invoke record");
6163 while (OpNum !=
Record.size()) {
6166 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6167 return error(
"Invalid invoke record");
6174 if (!OperandBundles.empty())
6179 ResTypeID = getContainedTypeID(FTyID);
6180 OperandBundles.clear();
6183 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
6194 Value *Val =
nullptr;
6196 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
6197 return error(
"Invalid resume record");
6206 unsigned CCInfo =
Record[OpNum++];
6208 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
6209 unsigned NumIndirectDests =
Record[OpNum++];
6210 SmallVector<BasicBlock *, 16> IndirectDests;
6211 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
6212 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
6214 unsigned FTyID = InvalidTypeID;
6215 FunctionType *FTy =
nullptr;
6220 return error(
"Explicit call type is not a function type");
6224 unsigned CalleeTypeID;
6225 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6227 return error(
"Invalid callbr record");
6231 return error(
"Callee is not a pointer type");
6233 FTyID = getContainedTypeID(CalleeTypeID);
6236 return error(
"Callee is not of pointer to function type");
6238 if (
Record.size() < FTy->getNumParams() + OpNum)
6239 return error(
"Insufficient operands to call");
6241 SmallVector<Value*, 16>
Args;
6242 SmallVector<unsigned, 16> ArgTyIDs;
6244 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6246 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6247 if (FTy->getParamType(i)->isLabelTy())
6248 Arg = getBasicBlock(Record[OpNum]);
6250 Arg =
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6253 return error(
"Invalid callbr record");
6254 Args.push_back(Arg);
6259 if (!FTy->isVarArg()) {
6260 if (OpNum !=
Record.size())
6261 return error(
"Invalid callbr record");
6263 while (OpNum !=
Record.size()) {
6266 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6267 return error(
"Invalid callbr record");
6274 if (!OperandBundles.empty())
6279 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6282 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6287 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6288 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6289 unsigned LabelNo = ArgNo - FirstBlockArg;
6291 if (!BA || BA->getFunction() !=
F ||
6292 LabelNo > IndirectDests.
size() ||
6293 BA->getBasicBlock() != IndirectDests[LabelNo])
6294 return error(
"callbr argument does not match indirect dest");
6299 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6303 for (
Value *Arg : Args)
6306 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6309 std::string Constraints =
IA->getConstraintString().str();
6312 for (
const auto &CI : ConstraintInfo) {
6314 if (ArgNo >= FirstBlockArg)
6315 Constraints.insert(Pos,
"!");
6320 Pos = Constraints.find(
',', Pos);
6321 if (Pos == std::string::npos)
6327 IA->hasSideEffects(),
IA->isAlignStack(),
6328 IA->getDialect(),
IA->canThrow());
6334 ResTypeID = getContainedTypeID(FTyID);
6335 OperandBundles.clear();
6352 return error(
"Invalid phi record");
6354 unsigned TyID =
Record[0];
6355 Type *Ty = getTypeByID(TyID);
6357 return error(
"Invalid phi record");
6362 size_t NumArgs = (
Record.size() - 1) / 2;
6366 return error(
"Invalid phi record");
6370 SmallDenseMap<BasicBlock *, Value *>
Args;
6371 for (
unsigned i = 0; i != NumArgs; i++) {
6372 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6375 return error(
"Invalid phi BB");
6382 auto It =
Args.find(BB);
6384 if (It !=
Args.end()) {
6398 if (!PhiConstExprBB)
6400 EdgeBB = PhiConstExprBB;
6408 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6410 V =
getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6414 return error(
"Invalid phi record");
6417 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6418 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6419 PhiConstExprBB =
nullptr;
6422 Args.insert({BB,
V});
6428 if (
Record.size() % 2 == 0) {
6432 I->setFastMathFlags(FMF);
6444 return error(
"Invalid landingpad record");
6448 return error(
"Invalid landingpad record");
6451 Type *Ty = getTypeByID(ResTypeID);
6453 return error(
"Invalid landingpad record");
6455 Value *PersFn =
nullptr;
6456 unsigned PersFnTypeID;
6457 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6459 return error(
"Invalid landingpad record");
6461 if (!
F->hasPersonalityFn())
6464 return error(
"Personality function mismatch");
6471 for (
unsigned J = 0; J != NumClauses; ++J) {
6477 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6480 return error(
"Invalid landingpad record");
6485 "Catch clause has a invalid type!");
6488 "Filter clause has invalid type!");
6499 return error(
"Invalid alloca record");
6500 using APV = AllocaPackedValues;
6504 unsigned TyID =
Record[0];
6505 Type *Ty = getTypeByID(TyID);
6507 TyID = getContainedTypeID(TyID);
6508 Ty = getTypeByID(TyID);
6510 return error(
"Missing element type for old-style alloca");
6512 unsigned OpTyID =
Record[1];
6513 Type *OpTy = getTypeByID(OpTyID);
6514 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6519 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6523 return error(
"Invalid alloca record");
6525 const DataLayout &
DL = TheModule->getDataLayout();
6526 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6529 return error(
"alloca of unsized type");
6531 Align =
DL.getPrefTypeAlign(Ty);
6533 if (!
Size->getType()->isIntegerTy())
6534 return error(
"alloca element count must have integer type");
6536 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6540 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6548 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6549 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6550 return error(
"Invalid load record");
6553 return error(
"Load operand is not a pointer type");
6556 if (OpNum + 3 ==
Record.size()) {
6557 ResTypeID =
Record[OpNum++];
6558 Ty = getTypeByID(ResTypeID);
6560 ResTypeID = getContainedTypeID(OpTypeID);
6561 Ty = getTypeByID(ResTypeID);
6565 return error(
"Missing load type");
6567 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6571 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6574 return error(
"load of unsized type");
6576 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6577 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6586 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6587 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size() &&
6588 OpNum + 6 !=
Record.size()))
6589 return error(
"Invalid load atomic record");
6592 return error(
"Load operand is not a pointer type");
6595 if (
Record.size() >= OpNum + 5) {
6596 ResTypeID =
Record[OpNum++];
6597 Ty = getTypeByID(ResTypeID);
6599 ResTypeID = getContainedTypeID(OpTypeID);
6600 Ty = getTypeByID(ResTypeID);
6604 return error(
"Missing atomic load type");
6606 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6610 if (Ordering == AtomicOrdering::NotAtomic ||
6611 Ordering == AtomicOrdering::Release ||
6612 Ordering == AtomicOrdering::AcquireRelease)
6613 return error(
"Invalid load atomic record");
6614 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6615 return error(
"Invalid load atomic record");
6616 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6617 bool IsElementwise =
Record.size() > OpNum + 4 &&
Record[OpNum + 4];
6620 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6623 return error(
"Alignment missing from atomic load");
6626 LoadStoreInstProperties{
Record[OpNum + 1] != 0, *
Align,
6636 unsigned PtrTypeID, ValTypeID;
6637 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6638 return error(
"Invalid store record");
6641 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6642 return error(
"Invalid store record");
6644 ValTypeID = getContainedTypeID(PtrTypeID);
6645 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6646 ValTypeID, Val, CurBB))
6647 return error(
"Invalid store record");
6650 if (OpNum + 2 !=
Record.size())
6651 return error(
"Invalid store record");
6656 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6659 return error(
"store of unsized type");
6661 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6662 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6672 unsigned PtrTypeID, ValTypeID;
6673 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6675 return error(
"Invalid store atomic record");
6677 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6678 return error(
"Invalid store atomic record");
6680 ValTypeID = getContainedTypeID(PtrTypeID);
6681 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6682 ValTypeID, Val, CurBB))
6683 return error(
"Invalid store atomic record");
6686 if (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size())
6687 return error(
"Invalid store atomic record");
6692 if (Ordering == AtomicOrdering::NotAtomic ||
6693 Ordering == AtomicOrdering::Acquire ||
6694 Ordering == AtomicOrdering::AcquireRelease)
6695 return error(
"Invalid store atomic record");
6696 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6697 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6698 return error(
"Invalid store atomic record");
6701 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6704 return error(
"Alignment missing from atomic store");
6706 bool IsElementwise =
Record.size() > OpNum + 4 &&
Record[OpNum + 4];
6710 LoadStoreInstProperties{
Record[OpNum + 1] != 0, *
Align,
6719 const size_t NumRecords =
Record.size();
6721 Value *Ptr =
nullptr;
6723 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6724 return error(
"Invalid cmpxchg record");
6727 return error(
"Cmpxchg operand is not a pointer type");
6730 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6731 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6732 CmpTypeID, Cmp, CurBB))
6733 return error(
"Invalid cmpxchg record");
6736 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6738 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6739 return error(
"Invalid cmpxchg record");
6743 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6744 SuccessOrdering == AtomicOrdering::Unordered)
6745 return error(
"Invalid cmpxchg record");
6747 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6749 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6757 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6758 FailureOrdering == AtomicOrdering::Unordered)
6759 return error(
"Invalid cmpxchg record");
6762 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6764 I =
new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6765 FailureOrdering, SSID);
6768 if (NumRecords < 8) {
6772 I->insertInto(CurBB, CurBB->
end());
6774 ResTypeID = CmpTypeID;
6777 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6778 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6787 const size_t NumRecords =
Record.size();
6789 Value *Ptr =
nullptr;
6791 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6792 return error(
"Invalid cmpxchg record");
6795 return error(
"Cmpxchg operand is not a pointer type");
6799 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6800 return error(
"Invalid cmpxchg record");
6802 Value *Val =
nullptr;
6803 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6805 return error(
"Invalid cmpxchg record");
6807 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6808 return error(
"Invalid cmpxchg record");
6810 const bool IsVol =
Record[OpNum];
6815 return error(
"Invalid cmpxchg success ordering");
6817 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6819 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6825 return error(
"Invalid cmpxchg failure ordering");
6827 const bool IsWeak =
Record[OpNum + 4];
6831 if (NumRecords == (OpNum + 6)) {
6832 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6837 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6839 I =
new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6840 FailureOrdering, SSID);
6844 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6845 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6854 const size_t NumRecords =
Record.size();
6857 Value *Ptr =
nullptr;
6859 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6860 return error(
"Invalid atomicrmw record");
6863 return error(
"Invalid atomicrmw record");
6865 Value *Val =
nullptr;
6866 unsigned ValTypeID = InvalidTypeID;
6868 ValTypeID = getContainedTypeID(PtrTypeID);
6869 if (popValue(Record, OpNum, NextValueNo,
6870 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6871 return error(
"Invalid atomicrmw record");
6873 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6874 return error(
"Invalid atomicrmw record");
6877 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6878 return error(
"Invalid atomicrmw record");
6880 bool IsElementwise =
false;
6885 return error(
"Invalid atomicrmw record");
6887 const bool IsVol =
Record[OpNum + 1];
6890 if (Ordering == AtomicOrdering::NotAtomic ||
6891 Ordering == AtomicOrdering::Unordered)
6892 return error(
"Invalid atomicrmw record");
6894 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6898 if (NumRecords == (OpNum + 5)) {
6899 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6905 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6907 I =
new AtomicRMWInst(
Operation, Ptr, Val, *Alignment, Ordering, SSID,
6909 ResTypeID = ValTypeID;
6917 return error(
"Invalid fence record");
6919 if (Ordering == AtomicOrdering::NotAtomic ||
6920 Ordering == AtomicOrdering::Unordered ||
6921 Ordering == AtomicOrdering::Monotonic)
6922 return error(
"Invalid fence record");
6924 I =
new FenceInst(
Context, Ordering, SSID);
6931 SeenDebugRecord =
true;
6934 return error(
"Invalid dbg record: missing instruction");
6937 Inst->
getParent()->insertDbgRecordBefore(
6948 SeenDebugRecord =
true;
6951 return error(
"Invalid dbg record: missing instruction");
6968 DILocalVariable *Var =
6970 DIExpression *Expr =
6983 unsigned SlotBefore =
Slot;
6984 if (getValueTypePair(Record, Slot, NextValueNo,
V, TyID, CurBB))
6985 return error(
"Invalid dbg record: invalid value");
6987 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6990 RawLocation = getFnMetadataByID(Record[Slot++]);
6993 DbgVariableRecord *DVR =
nullptr;
6997 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6998 DbgVariableRecord::LocationType::Value);
7001 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
7002 DbgVariableRecord::LocationType::Declare);
7005 DVR =
new DbgVariableRecord(
7006 RawLocation, Var, Expr, DIL,
7007 DbgVariableRecord::LocationType::DeclareValue);
7011 DIExpression *AddrExpr =
7013 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
7014 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
7027 return error(
"Invalid call record");
7031 unsigned CCInfo =
Record[OpNum++];
7037 return error(
"Fast math flags indicator set for call with no FMF");
7040 unsigned FTyID = InvalidTypeID;
7041 FunctionType *FTy =
nullptr;
7046 return error(
"Explicit call type is not a function type");
7050 unsigned CalleeTypeID;
7051 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
7053 return error(
"Invalid call record");
7057 return error(
"Callee is not a pointer type");
7059 FTyID = getContainedTypeID(CalleeTypeID);
7062 return error(
"Callee is not of pointer to function type");
7064 if (
Record.size() < FTy->getNumParams() + OpNum)
7065 return error(
"Insufficient operands to call");
7067 SmallVector<Value*, 16>
Args;
7068 SmallVector<unsigned, 16> ArgTyIDs;
7070 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
7071 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
7072 if (FTy->getParamType(i)->isLabelTy())
7073 Args.push_back(getBasicBlock(Record[OpNum]));
7076 FTy->getParamType(i), ArgTyID, CurBB));
7079 return error(
"Invalid call record");
7083 if (!FTy->isVarArg()) {
7084 if (OpNum !=
Record.size())
7085 return error(
"Invalid call record");
7087 while (OpNum !=
Record.size()) {
7090 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
7091 return error(
"Invalid call record");
7098 if (!OperandBundles.empty())
7102 ResTypeID = getContainedTypeID(FTyID);
7103 OperandBundles.clear();
7117 SeenDebugIntrinsic =
true;
7120 if (
auto *ListAsValue =
7133 return error(
"Fast-math-flags specified for call without "
7134 "floating-point scalar or vector return type");
7135 I->setFastMathFlags(FMF);
7141 return error(
"Invalid va_arg record");
7142 unsigned OpTyID =
Record[0];
7143 Type *OpTy = getTypeByID(OpTyID);
7146 Type *ResTy = getTypeByID(ResTypeID);
7147 if (!OpTy || !
Op || !ResTy)
7148 return error(
"Invalid va_arg record");
7149 I =
new VAArgInst(
Op, ResTy);
7159 if (
Record.empty() || Record[0] >= BundleTags.size())
7160 return error(
"Invalid operand bundle record");
7162 std::vector<Value *> Inputs;
7165 while (OpNum !=
Record.size()) {
7167 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
7168 return error(
"Invalid operand bundle record");
7169 Inputs.push_back(
Op);
7172 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
7180 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
7181 return error(
"Invalid freeze record");
7182 if (OpNum !=
Record.size())
7183 return error(
"Invalid freeze record");
7185 I =
new FreezeInst(
Op);
7186 ResTypeID = OpTypeID;
7196 return error(
"Invalid instruction with no BB");
7198 if (!OperandBundles.empty()) {
7200 return error(
"Operand bundles found with no consumer");
7202 I->insertInto(CurBB, CurBB->
end());
7205 if (
I->isTerminator()) {
7207 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
7211 if (!
I->getType()->isVoidTy()) {
7212 assert(
I->getType() == getTypeByID(ResTypeID) &&
7213 "Incorrect result type ID");
7221 if (!OperandBundles.empty())
7222 return error(
"Operand bundles found with no consumer");
7226 if (!
A->getParent()) {
7228 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
7234 return error(
"Never resolved value found in function");
7239 if (MDLoader->hasFwdRefs())
7240 return error(
"Invalid function metadata: outgoing forward refs");
7245 for (
const auto &Pair : ConstExprEdgeBBs) {
7256 ValueList.
shrinkTo(ModuleValueListSize);
7257 MDLoader->shrinkTo(ModuleMDLoaderSize);
7258 std::vector<BasicBlock*>().swap(FunctionBBs);
7263Error BitcodeReader::findFunctionInStream(
7265 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7266 while (DeferredFunctionInfoIterator->second == 0) {
7271 assert(VSTOffset == 0 || !
F->hasName());
7274 if (
Error Err = rememberAndSkipFunctionBodies())
7280SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
7283 if (Val >= SSIDs.
size())
7292Error BitcodeReader::materialize(GlobalValue *GV) {
7295 if (!
F || !
F->isMaterializable())
7298 auto DFII = DeferredFunctionInfo.
find(
F);
7299 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
7302 if (DFII->second == 0)
7303 if (
Error Err = findFunctionInStream(
F, DFII))
7307 if (
Error Err = materializeMetadata())
7314 if (
Error Err = parseFunctionBody(
F))
7316 F->setIsMaterializable(
false);
7320 if (SeenDebugIntrinsic && SeenDebugRecord)
7321 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7327 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7328 F->setSubprogram(SP);
7333 attachUpgradedGUIDMetadata(*
F);
7336 if (!MDLoader->isStrippingTBAA()) {
7338 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7341 MDLoader->setStripTBAA(
true);
7348 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7349 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7355 unsigned ExpectedNumOperands = 0;
7357 ExpectedNumOperands = 2;
7359 ExpectedNumOperands =
SI->getNumSuccessors();
7361 ExpectedNumOperands = 1;
7365 ExpectedNumOperands = 2;
7372 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7373 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7379 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7380 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7382 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7383 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7384 CI->getArgOperand(ArgNo)->getType(),
7385 CI->getParamAttributes(ArgNo)));
7388 if (
Function *OldFn = CI->getCalledFunction()) {
7389 auto It = UpgradedIntrinsics.
find(OldFn);
7390 if (It != UpgradedIntrinsics.
end())
7394 BC && BC->getSrcTy() == BC->getDestTy() &&
7400 CI && CI->isMustTailCall() && CI->getNextNode() == BC) {
7401 BC->replaceAllUsesWith(CI);
7402 BC->eraseFromParent();
7412 return materializeForwardReferencedFunctions();
7415Error BitcodeReader::materializeModule() {
7416 if (
Error Err = materializeMetadata())
7420 WillMaterializeAllForwardRefs =
true;
7425 if (
Error Err = materialize(&
F))
7431 if (LastFunctionBlockBit || NextUnreadBit)
7433 ? LastFunctionBlockBit
7439 if (!BasicBlockFwdRefs.
empty())
7440 return error(
"Never resolved function from blockaddress");
7446 for (
auto &[OldFn, NewFn] : UpgradedIntrinsics) {
7447 for (User *U : OldFn->users()) {
7451 if (OldFn != NewFn) {
7452 if (!OldFn->use_empty())
7453 OldFn->replaceAllUsesWith(NewFn);
7454 OldFn->eraseFromParent();
7457 UpgradedIntrinsics.clear();
7472std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7473 return IdentifiedStructTypes;
7476ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7477 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7478 StringRef ModulePath, std::function<
bool(StringRef)> IsPrevailing,
7479 std::function<
void(ValueInfo)> OnValueInfo)
7480 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7481 ModulePath(ModulePath), IsPrevailing(IsPrevailing),
7482 OnValueInfo(OnValueInfo) {}
7484void ModuleSummaryIndexBitcodeReader::addThisModule() {
7489ModuleSummaryIndexBitcodeReader::getThisModule() {
7493template <
bool AllowNullValueInfo>
7494std::pair<ValueInfo, GlobalValue::GUID>
7495ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7496 auto VGI = ValueIdToValueInfoMap[ValueId];
7503 assert(AllowNullValueInfo || std::get<0>(VGI));
7507void ModuleSummaryIndexBitcodeReader::setValueGUID(
7509 StringRef SourceFileName) {
7511 if (ValueID < DefinedGUIDs.size())
7512 ValueGUID = DefinedGUIDs[ValueID];
7519 auto OriginalNameID = ValueGUID;
7523 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7531 ValueIdToValueInfoMap[ValueID] = std::make_pair(VI, OriginalNameID);
7539Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7541 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7548 if (!MaybeCurrentBit)
7555 SmallVector<uint64_t, 64>
Record;
7564 BitstreamEntry
Entry = MaybeEntry.
get();
7566 switch (
Entry.Kind) {
7569 return error(
"Malformed block");
7585 switch (MaybeRecord.
get()) {
7590 return error(
"Invalid vst_code_entry record");
7591 unsigned ValueID =
Record[0];
7593 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7594 assert(VLI != ValueIdToLinkageMap.
end() &&
7595 "No linkage found for VST entry?");
7604 return error(
"Invalid vst_code_fnentry record");
7605 unsigned ValueID =
Record[0];
7607 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7608 assert(VLI != ValueIdToLinkageMap.
end() &&
7609 "No linkage found for VST entry?");
7617 unsigned ValueID =
Record[0];
7621 ValueIdToValueInfoMap[ValueID] =
7632Error ModuleSummaryIndexBitcodeReader::parseModule() {
7636 SmallVector<uint64_t, 64>
Record;
7637 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7638 unsigned ValueId = 0;
7642 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
7645 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7647 switch (
Entry.Kind) {
7649 return error(
"Malformed block");
7661 if (
Error Err = readBlockInfo())
7667 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7668 !SeenGlobalValSummary) &&
7669 "Expected early VST parse via VSTOffset record");
7676 if (!SourceFileName.
empty())
7678 assert(!SeenValueSymbolTable &&
7679 "Already read VST when parsing summary block?");
7684 if (VSTOffset > 0) {
7685 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7687 SeenValueSymbolTable =
true;
7689 SeenGlobalValSummary =
true;
7690 if (
Error Err = parseEntireSummary(
Entry.ID))
7694 if (
Error Err = parseModuleStringTable())
7702 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7705 switch (MaybeBitCode.
get()) {
7709 if (
Error Err = parseVersionRecord(Record).takeError())
7717 return error(
"Invalid source filename record");
7724 return error(
"Invalid hash length " + Twine(
Record.size()));
7725 auto &Hash = getThisModule()->second;
7727 for (
auto &Val : Record) {
7728 assert(!(Val >> 32) &&
"Unexpected high bits set");
7736 return error(
"Invalid vstoffset record");
7740 VSTOffset =
Record[0] - 1;
7745 DefinedGUIDs.reserve(DefinedGUIDs.size() +
Record.size() / 2);
7746 for (
size_t i = 0; i <
Record.size(); i += 2)
7747 DefinedGUIDs.push_back(Record[i] << 32 | Record[i + 1]);
7757 ArrayRef<uint64_t> GVRecord;
7758 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7759 if (GVRecord.
size() <= 3)
7760 return error(
"Invalid global record");
7764 ValueIdToLinkageMap[ValueId++] =
Linkage;
7768 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7779ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7783 Ret.
push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7788ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7789 bool IsOldProfileFormat,
7790 bool HasProfile,
bool HasRelBF) {
7794 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7799 for (
unsigned I = 0,
E =
Record.size();
I !=
E; ++
I) {
7801 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7802 if (IsOldProfileFormat) {
7806 }
else if (HasProfile)
7809 else if (HasRelBF) {
7811 bool HasTailCall =
false;
7813 Info.setHasTailCall(HasTailCall);
7843 static_cast<size_t>(
Record[Slot + 1])};
7866 while (Slot <
Record.size())
7870std::vector<FunctionSummary::ParamAccess>
7871ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7872 auto ReadRange = [&]() {
7874 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7876 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7883 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7884 while (!
Record.empty()) {
7885 PendingParamAccesses.emplace_back();
7886 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7888 ParamAccess.
Use = ReadRange();
7893 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7894 Call.Offsets = ReadRange();
7897 return PendingParamAccesses;
7900void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7901 ArrayRef<uint64_t> Record,
size_t &Slot,
7904 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7908void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7909 ArrayRef<uint64_t> Record) {
7917 while (Slot <
Record.size())
7918 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7921SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7922 ArrayRef<uint64_t> Record,
unsigned &
I) {
7923 SmallVector<unsigned> StackIdList;
7927 if (RadixArray.empty()) {
7928 unsigned NumStackEntries =
Record[
I++];
7930 StackIdList.
reserve(NumStackEntries);
7931 for (
unsigned J = 0; J < NumStackEntries; J++) {
7932 assert(Record[
I] < StackIds.size());
7933 StackIdList.
push_back(getStackIdIndex(Record[
I++]));
7936 unsigned RadixIndex =
Record[
I++];
7942 assert(RadixIndex < RadixArray.size());
7943 unsigned NumStackIds = RadixArray[RadixIndex++];
7944 StackIdList.
reserve(NumStackIds);
7945 while (NumStackIds--) {
7946 assert(RadixIndex < RadixArray.size());
7947 unsigned Elem = RadixArray[RadixIndex];
7948 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7949 RadixIndex = RadixIndex - Elem;
7950 assert(RadixIndex < RadixArray.size());
7951 Elem = RadixArray[RadixIndex];
7953 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7956 StackIdList.
push_back(getStackIdIndex(Elem));
7966 unsigned FirstWORef = Refs.
size() - WOCnt;
7967 unsigned RefNo = FirstWORef - ROCnt;
7968 for (; RefNo < FirstWORef; ++RefNo)
7969 Refs[RefNo].setReadOnly();
7970 for (; RefNo < Refs.
size(); ++RefNo)
7971 Refs[RefNo].setWriteOnly();
7976Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7979 SmallVector<uint64_t, 64>
Record;
7986 BitstreamEntry
Entry = MaybeEntry.
get();
7989 return error(
"Invalid Summary Block: record for version expected");
7994 return error(
"Invalid Summary Block: version expected");
7997 const bool IsOldProfileFormat =
Version == 1;
8000 const bool MemProfAfterFunctionSummary =
Version >= 13;
8002 return error(
"Invalid summary version " + Twine(
Version) +
" in module '" +
8003 ModulePath +
"'. Version should be in the range [1-" +
8009 GlobalValueSummary *LastSeenSummary =
nullptr;
8019 FunctionSummary *CurrentPrevailingFS =
nullptr;
8024 std::vector<GlobalValue::GUID> PendingTypeTests;
8025 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
8026 PendingTypeCheckedLoadVCalls;
8027 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
8028 PendingTypeCheckedLoadConstVCalls;
8029 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
8031 std::vector<CallsiteInfo> PendingCallsites;
8032 std::vector<AllocInfo> PendingAllocs;
8033 std::vector<uint64_t> PendingContextIds;
8039 BitstreamEntry
Entry = MaybeEntry.
get();
8041 switch (
Entry.Kind) {
8044 return error(
"Malformed block");
8060 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
8063 unsigned BitCode = MaybeBitCode.
get();
8080 ValueIdToValueInfoMap[ValueID] =
8098 unsigned ValueID =
Record[0];
8100 unsigned InstCount =
Record[2];
8102 unsigned NumRefs =
Record[3];
8103 unsigned NumRORefs = 0, NumWORefs = 0;
8104 int RefListStartIndex = 4;
8108 RefListStartIndex = 5;
8111 RefListStartIndex = 6;
8114 RefListStartIndex = 7;
8125 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8127 "Record size inconsistent with number of references");
8129 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8134 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8135 IsOldProfileFormat, HasProfile, HasRelBF);
8137 auto [
VI,
GUID] = getValueInfoFromValueId(ValueID);
8144 IsPrevailing(
VI.name());
8150 assert(!MemProfAfterFunctionSummary ||
8151 (PendingCallsites.empty() && PendingAllocs.empty()));
8152 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
8153 PendingCallsites.clear();
8154 PendingAllocs.clear();
8157 auto FS = std::make_unique<FunctionSummary>(
8159 std::move(Calls), std::move(PendingTypeTests),
8160 std::move(PendingTypeTestAssumeVCalls),
8161 std::move(PendingTypeCheckedLoadVCalls),
8162 std::move(PendingTypeTestAssumeConstVCalls),
8163 std::move(PendingTypeCheckedLoadConstVCalls),
8164 std::move(PendingParamAccesses), std::move(PendingCallsites),
8165 std::move(PendingAllocs));
8166 FS->setModulePath(getThisModule()->first());
8167 FS->setOriginalName(GUID);
8170 if (MemProfAfterFunctionSummary) {
8171 if (IsPrevailingSym)
8172 CurrentPrevailingFS =
FS.get();
8174 CurrentPrevailingFS =
nullptr;
8183 unsigned ValueID =
Record[0];
8185 unsigned AliaseeID =
Record[2];
8187 auto AS = std::make_unique<AliasSummary>(Flags);
8193 AS->setModulePath(getThisModule()->first());
8195 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
8197 if (!AliaseeInModule)
8198 return error(
"Alias expects aliasee summary to be parsed");
8199 AS->setAliasee(AliaseeVI, AliaseeInModule);
8201 auto GUID = getValueInfoFromValueId(ValueID);
8202 AS->setOriginalName(std::get<1>(GUID));
8208 unsigned ValueID =
Record[0];
8210 unsigned RefArrayStart = 2;
8211 GlobalVarSummary::GVarFlags GVF(
false,
8221 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8223 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8224 FS->setModulePath(getThisModule()->first());
8225 auto GUID = getValueInfoFromValueId(ValueID);
8226 FS->setOriginalName(std::get<1>(GUID));
8234 unsigned ValueID =
Record[0];
8237 unsigned NumRefs =
Record[3];
8238 unsigned RefListStartIndex = 4;
8239 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
8242 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8244 for (
unsigned I = VTableListStartIndex,
E =
Record.size();
I !=
E; ++
I) {
8245 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
8250 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8251 VS->setModulePath(getThisModule()->first());
8252 VS->setVTableFuncs(VTableFuncs);
8253 auto GUID = getValueInfoFromValueId(ValueID);
8254 VS->setOriginalName(std::get<1>(GUID));
8266 unsigned ValueID =
Record[0];
8269 unsigned InstCount =
Record[3];
8271 unsigned NumRefs =
Record[4];
8272 unsigned NumRORefs = 0, NumWORefs = 0;
8273 int RefListStartIndex = 5;
8277 RefListStartIndex = 6;
8278 size_t NumRefsIndex = 5;
8280 unsigned NumRORefsOffset = 1;
8281 RefListStartIndex = 7;
8284 RefListStartIndex = 8;
8286 RefListStartIndex = 9;
8288 NumRORefsOffset = 2;
8291 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
8293 NumRefs =
Record[NumRefsIndex];
8297 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8299 "Record size inconsistent with number of references");
8301 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8304 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8305 IsOldProfileFormat, HasProfile,
false);
8306 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8308 auto FS = std::make_unique<FunctionSummary>(
8310 std::move(Edges), std::move(PendingTypeTests),
8311 std::move(PendingTypeTestAssumeVCalls),
8312 std::move(PendingTypeCheckedLoadVCalls),
8313 std::move(PendingTypeTestAssumeConstVCalls),
8314 std::move(PendingTypeCheckedLoadConstVCalls),
8315 std::move(PendingParamAccesses), std::move(PendingCallsites),
8316 std::move(PendingAllocs));
8317 LastSeenSummary =
FS.get();
8318 if (MemProfAfterFunctionSummary)
8319 CurrentPrevailingFS =
FS.get();
8320 LastSeenGUID =
VI.getGUID();
8321 FS->setModulePath(ModuleIdMap[ModuleId]);
8329 unsigned ValueID =
Record[0];
8332 unsigned AliaseeValueId =
Record[3];
8334 auto AS = std::make_unique<AliasSummary>(Flags);
8335 LastSeenSummary = AS.get();
8336 AS->setModulePath(ModuleIdMap[ModuleId]);
8338 auto AliaseeVI = std::get<0>(
8339 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8341 auto AliaseeInModule =
8343 AS->setAliasee(AliaseeVI, AliaseeInModule);
8345 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8346 LastSeenGUID =
VI.getGUID();
8352 unsigned ValueID =
Record[0];
8355 unsigned RefArrayStart = 3;
8356 GlobalVarSummary::GVarFlags GVF(
false,
8366 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8368 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8369 LastSeenSummary =
FS.get();
8370 FS->setModulePath(ModuleIdMap[ModuleId]);
8371 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8372 LastSeenGUID =
VI.getGUID();
8379 if (!LastSeenSummary)
8380 return error(
"Name attachment that does not follow a combined record");
8384 LastSeenSummary =
nullptr;
8389 assert(PendingTypeTests.empty());
8394 assert(PendingTypeTestAssumeVCalls.empty());
8395 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8396 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8400 assert(PendingTypeCheckedLoadVCalls.empty());
8401 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8402 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8406 PendingTypeTestAssumeConstVCalls.push_back(
8411 PendingTypeCheckedLoadConstVCalls.push_back(
8418 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8419 StringRef
Name(Strtab.
data() + Record[
I],
8420 static_cast<size_t>(Record[
I + 1]));
8423 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, GUID);
8426 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8428 StringRef
Name(Strtab.
data() + Record[
I + 1],
8429 static_cast<size_t>(Record[
I + 2]));
8430 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8439 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8440 StringRef
Name(Strtab.
data() + Record[
I],
8441 static_cast<size_t>(Record[
I + 1]));
8444 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, GUID);
8447 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8449 StringRef
Name(Strtab.
data() + Record[
I + 1],
8450 static_cast<size_t>(Record[
I + 2]));
8451 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8462 parseTypeIdCompatibleVtableSummaryRecord(Record);
8470 PendingParamAccesses = parseParamAccesses(Record);
8477 assert(StackIds.empty());
8479 StackIds = ArrayRef<uint64_t>(Record);
8485 StackIds.reserve(
Record.size() / 2);
8486 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8487 StackIds.push_back(*R << 32 | *(R + 1));
8489 assert(StackIdToIndex.empty());
8491 StackIdToIndex.resize(StackIds.size(), UninitializedStackIdIndex);
8496 RadixArray = ArrayRef<uint64_t>(Record);
8503 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8505 unsigned ValueID =
Record[0];
8506 SmallVector<unsigned> StackIdList;
8508 assert(R < StackIds.size());
8509 StackIdList.
push_back(getStackIdIndex(R));
8511 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8512 if (MemProfAfterFunctionSummary)
8514 CallsiteInfo({
VI, std::move(StackIdList)}));
8516 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8523 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8524 auto RecordIter =
Record.begin();
8525 unsigned ValueID = *RecordIter++;
8526 unsigned NumStackIds = *RecordIter++;
8527 unsigned NumVersions = *RecordIter++;
8528 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8529 SmallVector<unsigned> StackIdList;
8530 for (
unsigned J = 0; J < NumStackIds; J++) {
8531 assert(*RecordIter < StackIds.size());
8532 StackIdList.
push_back(getStackIdIndex(*RecordIter++));
8534 SmallVector<unsigned> Versions;
8535 for (
unsigned J = 0; J < NumVersions; J++)
8537 ValueInfo
VI = std::get<0>(
8538 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8539 if (MemProfAfterFunctionSummary)
8541 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8543 PendingCallsites.push_back(
8544 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8551 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8556 PendingContextIds.reserve(
Record.size() / 2);
8557 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8558 PendingContextIds.push_back(*R << 32 | *(R + 1));
8565 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8566 PendingContextIds.clear();
8570 std::vector<MIBInfo> MIBs;
8571 unsigned NumMIBs = 0;
8574 unsigned MIBsRead = 0;
8575 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8579 auto StackIdList = parseAllocInfoContext(Record,
I);
8580 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8586 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8588 assert(!PendingContextIds.empty() &&
8589 "Missing context ids for alloc sizes");
8590 unsigned ContextIdIndex = 0;
8596 while (MIBsRead++ < NumMIBs) {
8598 unsigned NumContextSizeInfoEntries =
Record[
I++];
8600 std::vector<ContextTotalSize> ContextSizes;
8601 ContextSizes.reserve(NumContextSizeInfoEntries);
8602 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8603 assert(ContextIdIndex < PendingContextIds.size());
8605 if (PendingContextIds[ContextIdIndex] == 0) {
8614 ContextSizes.push_back(
8615 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8617 AllContextSizes.push_back(std::move(ContextSizes));
8619 PendingContextIds.clear();
8621 AllocInfo AI(std::move(MIBs));
8622 if (!AllContextSizes.empty()) {
8623 assert(AI.MIBs.size() == AllContextSizes.size());
8624 AI.ContextSizeInfos = std::move(AllContextSizes);
8627 if (MemProfAfterFunctionSummary)
8628 CurrentPrevailingFS->
addAlloc(std::move(AI));
8630 PendingAllocs.push_back(std::move(AI));
8638 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8640 std::vector<MIBInfo> MIBs;
8641 unsigned NumMIBs =
Record[
I++];
8642 unsigned NumVersions =
Record[
I++];
8643 unsigned MIBsRead = 0;
8644 while (MIBsRead++ < NumMIBs) {
8647 SmallVector<unsigned> StackIdList;
8649 StackIdList = parseAllocInfoContext(Record,
I);
8650 MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8653 SmallVector<uint8_t> Versions;
8654 for (
unsigned J = 0; J < NumVersions; J++)
8657 AllocInfo AI(std::move(Versions), std::move(MIBs));
8658 if (MemProfAfterFunctionSummary)
8659 CurrentPrevailingFS->
addAlloc(std::move(AI));
8661 PendingAllocs.push_back(std::move(AI));
8671Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8675 SmallVector<uint64_t, 64>
Record;
8677 SmallString<128> ModulePath;
8684 BitstreamEntry
Entry = MaybeEntry.
get();
8686 switch (
Entry.Kind) {
8689 return error(
"Malformed block");
8701 switch (MaybeRecord.
get()) {
8709 return error(
"Invalid code_entry record");
8711 LastSeenModule = TheIndex.
addModule(ModulePath);
8712 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8720 return error(
"Invalid hash length " + Twine(
Record.size()));
8721 if (!LastSeenModule)
8722 return error(
"Invalid hash that does not follow a module path");
8724 for (
auto &Val : Record) {
8725 assert(!(Val >> 32) &&
"Unexpected high bits set");
8726 LastSeenModule->
second[Pos++] = Val;
8729 LastSeenModule =
nullptr;
8742class BitcodeErrorCategoryType :
public std::error_category {
8743 const char *
name()
const noexcept
override {
8744 return "llvm.bitcode";
8747 std::string message(
int IE)
const override {
8750 case BitcodeError::CorruptedBitcode:
8751 return "Corrupted bitcode";
8760 static BitcodeErrorCategoryType ErrorCategory;
8761 return ErrorCategory;
8765 unsigned Block,
unsigned RecordID) {
8767 return std::move(Err);
8776 switch (Entry.Kind) {
8781 return error(
"Malformed block");
8785 return std::move(Err);
8795 if (MaybeRecord.
get() == RecordID)
8806Expected<std::vector<BitcodeModule>>
8810 return FOrErr.takeError();
8811 return std::move(FOrErr->Mods);
8836 switch (Entry.Kind) {
8839 return error(
"Malformed block");
8842 uint64_t IdentificationBit = -1ull;
8846 return std::move(Err);
8852 Entry = MaybeEntry.
get();
8857 return error(
"Malformed block");
8863 return std::move(Err);
8882 if (!
I.Strtab.empty())
8889 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8890 F.StrtabForSymtab = *Strtab;
8906 if (
F.Symtab.empty())
8907 F.Symtab = *SymtabOrErr;
8912 return std::move(Err);
8917 return std::move(E);
8932BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8933 bool ShouldLazyLoadMetadata,
bool IsImporting,
8937 std::string ProducerIdentification;
8938 if (IdentificationBit != -1ull) {
8940 return std::move(JumpFailed);
8943 return std::move(
E);
8947 return std::move(JumpFailed);
8948 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8951 std::unique_ptr<Module>
M =
8952 std::make_unique<Module>(ModuleIdentifier,
Context);
8953 M->setMaterializer(R);
8956 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8957 IsImporting, Callbacks))
8958 return std::move(Err);
8960 if (MaterializeAll) {
8962 if (
Error Err =
M->materializeAll())
8963 return std::move(Err);
8966 if (
Error Err =
R->materializeForwardReferencedFunctions())
8967 return std::move(Err);
8970 return std::move(M);
8973Expected<std::unique_ptr<Module>>
8976 return getModuleImpl(
Context,
false, ShouldLazyLoadMetadata, IsImporting,
8986 std::function<
bool(
StringRef)> IsPrevailing,
8987 std::function<
void(
ValueInfo)> OnValueInfo) {
8992 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8993 ModulePath, IsPrevailing, OnValueInfo);
8994 return R.parseModule();
9001 return std::move(JumpFailed);
9003 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
9004 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
9005 ModuleIdentifier, 0);
9007 if (
Error Err = R.parseModule())
9008 return std::move(Err);
9010 return std::move(Index);
9016 return std::move(Err);
9022 return std::move(
E);
9024 switch (Entry.Kind) {
9027 return error(
"Malformed block");
9030 return std::make_pair(
false,
false);
9042 switch (MaybeBitCode.
get()) {
9048 assert(Flags <= 0xfff &&
"Unexpected bits in flag");
9050 bool EnableSplitLTOUnit = Flags & 0x8;
9051 bool UnifiedLTO = Flags & 0x200;
9052 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
9063 return std::move(JumpFailed);
9066 return std::move(Err);
9071 return std::move(E);
9073 switch (Entry.Kind) {
9075 return error(
"Malformed block");
9086 return Flags.takeError();
9096 return std::move(Err);
9103 return StreamFailed.takeError();
9113 if (MsOrErr->size() != 1)
9114 return error(
"Expected a single module");
9116 return (*MsOrErr)[0];
9119Expected<std::unique_ptr<Module>>
9121 bool ShouldLazyLoadMetadata,
bool IsImporting,
9127 return BM->getLazyModule(
Context, ShouldLazyLoadMetadata, IsImporting,
9133 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
9135 IsImporting, Callbacks);
9137 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
9143 return getModuleImpl(
Context,
true,
false,
false, Callbacks);
9155 return BM->parseModule(
Context, Callbacks);
9188 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
9197 return BM->getSummary();
9205 return BM->getLTOInfo();
9210 bool IgnoreEmptyThinLTOIndexFile) {
9215 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
bpf unwind BPF Unwind Lower
static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF, bool &HasTailCall)
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
static cl::opt< bool > PrintSummaryGUIDs("print-summary-global-ids", cl::init(false), cl::Hidden, cl::desc("Print the global id for each value when reading the module summary"))
static AtomicOrdering getDecodedOrdering(unsigned Val)
static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags)
static std::optional< CodeModel::Model > getDecodedCodeModel(unsigned Val)
static void setSpecialRefs(SmallVectorImpl< ValueInfo > &Refs, unsigned ROCnt, unsigned WOCnt)
static bool getDecodedDSOLocal(unsigned Val)
static bool convertToString(ArrayRef< uint64_t > Record, unsigned Idx, StrTy &Result)
Convert a string from a record into an std::string, return true on failure.
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
static void stripTBAA(Module *M)
static int getDecodedUnaryOpcode(unsigned Val, Type *Ty)
static Expected< std::string > readTriple(BitstreamCursor &Stream)
static void parseWholeProgramDevirtResolutionByArg(ArrayRef< uint64_t > Record, size_t &Slot, WholeProgramDevirtResolution &Wpd)
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
static CalleeInfo getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)
static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags)
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
static Expected< uint64_t > jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
static Expected< bool > hasObjCCategoryInModule(BitstreamCursor &Stream)
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags)
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs, uint64_t AttrIdx)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val, bool &IsElementwise)
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
static bool hasImplicitComdat(size_t Val)
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream)
static bool isConstExprSupported(const BitReaderOptions &Opts, const BitcodeConstant *BC)
static Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
static void parseWholeProgramDevirtResolution(ArrayRef< uint64_t > Record, StringRef Strtab, size_t &Slot, TypeIdSummary &TypeId)
static void inferDSOLocal(GlobalValue *GV)
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V)
static Expected< BitstreamCursor > initStream(MemoryBufferRef Buffer)
static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind)
static Expected< StringRef > readBlobInRecord(BitstreamCursor &Stream, unsigned Block, unsigned RecordID)
static Expected< std::string > readIdentificationBlock(BitstreamCursor &Stream)
Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the "epoch" encoded in the bit...
static Expected< std::pair< bool, bool > > getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, unsigned ID)
static int getDecodedCastOpcode(unsigned Val)
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase)
This file defines the DenseMap class.
Provides ErrorOr<T> smart pointer.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Module.h This file contains the declarations for the Module class.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
SmallVector< MachineOperand, 4 > Cond
Machine Check Debug Module
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
PowerPC Reduce CR logical Operation
This file contains the declarations for profiling metadata utility functions.
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallString class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Class for arbitrary precision integers.
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
PointerType * getType() const
Overload to return most specific pointer type.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
static bool isValidFailureOrdering(AtomicOrdering Ordering)
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
static bool isTypeAttrKind(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ None
No attributes have been set.
@ EndAttrKinds
Sentinel value useful for loops.
LLVM Basic Block Representation.
const Instruction & back() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
static BitInsertInst * Create(Value *Base, Value *Val, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Represents a module in a bitcode file.
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(StringRef)> IsPrevailing=nullptr, std::function< void(ValueInfo)> OnValueInfo=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
void push_back(Value *V, unsigned TypeID)
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
void shrinkTo(unsigned N)
unsigned getTypeID(unsigned ValNo) const
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
ArrayRef< uint8_t > getBitcodeBytes() const
Expected< word_t > Read(unsigned NumBits)
Expected< BitstreamEntry > advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Expected< BitstreamEntry > advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
Error SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block.
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
uint64_t getCurrentByteNo() const
LLVM_ABI Expected< std::optional< BitstreamBlockInfo > > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
Error JumpToBit(uint64_t NewBitNo)
Reset the stream to the specified bit number.
unsigned getAbbrevIDWidth() const
Return the number of bits used to encode an abbrev #.
bool canSkipToPos(size_t pos) const
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
@ MIN_BYTE_BITS
Minimum number of bits that can be specified.
@ MAX_BYTE_BITS
Maximum number of bits that can be specified Note that bit width is stored in the Type classes Subcla...
static LLVM_ABI ByteType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing a ByteType.
bool isInlineAsm() const
Check if this call is an inline asm statement.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo createFromIntValue(uint32_t Data)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
bool isFPPredicate() const
bool isIntPredicate() const
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI bool isElementTypeCompatible(Type *Ty)
Return true if a ConstantDataSequential can be formed with a vector or array of the specified element...
static Constant * getRaw(StringRef Data, uint64_t NumElements, Type *ElementTy)
getRaw() constructor - Return a constant with vector type with an element count and element type matc...
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static LLVM_ABI bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
static LLVM_ABI bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
LLVM_ABI bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static DeadOnReturnInfo createFromIntValue(uint64_t Data)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Base class for error info classes.
virtual std::string message() const
Return the error message as a string.
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
Convenience struct for specifying and reasoning about fast-math flags.
void setFast(bool B=true)
void setAllowContract(bool B=true)
void setAllowReciprocal(bool B=true)
void setNoSignedZeros(bool B=true)
void setNoNaNs(bool B=true)
void setAllowReassoc(bool B=true)
Flag setters.
void setApproxFunc(bool B=true)
void setNoInfs(bool B=true)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
void addCallsite(CallsiteInfo &&Callsite)
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
void addAlloc(AllocInfo &&Alloc)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
BasicBlockListType::iterator iterator
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
bool hasDefaultVisibility() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
bool hasExternalWeakLinkage() const
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
LLVM_ABI void setPartition(StringRef Part)
void setAttributes(AttributeSet A)
Set attribute list for this global.
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
std::vector< ConstraintInfo > ConstraintInfoVector
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
const char * getOpcodeName() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
@ MIN_INT_BITS
Minimum number of bits that can be specified.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
LLVM_ABI StringRef getString() const
ValueT lookup(const KeyT &Key) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
size_t getBufferSize() const
StringRef getBufferIdentifier() const
const char * getBufferStart() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static MemoryEffectsBase readOnly()
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
ModRefInfo getModRef(Location Loc) const
Get ModRefInfo for the given Location.
static MemoryEffectsBase errnoMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase createFromIntValue(uint32_t Data)
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static constexpr uint64_t BitcodeSummaryVersion
StringRef saveString(StringRef String)
LLVM_ABI void setFlags(uint64_t Flags)
CfiFunctionIndex & cfiFunctionDecls()
void addBlockCount(uint64_t C)
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
CfiFunctionIndex & cfiFunctionDefs()
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
unsigned addOrGetStackIdIndex(uint64_t StackId)
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
iterator_range< global_iterator > globals()
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
void append(StringRef RHS)
Append from a StringRef.
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
LLVM_ABI void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Triple - Helper class for working with autoconf configuration names.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
Type * getArrayElementType() const
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
bool isSized() const
Return true if it makes sense to take the size of this type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isStructTy() const
True if this is an instance of StructType.
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
const ParentTy * getParent() const
self_iterator getIterator()
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
@ BasicBlock
Various leaf nodes.
static const int NoAliasScopeDeclScopeArg
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
@ System
Synchronized with respect to all concurrently executing threads.
@ TYPE_CODE_OPAQUE_POINTER
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_CE_INBOUNDS_GEP
@ CST_CODE_INLINEASM_OLD3
@ CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_INLINEASM_OLD2
@ CST_CODE_CE_GEP_WITH_INRANGE
@ VST_CODE_COMBINED_ENTRY
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_INACCESSIBLEMEM_ONLY
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_SANITIZE_CONCURRENCY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_ALWAYS_UNIFORM
@ ATTR_KIND_LIKELY_MODULE_LOCAL
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_ATOMICRMW_OLD
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_INBOUNDS_GEP_OLD
@ FUNC_CODE_INST_STOREATOMIC_OLD
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_INST_LANDINGPAD_OLD
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_STORE_OLD
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_BITINSERT
@ FUNC_CODE_INST_CMPXCHG_OLD
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ PARAMATTR_CODE_ENTRY_OLD
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
constexpr bool IsBigEndianHost
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
StringMapEntry< Value * > ValueName
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
LLVM_ABI const std::error_category & BitcodeErrorCategory()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI void UpgradeInlineAsmString(std::string *AsmStr)
Upgrade comment in call to inline asm that represents an objc retain release marker.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
std::error_code make_error_code(BitcodeError E)
LLVM_ABI bool stripDebugInfo(Function &F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeAttributes(AttrBuilder &B)
Upgrade attributes that changed format or kind.
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
LLVM_ABI std::unique_ptr< Module > parseModule(const uint8_t *Data, size_t Size, LLVMContext &Context)
Fuzzer friendly interface for the llvm bitcode parser.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto uninitialized_copy(R &&Src, IterTy Dst)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
bool isa_and_nonnull(const Y &Val)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
LLVM_ABI void UpgradeOperandBundles(std::vector< OperandBundleDef > &OperandBundles)
Upgrade operand bundles (without knowing about their user instruction).
LLVM_ABI Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
const BitReaderOptions & getBitReaderOptions(const LLVMContext &C)
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
auto reverse(ContainerTy &&C)
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI std::string UpgradeDataLayoutString(StringRef DL, StringRef Triple)
Upgrade the datalayout string by adding a section for address space pointers.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ ArgMem
Access to memory via argument pointers.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
LLVM_ABI Instruction * UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, Instruction *&Temp)
This is an auto-upgrade for bitcast between pointers with different address spaces: the instruction i...
MaybeAlign decodeMaybeAlign(unsigned Value)
Dual operation of the encode function above.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
LLVM_ABI void UpgradeFunctionAttributes(Function &F)
Correct any IR that is relying on old function attribute behavior.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
LLVM_ABI Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
LLVM_ABI std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Basic information extracted from a bitcode module to be used for LTO.
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
Class to accumulate and hold information about a callee.
static constexpr DenormalFPEnv createFromIntValue(uint32_t Data)
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
ConstantRange Use
The range contains byte offsets from the parameter pointer which accessed by the function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const char * BranchWeights
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
std::optional< DataLayoutCallbackFuncTy > DataLayout
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
bool SkipDebugIntrinsicUpgrade
If true, do not auto-upgrade debug intrinsic calls (llvm.dbg.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
Kind
Specifies which kind of type check we should emit for this byte array.
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Struct that holds a reference to a particular GUID in a global value summary.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName