24#include "llvm/Config/llvm-config.h"
54#include "llvm/IR/IntrinsicsAArch64.h"
55#include "llvm/IR/IntrinsicsARM.h"
88#include <system_error>
98 "Print the global id for each value when reading the module summary"));
103 "Expand constant expressions to instructions for testing purposes"));
108 SWITCH_INST_MAGIC = 0x4B5
121 "file too small to contain bitcode header");
122 for (
unsigned C : {
'B',
'C'})
126 "file doesn't start with bitcode header");
128 return Res.takeError();
129 for (
unsigned C : {0x0, 0xC, 0xE, 0xD})
133 "file doesn't start with bitcode header");
135 return Res.takeError();
140 const unsigned char *BufPtr = (
const unsigned char *)Buffer.
getBufferStart();
141 const unsigned char *BufEnd = BufPtr + Buffer.
getBufferSize();
144 return error(
"Invalid bitcode signature");
150 return error(
"Invalid bitcode wrapper header");
154 return std::move(Err);
156 return std::move(Stream);
160template <
typename StrTy>
173 if (
F.isMaterializable())
176 I.setMetadata(LLVMContext::MD_tbaa,
nullptr);
184 return std::move(Err);
189 std::string ProducerIdentification;
196 switch (Entry.Kind) {
199 return error(
"Malformed block");
201 return ProducerIdentification;
212 switch (MaybeBitCode.
get()) {
214 return error(
"Invalid value");
222 Twine(
"Incompatible epoch: Bitcode '") +
Twine(epoch) +
241 switch (Entry.Kind) {
244 return error(
"Malformed block");
252 return std::move(Err);
264 return std::move(Err);
275 switch (Entry.Kind) {
278 return error(
"Malformed block");
290 switch (MaybeRecord.
get()) {
296 return error(
"Invalid section name record");
301 Segment = Segment.trim();
302 Section = Section.trim();
304 if (Segment ==
"__DATA" && Section.starts_with(
"__objc_catlist"))
306 if (Segment ==
"__OBJC" && Section.starts_with(
"__category"))
308 if (Segment ==
"__TEXT" && Section.starts_with(
"__swift"))
326 switch (Entry.Kind) {
328 return error(
"Malformed block");
338 return std::move(Err);
351 return std::move(Err);
364 switch (Entry.Kind) {
367 return error(
"Malformed block");
379 switch (MaybeRecord.
get()) {
384 return error(
"Invalid triple record");
403 switch (Entry.Kind) {
405 return error(
"Malformed block");
415 return std::move(Err);
422 return Skipped.takeError();
429class BitcodeReaderBase {
431 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
432 : Stream(std::
move(Stream)), Strtab(Strtab) {
433 this->Stream.setBlockInfo(&BlockInfo);
436 BitstreamBlockInfo BlockInfo;
437 BitstreamCursor Stream;
442 bool UseStrtab =
false;
444 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
449 std::pair<StringRef, ArrayRef<uint64_t>>
450 readNameFromStrtab(ArrayRef<uint64_t> Record);
452 Error readBlockInfo();
455 std::string ProducerIdentification;
462Error BitcodeReaderBase::error(
const Twine &Message) {
463 std::string FullMsg = Message.
str();
464 if (!ProducerIdentification.empty())
465 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
466 LLVM_VERSION_STRING
"')";
467 return ::error(FullMsg);
471BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
473 return error(
"Invalid version record");
474 unsigned ModuleVersion =
Record[0];
475 if (ModuleVersion > 2)
476 return error(
"Invalid value");
477 UseStrtab = ModuleVersion >= 2;
478 return ModuleVersion;
481std::pair<StringRef, ArrayRef<uint64_t>>
482BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
486 if (Record[0] + Record[1] > Strtab.
size())
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 {
583 Module *TheModule =
nullptr;
585 uint64_t NextUnreadBit = 0;
587 uint64_t LastFunctionBlockBit = 0;
588 bool SeenValueSymbolTable =
false;
589 uint64_t VSTOffset = 0;
591 std::vector<std::string> SectionTable;
592 std::vector<std::string> GCTable;
594 std::vector<Type *> TypeList;
598 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
605 DenseMap<std::pair<Type *, unsigned>,
unsigned> VirtualTypeIDs;
606 DenseMap<Function *, unsigned> FunctionTypeIDs;
611 BitcodeReaderValueList ValueList;
612 std::optional<MetadataLoader> MDLoader;
613 std::vector<Comdat *> ComdatList;
614 DenseSet<GlobalObject *> ImplicitComdatObjects;
617 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
618 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
620 struct FunctionOperandInfo {
622 unsigned PersonalityFn;
626 std::vector<FunctionOperandInfo> FunctionOperands;
630 std::vector<AttributeList> MAttributes;
633 std::map<unsigned, AttributeList> MAttributeGroups;
637 std::vector<BasicBlock*> FunctionBBs;
641 std::vector<Function*> FunctionsWithBodies;
645 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
646 UpdatedIntrinsicMap UpgradedIntrinsics;
651 bool SeenFirstFunctionBody =
false;
655 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
660 std::vector<uint64_t> DeferredMetadataInfo;
665 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
666 std::deque<Function *> BasicBlockFwdRefQueue;
673 std::vector<Function *> BackwardRefFunctions;
681 bool UseRelativeIDs =
false;
685 bool WillMaterializeAllForwardRefs =
false;
689 bool SeenDebugIntrinsic =
false;
690 bool SeenDebugRecord =
false;
693 TBAAVerifier TBAAVerifyHelper;
695 std::vector<std::string> BundleTags;
698 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
701 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
702 StringRef ProducerIdentification, LLVMContext &
Context);
704 Error materializeForwardReferencedFunctions();
706 Error materialize(GlobalValue *GV)
override;
707 Error materializeModule()
override;
708 std::vector<StructType *> getIdentifiedStructTypes()
const override;
712 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
713 bool IsImporting, ParserCallbacks Callbacks = {});
715 static uint64_t decodeSignRotatedValue(uint64_t V);
718 Error materializeMetadata()
override;
720 void setStripDebugInfo()
override;
723 std::vector<StructType *> IdentifiedStructTypes;
724 StructType *createIdentifiedStructType(LLVMContext &
Context, StringRef Name);
725 StructType *createIdentifiedStructType(LLVMContext &
Context);
727 static constexpr unsigned InvalidTypeID = ~0
u;
729 Type *getTypeByID(
unsigned ID);
730 Type *getPtrElementTypeByID(
unsigned ID);
731 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
732 unsigned getVirtualTypeID(
Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
735 Expected<Value *> materializeValue(
unsigned ValID, BasicBlock *InsertBB);
736 Expected<Constant *> getValueForInitializer(
unsigned ID);
738 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
739 BasicBlock *ConstExprInsertBB) {
746 return MDLoader->getMetadataFwdRefOrLoad(
ID);
750 if (
ID >= FunctionBBs.size())
return nullptr;
751 return FunctionBBs[
ID];
755 if (i-1 < MAttributes.size())
756 return MAttributes[i-1];
757 return AttributeList();
763 bool getValueTypePair(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
764 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
765 BasicBlock *ConstExprInsertBB) {
766 if (Slot ==
Record.size())
return true;
767 unsigned ValNo = (unsigned)Record[Slot++];
770 ValNo = InstNum - ValNo;
771 if (ValNo < InstNum) {
775 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
777 "Incorrect type ID stored for value");
778 return ResVal ==
nullptr;
780 if (Slot ==
Record.size())
783 TypeID = (unsigned)Record[Slot++];
784 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
786 return ResVal ==
nullptr;
789 bool getValueOrMetadata(
const SmallVectorImpl<uint64_t> &Record,
790 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
791 BasicBlock *ConstExprInsertBB) {
792 if (Slot ==
Record.size())
797 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
800 if (Slot ==
Record.size())
802 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
810 bool popValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
811 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
812 BasicBlock *ConstExprInsertBB) {
813 if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
821 bool getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
822 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
823 BasicBlock *ConstExprInsertBB) {
824 ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
825 return ResVal ==
nullptr;
830 Value *getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
831 unsigned InstNum,
Type *Ty,
unsigned TyID,
832 BasicBlock *ConstExprInsertBB) {
833 if (Slot ==
Record.size())
return nullptr;
834 unsigned ValNo = (unsigned)Record[Slot];
837 ValNo = InstNum - ValNo;
838 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
842 Value *getValueSigned(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
843 unsigned InstNum,
Type *Ty,
unsigned TyID,
844 BasicBlock *ConstExprInsertBB) {
845 if (Slot ==
Record.size())
return nullptr;
846 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
849 ValNo = InstNum - ValNo;
850 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
853 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
856 if (
Record.size() - OpNum < 2)
857 return error(
"Too few records for range");
859 unsigned LowerActiveWords =
Record[OpNum];
860 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
861 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
862 return error(
"Too few records for range");
865 OpNum += LowerActiveWords;
868 OpNum += UpperActiveWords;
871 int64_t
Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
872 int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
873 return ConstantRange(APInt(
BitWidth, Start,
true),
878 Expected<ConstantRange>
879 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,
unsigned &OpNum) {
880 if (
Record.size() - OpNum < 1)
881 return error(
"Too few records for range");
883 return readConstantRange(Record, OpNum,
BitWidth);
889 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
894 Error parseAlignmentValue(uint64_t
Exponent, MaybeAlign &Alignment);
895 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
897 ParserCallbacks Callbacks = {});
899 Error parseComdatRecord(ArrayRef<uint64_t> Record);
900 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
901 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
902 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
903 ArrayRef<uint64_t> Record);
905 Error parseAttributeBlock();
906 Error parseAttributeGroupBlock();
907 Error parseTypeTable();
908 Error parseTypeTableBody();
909 Error parseOperandBundleTags();
910 Error parseSyncScopeNames();
912 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
913 unsigned NameIndex, Triple &TT);
914 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta, Function *
F,
915 ArrayRef<uint64_t> Record);
917 Error parseGlobalValueSymbolTable();
918 Error parseConstants();
919 Error rememberAndSkipFunctionBodies();
920 Error rememberAndSkipFunctionBody();
922 Error rememberAndSkipMetadata();
924 Error parseFunctionBody(Function *
F);
925 Error globalCleanup();
926 Error resolveGlobalAndIndirectSymbolInits();
927 Error parseUseLists();
928 Error findFunctionInStream(
930 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
937class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
939 ModuleSummaryIndex &TheIndex;
943 bool SeenGlobalValSummary =
false;
946 bool SeenValueSymbolTable =
false;
950 uint64_t VSTOffset = 0;
960 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
961 ValueIdToValueInfoMap;
967 DenseMap<uint64_t, StringRef> ModuleIdMap;
970 std::string SourceFileName;
974 StringRef ModulePath;
982 std::vector<uint64_t> StackIds;
986 std::vector<uint64_t> RadixArray;
991 std::vector<unsigned> StackIdToIndex;
994 ModuleSummaryIndexBitcodeReader(
995 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
996 StringRef ModulePath,
1002 void setValueGUID(uint64_t ValueID, StringRef
ValueName,
1004 StringRef SourceFileName);
1005 Error parseValueSymbolTable(
1007 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1010 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1011 bool HasProfile,
bool HasRelBF);
1012 Error parseEntireSummary(
unsigned ID);
1013 Error parseModuleStringTable();
1014 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1015 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1017 std::vector<FunctionSummary::ParamAccess>
1018 parseParamAccesses(ArrayRef<uint64_t> Record);
1019 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1023 static constexpr unsigned UninitializedStackIdIndex =
1024 std::numeric_limits<unsigned>::max();
1026 unsigned getStackIdIndex(
unsigned LocalIndex) {
1027 unsigned &
Index = StackIdToIndex[LocalIndex];
1030 if (Index == UninitializedStackIdIndex)
1035 template <
bool AllowNullValueInfo = false>
1036 std::pair<ValueInfo, GlobalValue::GUID>
1037 getValueInfoFromValueId(
unsigned ValueId);
1039 void addThisModule();
1055 return std::error_code();
1061 : BitcodeReaderBase(
std::
move(Stream), Strtab), Context(Context),
1062 ValueList(this->Stream.SizeInBytes(),
1064 return materializeValue(
ValID, InsertBB);
1066 this->ProducerIdentification = std::string(ProducerIdentification);
1069Error BitcodeReader::materializeForwardReferencedFunctions() {
1070 if (WillMaterializeAllForwardRefs)
1074 WillMaterializeAllForwardRefs =
true;
1076 while (!BasicBlockFwdRefQueue.empty()) {
1077 Function *
F = BasicBlockFwdRefQueue.front();
1078 BasicBlockFwdRefQueue.pop_front();
1079 assert(
F &&
"Expected valid function");
1080 if (!BasicBlockFwdRefs.
count(
F))
1088 if (!
F->isMaterializable())
1089 return error(
"Never resolved function from blockaddress");
1092 if (
Error Err = materialize(
F))
1095 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1097 for (Function *
F : BackwardRefFunctions)
1098 if (
Error Err = materialize(
F))
1100 BackwardRefFunctions.clear();
1103 WillMaterializeAllForwardRefs =
false;
1168 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1169 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1170 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1171 Flags.NoInline = (RawFlags >> 4) & 0x1;
1172 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1173 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1174 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1175 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1176 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1192 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1);
1193 RawFlags = RawFlags >> 4;
1194 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1198 bool Live = (RawFlags & 0x2) || Version < 3;
1199 bool Local = (RawFlags & 0x4);
1200 bool AutoHide = (RawFlags & 0x8);
1203 Live,
Local, AutoHide, IK,
1204 NoRenameOnPromotion);
1210 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1211 (RawFlags & 0x4) ?
true :
false,
1215static std::pair<CalleeInfo::HotnessType, bool>
1219 bool HasTailCall = (RawFlags & 0x8);
1220 return {Hotness, HasTailCall};
1225 bool &HasTailCall) {
1226 static constexpr unsigned RelBlockFreqBits = 28;
1227 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1228 RelBF = RawFlags & RelBlockFreqMask;
1229 HasTailCall = (RawFlags & (1 << RelBlockFreqBits));
1254 case 0:
return false;
1255 case 1:
return true;
1317 bool IsFP = Ty->isFPOrFPVectorTy();
1319 if (!IsFP && !Ty->isIntOrIntVectorTy())
1326 return IsFP ? Instruction::FNeg : -1;
1331 bool IsFP = Ty->isFPOrFPVectorTy();
1333 if (!IsFP && !Ty->isIntOrIntVectorTy())
1340 return IsFP ? Instruction::FAdd : Instruction::Add;
1342 return IsFP ? Instruction::FSub : Instruction::Sub;
1344 return IsFP ? Instruction::FMul : Instruction::Mul;
1346 return IsFP ? -1 : Instruction::UDiv;
1348 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1350 return IsFP ? -1 : Instruction::URem;
1352 return IsFP ? Instruction::FRem : Instruction::SRem;
1354 return IsFP ? -1 : Instruction::Shl;
1356 return IsFP ? -1 : Instruction::LShr;
1358 return IsFP ? -1 : Instruction::AShr;
1360 return IsFP ? -1 : Instruction::And;
1362 return IsFP ? -1 : Instruction::Or;
1364 return IsFP ? -1 : Instruction::Xor;
1465Type *BitcodeReader::getTypeByID(
unsigned ID) {
1467 if (
ID >= TypeList.size())
1470 if (
Type *Ty = TypeList[
ID])
1475 return TypeList[
ID] = createIdentifiedStructType(
Context);
1478unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1479 auto It = ContainedTypeIDs.
find(
ID);
1480 if (It == ContainedTypeIDs.
end())
1481 return InvalidTypeID;
1483 if (Idx >= It->second.size())
1484 return InvalidTypeID;
1486 return It->second[Idx];
1489Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1490 if (
ID >= TypeList.size())
1497 return getTypeByID(getContainedTypeID(
ID, 0));
1500unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1501 ArrayRef<unsigned> ChildTypeIDs) {
1502 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1503 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1504 auto It = VirtualTypeIDs.
find(CacheKey);
1505 if (It != VirtualTypeIDs.
end()) {
1511 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1512 "Incorrect cached contained type IDs");
1516 unsigned TypeID = TypeList.size();
1517 TypeList.push_back(Ty);
1518 if (!ChildTypeIDs.
empty())
1539 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1553 if (Opcode == Instruction::GetElementPtr)
1557 case Instruction::FNeg:
1558 case Instruction::Select:
1559 case Instruction::ICmp:
1560 case Instruction::FCmp:
1567Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1568 BasicBlock *InsertBB) {
1570 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1572 return ValueList[StartValID];
1574 SmallDenseMap<unsigned, Value *> MaterializedValues;
1575 SmallVector<unsigned> Worklist;
1577 while (!Worklist.
empty()) {
1578 unsigned ValID = Worklist.
back();
1579 if (MaterializedValues.
count(ValID)) {
1585 if (ValID >= ValueList.
size() || !ValueList[ValID])
1586 return error(
"Invalid value ID");
1588 Value *
V = ValueList[ValID];
1591 MaterializedValues.
insert({ValID,
V});
1599 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1600 auto It = MaterializedValues.
find(OpID);
1601 if (It != MaterializedValues.
end())
1602 Ops.push_back(It->second);
1609 if (
Ops.size() != BC->getOperandIDs().size())
1611 std::reverse(
Ops.begin(),
Ops.end());
1628 switch (BC->Opcode) {
1629 case BitcodeConstant::ConstantPtrAuthOpcode: {
1632 return error(
"ptrauth key operand must be ConstantInt");
1636 return error(
"ptrauth disc operand must be ConstantInt");
1639 ConstOps.
size() > 4 ? ConstOps[4]
1644 "ptrauth deactivation symbol operand must be a pointer");
1647 DeactivationSymbol);
1650 case BitcodeConstant::NoCFIOpcode: {
1653 return error(
"no_cfi operand must be GlobalValue");
1657 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1660 return error(
"dso_local operand must be GlobalValue");
1664 case BitcodeConstant::BlockAddressOpcode: {
1667 return error(
"blockaddress operand must be a function");
1672 unsigned BBID = BC->BlockAddressBB;
1675 return error(
"Invalid ID");
1678 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1680 return error(
"Invalid ID");
1687 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1689 BasicBlockFwdRefQueue.push_back(Fn);
1690 if (FwdBBs.size() < BBID + 1)
1691 FwdBBs.resize(BBID + 1);
1699 case BitcodeConstant::ConstantStructOpcode: {
1701 if (
ST->getNumElements() != ConstOps.
size())
1702 return error(
"Invalid number of elements in struct initializer");
1704 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1705 if (
Op->getType() != Ty)
1706 return error(
"Incorrect type in struct initializer");
1711 case BitcodeConstant::ConstantArrayOpcode: {
1713 if (AT->getNumElements() != ConstOps.
size())
1714 return error(
"Invalid number of elements in array initializer");
1716 for (Constant *
Op : ConstOps)
1717 if (
Op->getType() != AT->getElementType())
1718 return error(
"Incorrect type in array initializer");
1723 case BitcodeConstant::ConstantVectorOpcode: {
1725 if (VT->getNumElements() != ConstOps.size())
1726 return error(
"Invalid number of elements in vector initializer");
1728 for (Constant *
Op : ConstOps)
1729 if (
Op->getType() != VT->getElementType())
1730 return error(
"Incorrect type in vector initializer");
1735 case Instruction::GetElementPtr:
1737 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1740 case Instruction::ExtractElement:
1743 case Instruction::InsertElement:
1747 case Instruction::ShuffleVector: {
1748 SmallVector<int, 16>
Mask;
1760 MaterializedValues.
insert({ValID,
C});
1766 return error(Twine(
"Value referenced by initializer is an unsupported "
1767 "constant expression of type ") +
1768 BC->getOpcodeName());
1774 BC->getType(),
"constexpr", InsertBB);
1777 "constexpr", InsertBB);
1780 Ops[1],
"constexpr", InsertBB);
1783 I->setHasNoSignedWrap();
1785 I->setHasNoUnsignedWrap();
1791 switch (BC->Opcode) {
1792 case BitcodeConstant::ConstantVectorOpcode: {
1793 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1796 Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1803 case BitcodeConstant::ConstantStructOpcode:
1804 case BitcodeConstant::ConstantArrayOpcode: {
1808 "constexpr.ins", InsertBB);
1812 case Instruction::ICmp:
1813 case Instruction::FCmp:
1816 "constexpr", InsertBB);
1818 case Instruction::GetElementPtr:
1824 case Instruction::Select:
1827 case Instruction::ExtractElement:
1830 case Instruction::InsertElement:
1834 case Instruction::ShuffleVector:
1835 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1843 MaterializedValues.
insert({ValID,
I});
1847 return MaterializedValues[StartValID];
1850Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1851 Expected<Value *> MaybeV = materializeValue(
ID,
nullptr);
1859StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1862 IdentifiedStructTypes.push_back(Ret);
1866StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1868 IdentifiedStructTypes.push_back(Ret);
1884 case Attribute::ZExt:
return 1 << 0;
1885 case Attribute::SExt:
return 1 << 1;
1886 case Attribute::NoReturn:
return 1 << 2;
1887 case Attribute::InReg:
return 1 << 3;
1888 case Attribute::StructRet:
return 1 << 4;
1889 case Attribute::NoUnwind:
return 1 << 5;
1890 case Attribute::NoAlias:
return 1 << 6;
1891 case Attribute::ByVal:
return 1 << 7;
1892 case Attribute::Nest:
return 1 << 8;
1893 case Attribute::ReadNone:
return 1 << 9;
1894 case Attribute::ReadOnly:
return 1 << 10;
1895 case Attribute::NoInline:
return 1 << 11;
1896 case Attribute::AlwaysInline:
return 1 << 12;
1897 case Attribute::OptimizeForSize:
return 1 << 13;
1898 case Attribute::StackProtect:
return 1 << 14;
1899 case Attribute::StackProtectReq:
return 1 << 15;
1900 case Attribute::Alignment:
return 31 << 16;
1902 case Attribute::NoRedZone:
return 1 << 22;
1903 case Attribute::NoImplicitFloat:
return 1 << 23;
1904 case Attribute::Naked:
return 1 << 24;
1905 case Attribute::InlineHint:
return 1 << 25;
1906 case Attribute::StackAlignment:
return 7 << 26;
1907 case Attribute::ReturnsTwice:
return 1 << 29;
1908 case Attribute::UWTable:
return 1 << 30;
1909 case Attribute::NonLazyBind:
return 1U << 31;
1910 case Attribute::SanitizeAddress:
return 1ULL << 32;
1911 case Attribute::MinSize:
return 1ULL << 33;
1912 case Attribute::NoDuplicate:
return 1ULL << 34;
1913 case Attribute::StackProtectStrong:
return 1ULL << 35;
1914 case Attribute::SanitizeThread:
return 1ULL << 36;
1915 case Attribute::SanitizeMemory:
return 1ULL << 37;
1916 case Attribute::NoBuiltin:
return 1ULL << 38;
1917 case Attribute::Returned:
return 1ULL << 39;
1918 case Attribute::Cold:
return 1ULL << 40;
1919 case Attribute::Builtin:
return 1ULL << 41;
1920 case Attribute::OptimizeNone:
return 1ULL << 42;
1921 case Attribute::InAlloca:
return 1ULL << 43;
1922 case Attribute::NonNull:
return 1ULL << 44;
1923 case Attribute::JumpTable:
return 1ULL << 45;
1924 case Attribute::Convergent:
return 1ULL << 46;
1925 case Attribute::SafeStack:
return 1ULL << 47;
1926 case Attribute::NoRecurse:
return 1ULL << 48;
1929 case Attribute::SwiftSelf:
return 1ULL << 51;
1930 case Attribute::SwiftError:
return 1ULL << 52;
1931 case Attribute::WriteOnly:
return 1ULL << 53;
1932 case Attribute::Speculatable:
return 1ULL << 54;
1933 case Attribute::StrictFP:
return 1ULL << 55;
1934 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1935 case Attribute::NoCfCheck:
return 1ULL << 57;
1936 case Attribute::OptForFuzzing:
return 1ULL << 58;
1937 case Attribute::ShadowCallStack:
return 1ULL << 59;
1938 case Attribute::SpeculativeLoadHardening:
1940 case Attribute::ImmArg:
1942 case Attribute::WillReturn:
1944 case Attribute::NoFree:
1960 if (
I == Attribute::Alignment)
1961 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
1962 else if (
I == Attribute::StackAlignment)
1963 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
1965 B.addTypeAttr(
I,
nullptr);
1979 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1981 "Alignment must be a power of two.");
1984 B.addAlignmentAttr(Alignment);
1986 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1987 (EncodedAttrs & 0xffff);
1989 if (AttrIdx == AttributeList::FunctionIndex) {
1992 if (Attrs & (1ULL << 9)) {
1994 Attrs &= ~(1ULL << 9);
1997 if (Attrs & (1ULL << 10)) {
1999 Attrs &= ~(1ULL << 10);
2002 if (Attrs & (1ULL << 49)) {
2004 Attrs &= ~(1ULL << 49);
2007 if (Attrs & (1ULL << 50)) {
2009 Attrs &= ~(1ULL << 50);
2012 if (Attrs & (1ULL << 53)) {
2014 Attrs &= ~(1ULL << 53);
2018 B.addMemoryAttr(ME);
2022 if (Attrs & (1ULL << 21)) {
2023 Attrs &= ~(1ULL << 21);
2030Error BitcodeReader::parseAttributeBlock() {
2034 if (!MAttributes.empty())
2035 return error(
"Invalid multiple blocks");
2037 SmallVector<uint64_t, 64>
Record;
2046 BitstreamEntry
Entry = MaybeEntry.
get();
2048 switch (
Entry.Kind) {
2051 return error(
"Malformed block");
2064 switch (MaybeRecord.
get()) {
2070 return error(
"Invalid parameter attribute record");
2072 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2078 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2082 for (uint64_t Val : Record)
2083 Attrs.push_back(MAttributeGroups[Val]);
2085 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2098 return Attribute::Alignment;
2100 return Attribute::AlwaysInline;
2102 return Attribute::Builtin;
2104 return Attribute::ByVal;
2106 return Attribute::InAlloca;
2108 return Attribute::Cold;
2110 return Attribute::Convergent;
2112 return Attribute::DisableSanitizerInstrumentation;
2114 return Attribute::ElementType;
2116 return Attribute::FnRetThunkExtern;
2118 return Attribute::Flatten;
2120 return Attribute::InlineHint;
2122 return Attribute::InReg;
2124 return Attribute::JumpTable;
2126 return Attribute::Memory;
2128 return Attribute::NoFPClass;
2130 return Attribute::MinSize;
2132 return Attribute::Naked;
2134 return Attribute::Nest;
2136 return Attribute::NoAlias;
2138 return Attribute::NoBuiltin;
2140 return Attribute::NoCallback;
2142 return Attribute::NoDivergenceSource;
2144 return Attribute::NoDuplicate;
2146 return Attribute::NoFree;
2148 return Attribute::NoImplicitFloat;
2150 return Attribute::NoInline;
2152 return Attribute::NoRecurse;
2154 return Attribute::NoMerge;
2156 return Attribute::NonLazyBind;
2158 return Attribute::NonNull;
2160 return Attribute::Dereferenceable;
2162 return Attribute::DereferenceableOrNull;
2164 return Attribute::AllocAlign;
2166 return Attribute::AllocKind;
2168 return Attribute::AllocSize;
2170 return Attribute::AllocatedPointer;
2172 return Attribute::NoRedZone;
2174 return Attribute::NoReturn;
2176 return Attribute::NoSync;
2178 return Attribute::NoCfCheck;
2180 return Attribute::NoProfile;
2182 return Attribute::SkipProfile;
2184 return Attribute::NoUnwind;
2186 return Attribute::NoSanitizeBounds;
2188 return Attribute::NoSanitizeCoverage;
2190 return Attribute::NullPointerIsValid;
2192 return Attribute::OptimizeForDebugging;
2194 return Attribute::OptForFuzzing;
2196 return Attribute::OptimizeForSize;
2198 return Attribute::OptimizeNone;
2200 return Attribute::ReadNone;
2202 return Attribute::ReadOnly;
2204 return Attribute::Returned;
2206 return Attribute::ReturnsTwice;
2208 return Attribute::SExt;
2210 return Attribute::Speculatable;
2212 return Attribute::StackAlignment;
2214 return Attribute::StackProtect;
2216 return Attribute::StackProtectReq;
2218 return Attribute::StackProtectStrong;
2220 return Attribute::SafeStack;
2222 return Attribute::ShadowCallStack;
2224 return Attribute::StrictFP;
2226 return Attribute::StructRet;
2228 return Attribute::SanitizeAddress;
2230 return Attribute::SanitizeHWAddress;
2232 return Attribute::SanitizeThread;
2234 return Attribute::SanitizeType;
2236 return Attribute::SanitizeMemory;
2238 return Attribute::SanitizeNumericalStability;
2240 return Attribute::SanitizeRealtime;
2242 return Attribute::SanitizeRealtimeBlocking;
2244 return Attribute::SanitizeAllocToken;
2246 return Attribute::SpeculativeLoadHardening;
2248 return Attribute::SwiftError;
2250 return Attribute::SwiftSelf;
2252 return Attribute::SwiftAsync;
2254 return Attribute::UWTable;
2256 return Attribute::VScaleRange;
2258 return Attribute::WillReturn;
2260 return Attribute::WriteOnly;
2262 return Attribute::ZExt;
2264 return Attribute::ImmArg;
2266 return Attribute::SanitizeMemTag;
2268 return Attribute::Preallocated;
2270 return Attribute::NoUndef;
2272 return Attribute::ByRef;
2274 return Attribute::MustProgress;
2276 return Attribute::Hot;
2278 return Attribute::PresplitCoroutine;
2280 return Attribute::Writable;
2282 return Attribute::CoroDestroyOnlyWhenComplete;
2284 return Attribute::DeadOnUnwind;
2286 return Attribute::Range;
2288 return Attribute::Initializes;
2290 return Attribute::CoroElideSafe;
2292 return Attribute::NoExt;
2294 return Attribute::Captures;
2296 return Attribute::DeadOnReturn;
2298 return Attribute::NoCreateUndefOrPoison;
2300 return Attribute::DenormalFPEnv;
2302 return Attribute::NoOutline;
2307 MaybeAlign &Alignment) {
2310 if (
Exponent > Value::MaxAlignmentExponent + 1)
2311 return error(
"Invalid alignment value");
2316Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2318 if (*Kind == Attribute::None)
2319 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2324 switch (EncodedKind) {
2348Error BitcodeReader::parseAttributeGroupBlock() {
2352 if (!MAttributeGroups.empty())
2353 return error(
"Invalid multiple blocks");
2355 SmallVector<uint64_t, 64>
Record;
2362 BitstreamEntry
Entry = MaybeEntry.
get();
2364 switch (
Entry.Kind) {
2367 return error(
"Malformed block");
2380 switch (MaybeRecord.
get()) {
2385 return error(
"Invalid grp record");
2387 uint64_t GrpID =
Record[0];
2388 uint64_t Idx =
Record[1];
2392 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2393 if (Record[i] == 0) {
2394 Attribute::AttrKind
Kind;
2395 uint64_t EncodedKind =
Record[++i];
2396 if (Idx == AttributeList::FunctionIndex &&
2405 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2411 if (Kind == Attribute::ByVal)
2412 B.addByValAttr(
nullptr);
2413 else if (Kind == Attribute::StructRet)
2414 B.addStructRetAttr(
nullptr);
2415 else if (Kind == Attribute::InAlloca)
2416 B.addInAllocaAttr(
nullptr);
2417 else if (Kind == Attribute::UWTable)
2418 B.addUWTableAttr(UWTableKind::Default);
2419 else if (Kind == Attribute::DeadOnReturn)
2420 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2421 else if (Attribute::isEnumAttrKind(Kind))
2422 B.addAttribute(Kind);
2424 return error(
"Not an enum attribute");
2425 }
else if (Record[i] == 1) {
2426 Attribute::AttrKind
Kind;
2427 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2429 if (!Attribute::isIntAttrKind(Kind))
2430 return error(
"Not an int attribute");
2431 if (Kind == Attribute::Alignment)
2432 B.addAlignmentAttr(Record[++i]);
2433 else if (Kind == Attribute::StackAlignment)
2434 B.addStackAlignmentAttr(Record[++i]);
2435 else if (Kind == Attribute::Dereferenceable)
2436 B.addDereferenceableAttr(Record[++i]);
2437 else if (Kind == Attribute::DereferenceableOrNull)
2438 B.addDereferenceableOrNullAttr(Record[++i]);
2439 else if (Kind == Attribute::DeadOnReturn)
2440 B.addDeadOnReturnAttr(
2442 else if (Kind == Attribute::AllocSize)
2443 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2444 else if (Kind == Attribute::VScaleRange)
2445 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2446 else if (Kind == Attribute::UWTable)
2448 else if (Kind == Attribute::AllocKind)
2449 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2450 else if (Kind == Attribute::Memory) {
2451 uint64_t EncodedME =
Record[++i];
2452 const uint8_t
Version = (EncodedME >> 56);
2464 B.addMemoryAttr(ME);
2469 EncodedME & 0x00FFFFFFFFFFFFFFULL));
2471 }
else if (Kind == Attribute::Captures)
2473 else if (Kind == Attribute::NoFPClass)
2476 else if (Kind == Attribute::DenormalFPEnv) {
2477 B.addDenormalFPEnvAttr(
2480 }
else if (Record[i] == 3 || Record[i] == 4) {
2482 SmallString<64> KindStr;
2483 SmallString<64> ValStr;
2485 while (Record[i] != 0 && i != e)
2487 assert(Record[i] == 0 &&
"Kind string not null terminated");
2492 while (Record[i] != 0 && i != e)
2494 assert(Record[i] == 0 &&
"Value string not null terminated");
2497 B.addAttribute(KindStr.
str(), ValStr.
str());
2498 }
else if (Record[i] == 5 || Record[i] == 6) {
2499 bool HasType =
Record[i] == 6;
2500 Attribute::AttrKind
Kind;
2501 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2503 if (!Attribute::isTypeAttrKind(Kind))
2504 return error(
"Not a type attribute");
2506 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2507 }
else if (Record[i] == 7) {
2508 Attribute::AttrKind
Kind;
2511 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2513 if (!Attribute::isConstantRangeAttrKind(Kind))
2514 return error(
"Not a ConstantRange attribute");
2516 Expected<ConstantRange> MaybeCR =
2517 readBitWidthAndConstantRange(Record, i);
2522 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2523 }
else if (Record[i] == 8) {
2524 Attribute::AttrKind
Kind;
2527 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2529 if (!Attribute::isConstantRangeListAttrKind(Kind))
2530 return error(
"Not a constant range list attribute");
2534 return error(
"Too few records for constant range list");
2535 unsigned RangeSize =
Record[i++];
2537 for (
unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2538 Expected<ConstantRange> MaybeCR =
2539 readConstantRange(Record, i,
BitWidth);
2547 return error(
"Invalid (unordered or overlapping) range list");
2548 B.addConstantRangeListAttr(Kind, Val);
2550 return error(
"Invalid attribute group entry");
2555 B.addMemoryAttr(ME);
2558 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2565Error BitcodeReader::parseTypeTable() {
2569 return parseTypeTableBody();
2572Error BitcodeReader::parseTypeTableBody() {
2573 if (!TypeList.empty())
2574 return error(
"Invalid multiple blocks");
2576 SmallVector<uint64_t, 64>
Record;
2577 unsigned NumRecords = 0;
2586 BitstreamEntry
Entry = MaybeEntry.
get();
2588 switch (
Entry.Kind) {
2591 return error(
"Malformed block");
2593 if (NumRecords != TypeList.size())
2594 return error(
"Malformed block");
2603 Type *ResultTy =
nullptr;
2604 SmallVector<unsigned> ContainedIDs;
2608 switch (MaybeRecord.
get()) {
2610 return error(
"Invalid value");
2615 return error(
"Invalid numentry record");
2616 TypeList.resize(Record[0]);
2619 ResultTy = Type::getVoidTy(
Context);
2622 ResultTy = Type::getHalfTy(
Context);
2625 ResultTy = Type::getBFloatTy(
Context);
2628 ResultTy = Type::getFloatTy(
Context);
2631 ResultTy = Type::getDoubleTy(
Context);
2634 ResultTy = Type::getX86_FP80Ty(
Context);
2637 ResultTy = Type::getFP128Ty(
Context);
2640 ResultTy = Type::getPPC_FP128Ty(
Context);
2643 ResultTy = Type::getLabelTy(
Context);
2646 ResultTy = Type::getMetadataTy(
Context);
2654 ResultTy = Type::getX86_AMXTy(
Context);
2657 ResultTy = Type::getTokenTy(
Context);
2661 return error(
"Invalid record");
2663 uint64_t NumBits =
Record[0];
2666 return error(
"Bitwidth for byte type out of range");
2672 return error(
"Invalid integer record");
2674 uint64_t NumBits =
Record[0];
2677 return error(
"Bitwidth for integer type out of range");
2684 return error(
"Invalid pointer record");
2688 ResultTy = getTypeByID(Record[0]);
2690 !PointerType::isValidElementType(ResultTy))
2691 return error(
"Invalid type");
2698 return error(
"Invalid opaque pointer record");
2707 return error(
"Invalid function record");
2709 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2710 if (
Type *
T = getTypeByID(Record[i]))
2716 ResultTy = getTypeByID(Record[2]);
2717 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2718 return error(
"Invalid type");
2721 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2727 return error(
"Invalid function record");
2729 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2730 if (
Type *
T = getTypeByID(Record[i])) {
2731 if (!FunctionType::isValidArgumentType(
T))
2732 return error(
"Invalid function argument type");
2739 ResultTy = getTypeByID(Record[1]);
2740 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2741 return error(
"Invalid type");
2744 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2749 return error(
"Invalid anon struct record");
2751 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2752 if (
Type *
T = getTypeByID(Record[i]))
2758 return error(
"Invalid type");
2765 return error(
"Invalid struct name record");
2770 return error(
"Invalid named struct record");
2772 if (NumRecords >= TypeList.size())
2773 return error(
"Invalid TYPE table");
2779 TypeList[NumRecords] =
nullptr;
2781 Res = createIdentifiedStructType(
Context, TypeName);
2785 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2786 if (
Type *
T = getTypeByID(Record[i]))
2792 return error(
"Invalid named struct record");
2801 return error(
"Invalid opaque type record");
2803 if (NumRecords >= TypeList.size())
2804 return error(
"Invalid TYPE table");
2810 TypeList[NumRecords] =
nullptr;
2812 Res = createIdentifiedStructType(
Context, TypeName);
2819 return error(
"Invalid target extension type record");
2821 if (NumRecords >= TypeList.size())
2822 return error(
"Invalid TYPE table");
2824 if (Record[0] >=
Record.size())
2825 return error(
"Too many type parameters");
2827 unsigned NumTys =
Record[0];
2829 SmallVector<unsigned, 8> IntParams;
2830 for (
unsigned i = 0; i < NumTys; i++) {
2831 if (
Type *
T = getTypeByID(Record[i + 1]))
2834 return error(
"Invalid type");
2837 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2838 if (Record[i] > UINT_MAX)
2839 return error(
"Integer parameter too large");
2844 if (
auto E = TTy.takeError())
2852 return error(
"Invalid array type record");
2853 ResultTy = getTypeByID(Record[1]);
2854 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2855 return error(
"Invalid type");
2857 ResultTy = ArrayType::get(ResultTy, Record[0]);
2862 return error(
"Invalid vector type record");
2864 return error(
"Invalid vector length");
2865 ResultTy = getTypeByID(Record[1]);
2866 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2867 return error(
"Invalid type");
2870 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2874 if (NumRecords >= TypeList.size())
2875 return error(
"Invalid TYPE table");
2876 if (TypeList[NumRecords])
2878 "Invalid TYPE table: Only named structs can be forward referenced");
2879 assert(ResultTy &&
"Didn't read a type?");
2880 TypeList[NumRecords] = ResultTy;
2881 if (!ContainedIDs.
empty())
2882 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2887Error BitcodeReader::parseOperandBundleTags() {
2891 if (!BundleTags.empty())
2892 return error(
"Invalid multiple blocks");
2894 SmallVector<uint64_t, 64>
Record;
2900 BitstreamEntry
Entry = MaybeEntry.
get();
2902 switch (
Entry.Kind) {
2905 return error(
"Malformed block");
2919 return error(
"Invalid operand bundle record");
2922 BundleTags.emplace_back();
2924 return error(
"Invalid operand bundle record");
2929Error BitcodeReader::parseSyncScopeNames() {
2934 return error(
"Invalid multiple synchronization scope names blocks");
2936 SmallVector<uint64_t, 64>
Record;
2941 BitstreamEntry
Entry = MaybeEntry.
get();
2943 switch (
Entry.Kind) {
2946 return error(
"Malformed block");
2949 return error(
"Invalid empty synchronization scope names block");
2963 return error(
"Invalid sync scope record");
2965 SmallString<16> SSN;
2967 return error(
"Invalid sync scope record");
2975Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2976 unsigned NameIndex, Triple &TT) {
2979 return error(
"Invalid record");
2980 unsigned ValueID =
Record[0];
2981 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
2982 return error(
"Invalid record");
2983 Value *
V = ValueList[ValueID];
2986 if (NameStr.contains(0))
2987 return error(
"Invalid value name");
2988 V->setName(NameStr);
2990 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
3003 return std::move(JumpFailed);
3009 return error(
"Expected value symbol table subblock");
3013void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
3015 ArrayRef<uint64_t> Record) {
3019 uint64_t FuncWordOffset =
Record[1] - 1;
3020 uint64_t FuncBitOffset = FuncWordOffset * 32;
3021 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3025 if (FuncBitOffset > LastFunctionBlockBit)
3026 LastFunctionBlockBit = FuncBitOffset;
3030Error BitcodeReader::parseGlobalValueSymbolTable() {
3031 unsigned FuncBitcodeOffsetDelta =
3037 SmallVector<uint64_t, 64>
Record;
3042 BitstreamEntry
Entry = MaybeEntry.
get();
3044 switch (
Entry.Kind) {
3047 return error(
"Malformed block");
3058 switch (MaybeRecord.
get()) {
3060 unsigned ValueID =
Record[0];
3061 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3062 return error(
"Invalid value reference in symbol table");
3063 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3073Error BitcodeReader::parseValueSymbolTable(uint64_t
Offset) {
3074 uint64_t CurrentBit;
3080 if (!MaybeCurrentBit)
3082 CurrentBit = MaybeCurrentBit.
get();
3085 if (
Error Err = parseGlobalValueSymbolTable())
3106 unsigned FuncBitcodeOffsetDelta =
3112 SmallVector<uint64_t, 64>
Record;
3123 BitstreamEntry
Entry = MaybeEntry.
get();
3125 switch (
Entry.Kind) {
3128 return error(
"Malformed block");
3144 switch (MaybeRecord.
get()) {
3148 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3156 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3164 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3169 return error(
"Invalid bbentry record");
3172 return error(
"Invalid bbentry record");
3184uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3194Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3195 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3196 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3197 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3199 GlobalInitWorklist.swap(GlobalInits);
3200 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3201 FunctionOperandWorklist.swap(FunctionOperands);
3203 while (!GlobalInitWorklist.empty()) {
3204 unsigned ValID = GlobalInitWorklist.back().second;
3205 if (ValID >= ValueList.
size()) {
3207 GlobalInits.push_back(GlobalInitWorklist.back());
3209 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3212 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3214 GlobalInitWorklist.pop_back();
3217 while (!IndirectSymbolInitWorklist.empty()) {
3218 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3219 if (ValID >= ValueList.
size()) {
3220 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3222 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3226 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3229 return error(
"Alias and aliasee types don't match");
3234 return error(
"Expected an alias or an ifunc");
3237 IndirectSymbolInitWorklist.pop_back();
3240 while (!FunctionOperandWorklist.empty()) {
3241 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3242 if (
Info.PersonalityFn) {
3243 unsigned ValID =
Info.PersonalityFn - 1;
3244 if (ValID < ValueList.
size()) {
3245 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3248 Info.F->setPersonalityFn(MaybeC.
get());
3249 Info.PersonalityFn = 0;
3253 unsigned ValID =
Info.Prefix - 1;
3254 if (ValID < ValueList.
size()) {
3255 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3258 Info.F->setPrefixData(MaybeC.
get());
3262 if (
Info.Prologue) {
3263 unsigned ValID =
Info.Prologue - 1;
3264 if (ValID < ValueList.
size()) {
3265 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3268 Info.F->setPrologueData(MaybeC.
get());
3272 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3273 FunctionOperands.push_back(Info);
3274 FunctionOperandWorklist.pop_back();
3283 BitcodeReader::decodeSignRotatedValue);
3285 return APInt(TypeBits, Words);
3288Error BitcodeReader::parseConstants() {
3296 unsigned Int32TyID = getVirtualTypeID(CurTy);
3297 unsigned CurTyID = Int32TyID;
3298 Type *CurElemTy =
nullptr;
3299 unsigned NextCstNo = ValueList.
size();
3307 switch (Entry.Kind) {
3310 return error(
"Malformed block");
3312 if (NextCstNo != ValueList.
size())
3313 return error(
"Invalid constant reference");
3324 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
3327 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3337 return error(
"Invalid settype record");
3338 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3339 return error(
"Invalid settype record");
3340 if (TypeList[Record[0]] == VoidType)
3341 return error(
"Invalid constant type");
3343 CurTy = TypeList[CurTyID];
3344 CurElemTy = getPtrElementTypeByID(CurTyID);
3348 return error(
"Invalid type for a constant null value");
3351 return error(
"Invalid type for a constant null value");
3356 return error(
"Invalid integer const record");
3361 return error(
"Invalid wide integer const record");
3364 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3365 V = ConstantInt::get(CurTy, VInt);
3370 return error(
"Invalid byte const record");
3371 V = ConstantByte::get(CurTy, decodeSignRotatedValue(Record[0]));
3375 return error(
"Invalid wide byte const record");
3378 APInt VByte =
readWideAPInt(Record, ScalarTy->getBitWidth());
3379 V = ConstantByte::get(CurTy, VByte);
3384 return error(
"Invalid float const record");
3387 if (ScalarTy->isHalfTy())
3388 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3389 APInt(16, (uint16_t)Record[0])));
3390 else if (ScalarTy->isBFloatTy())
3391 V = ConstantFP::get(
3392 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3393 else if (ScalarTy->isFloatTy())
3394 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3395 APInt(32, (uint32_t)Record[0])));
3396 else if (ScalarTy->isDoubleTy())
3397 V = ConstantFP::get(
3398 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3399 else if (ScalarTy->isX86_FP80Ty()) {
3401 uint64_t Rearrange[2];
3402 Rearrange[0] = (
Record[1] & 0xffffLL) | (Record[0] << 16);
3403 Rearrange[1] =
Record[0] >> 48;
3404 V = ConstantFP::get(
3405 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3406 }
else if (ScalarTy->isFP128Ty())
3407 V = ConstantFP::get(CurTy,
3408 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3409 else if (ScalarTy->isPPC_FP128Ty())
3410 V = ConstantFP::get(
3411 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3419 return error(
"Invalid aggregate record");
3421 SmallVector<unsigned, 16> Elts;
3425 V = BitcodeConstant::create(
3426 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3428 V = BitcodeConstant::create(
Alloc, CurTy,
3429 BitcodeConstant::ConstantArrayOpcode, Elts);
3431 V = BitcodeConstant::create(
3432 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3441 return error(
"Invalid string record");
3451 return error(
"Invalid data record");
3455 return error(
"Invalid type for value");
3458 SmallString<128> RawData;
3460 for (uint64_t Val : Record) {
3461 const char *Src =
reinterpret_cast<const char *
>(&Val);
3463 Src +=
sizeof(uint64_t) - EltBytes;
3464 RawData.
append(Src, Src + EltBytes);
3469 : ConstantDataArray::getRaw(RawData.str(),
Record.
size(), EltTy);
3474 return error(
"Invalid unary op constexpr record");
3479 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3485 return error(
"Invalid binary op constexpr record");
3491 if (
Record.size() >= 4) {
3492 if (
Opc == Instruction::Add ||
3493 Opc == Instruction::Sub ||
3494 Opc == Instruction::Mul ||
3495 Opc == Instruction::Shl) {
3500 }
else if (
Opc == Instruction::SDiv ||
3501 Opc == Instruction::UDiv ||
3502 Opc == Instruction::LShr ||
3503 Opc == Instruction::AShr) {
3508 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3509 {(unsigned)Record[1], (
unsigned)
Record[2]});
3515 return error(
"Invalid cast constexpr record");
3520 unsigned OpTyID =
Record[1];
3521 Type *OpTy = getTypeByID(OpTyID);
3523 return error(
"Invalid cast constexpr record");
3524 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3536 return error(
"Constant GEP record must have at least two elements");
3538 Type *PointeeType =
nullptr;
3542 PointeeType = getTypeByID(Record[OpNum++]);
3545 std::optional<ConstantRange>
InRange;
3549 unsigned InRangeIndex =
Op >> 1;
3555 Expected<ConstantRange> MaybeInRange =
3556 readBitWidthAndConstantRange(Record, OpNum);
3565 SmallVector<unsigned, 16> Elts;
3566 unsigned BaseTypeID =
Record[OpNum];
3567 while (OpNum !=
Record.size()) {
3568 unsigned ElTyID =
Record[OpNum++];
3569 Type *ElTy = getTypeByID(ElTyID);
3571 return error(
"Invalid getelementptr constexpr record");
3575 if (Elts.
size() < 1)
3576 return error(
"Invalid gep with no operands");
3580 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3581 BaseType = getTypeByID(BaseTypeID);
3586 return error(
"GEP base operand must be pointer or vector of pointer");
3589 PointeeType = getPtrElementTypeByID(BaseTypeID);
3591 return error(
"Missing element type for old-style constant GEP");
3594 V = BitcodeConstant::create(
3596 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3602 return error(
"Invalid select constexpr record");
3604 V = BitcodeConstant::create(
3605 Alloc, CurTy, Instruction::Select,
3606 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3612 return error(
"Invalid extractelement constexpr record");
3613 unsigned OpTyID =
Record[0];
3617 return error(
"Invalid extractelement constexpr record");
3619 if (
Record.size() == 4) {
3620 unsigned IdxTyID =
Record[2];
3621 Type *IdxTy = getTypeByID(IdxTyID);
3623 return error(
"Invalid extractelement constexpr record");
3629 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3630 {(unsigned)Record[1], IdxRecord});
3636 if (
Record.size() < 3 || !OpTy)
3637 return error(
"Invalid insertelement constexpr record");
3639 if (
Record.size() == 4) {
3640 unsigned IdxTyID =
Record[2];
3641 Type *IdxTy = getTypeByID(IdxTyID);
3643 return error(
"Invalid insertelement constexpr record");
3649 V = BitcodeConstant::create(
3650 Alloc, CurTy, Instruction::InsertElement,
3651 {(unsigned)Record[0], (
unsigned)
Record[1], IdxRecord});
3656 if (
Record.size() < 3 || !OpTy)
3657 return error(
"Invalid shufflevector constexpr record");
3658 V = BitcodeConstant::create(
3659 Alloc, CurTy, Instruction::ShuffleVector,
3660 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3667 if (
Record.size() < 4 || !RTy || !OpTy)
3668 return error(
"Invalid shufflevector constexpr record");
3669 V = BitcodeConstant::create(
3670 Alloc, CurTy, Instruction::ShuffleVector,
3671 {(unsigned)Record[1], (
unsigned)
Record[2], (unsigned)Record[3]});
3676 return error(
"Invalid cmp constexpt record");
3677 unsigned OpTyID =
Record[0];
3678 Type *OpTy = getTypeByID(OpTyID);
3680 return error(
"Invalid cmp constexpr record");
3681 V = BitcodeConstant::create(
3684 : Instruction::ICmp),
3685 (uint8_t)Record[3]},
3686 {(unsigned)Record[1], (
unsigned)
Record[2]});
3693 return error(
"Invalid inlineasm record");
3694 std::string AsmStr, ConstrStr;
3695 bool HasSideEffects =
Record[0] & 1;
3696 bool IsAlignStack =
Record[0] >> 1;
3697 unsigned AsmStrSize =
Record[1];
3698 if (2+AsmStrSize >=
Record.size())
3699 return error(
"Invalid inlineasm record");
3700 unsigned ConstStrSize =
Record[2+AsmStrSize];
3701 if (3+AsmStrSize+ConstStrSize >
Record.size())
3702 return error(
"Invalid inlineasm record");
3704 for (
unsigned i = 0; i != AsmStrSize; ++i)
3705 AsmStr += (
char)
Record[2+i];
3706 for (
unsigned i = 0; i != ConstStrSize; ++i)
3707 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3710 return error(
"Missing element type for old-style inlineasm");
3712 HasSideEffects, IsAlignStack);
3719 return error(
"Invalid inlineasm record");
3720 std::string AsmStr, ConstrStr;
3721 bool HasSideEffects =
Record[0] & 1;
3722 bool IsAlignStack = (
Record[0] >> 1) & 1;
3723 unsigned AsmDialect =
Record[0] >> 2;
3724 unsigned AsmStrSize =
Record[1];
3725 if (2+AsmStrSize >=
Record.size())
3726 return error(
"Invalid inlineasm record");
3727 unsigned ConstStrSize =
Record[2+AsmStrSize];
3728 if (3+AsmStrSize+ConstStrSize >
Record.size())
3729 return error(
"Invalid inlineasm record");
3731 for (
unsigned i = 0; i != AsmStrSize; ++i)
3732 AsmStr += (
char)
Record[2+i];
3733 for (
unsigned i = 0; i != ConstStrSize; ++i)
3734 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3737 return error(
"Missing element type for old-style inlineasm");
3739 HasSideEffects, IsAlignStack,
3746 return error(
"Invalid inlineasm record");
3748 std::string AsmStr, ConstrStr;
3749 bool HasSideEffects =
Record[OpNum] & 1;
3750 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3751 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3752 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3754 unsigned AsmStrSize =
Record[OpNum];
3756 if (OpNum + AsmStrSize >=
Record.size())
3757 return error(
"Invalid inlineasm record");
3758 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3759 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3760 return error(
"Invalid inlineasm record");
3762 for (
unsigned i = 0; i != AsmStrSize; ++i)
3763 AsmStr += (
char)
Record[OpNum + i];
3765 for (
unsigned i = 0; i != ConstStrSize; ++i)
3766 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3769 return error(
"Missing element type for old-style inlineasm");
3771 HasSideEffects, IsAlignStack,
3778 return error(
"Invalid inlineasm record");
3783 return error(
"Invalid inlineasm record");
3784 std::string AsmStr, ConstrStr;
3785 bool HasSideEffects =
Record[OpNum] & 1;
3786 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3787 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3788 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3790 unsigned AsmStrSize =
Record[OpNum];
3792 if (OpNum + AsmStrSize >=
Record.size())
3793 return error(
"Invalid inlineasm record");
3794 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3795 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3796 return error(
"Invalid inlineasm record");
3798 for (
unsigned i = 0; i != AsmStrSize; ++i)
3799 AsmStr += (
char)
Record[OpNum + i];
3801 for (
unsigned i = 0; i != ConstStrSize; ++i)
3802 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3804 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3810 return error(
"Invalid blockaddress record");
3811 unsigned FnTyID =
Record[0];
3812 Type *FnTy = getTypeByID(FnTyID);
3814 return error(
"Invalid blockaddress record");
3815 V = BitcodeConstant::create(
3817 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3823 return error(
"Invalid dso_local record");
3824 unsigned GVTyID =
Record[0];
3825 Type *GVTy = getTypeByID(GVTyID);
3827 return error(
"Invalid dso_local record");
3828 V = BitcodeConstant::create(
3829 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3834 return error(
"Invalid no_cfi record");
3835 unsigned GVTyID =
Record[0];
3836 Type *GVTy = getTypeByID(GVTyID);
3838 return error(
"Invalid no_cfi record");
3839 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3845 return error(
"Invalid ptrauth record");
3847 V = BitcodeConstant::create(
Alloc, CurTy,
3848 BitcodeConstant::ConstantPtrAuthOpcode,
3849 {(unsigned)Record[0], (
unsigned)
Record[1],
3850 (unsigned)Record[2], (
unsigned)
Record[3]});
3855 return error(
"Invalid ptrauth record");
3857 V = BitcodeConstant::create(
3858 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3859 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2],
3860 (
unsigned)
Record[3], (unsigned)Record[4]});
3865 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3872Error BitcodeReader::parseUseLists() {
3877 SmallVector<uint64_t, 64>
Record;
3883 BitstreamEntry
Entry = MaybeEntry.
get();
3885 switch (
Entry.Kind) {
3888 return error(
"Malformed block");
3902 switch (MaybeRecord.
get()) {
3910 if (RecordLength < 3)
3912 return error(
"Invalid uselist record");
3913 unsigned ID =
Record.pop_back_val();
3917 assert(
ID < FunctionBBs.size() &&
"Basic block not found");
3918 V = FunctionBBs[
ID];
3922 if (!
V->hasUseList())
3925 unsigned NumUses = 0;
3926 SmallDenseMap<const Use *, unsigned, 16> Order;
3927 for (
const Use &U :
V->materialized_uses()) {
3928 if (++NumUses >
Record.size())
3930 Order[&
U] =
Record[NumUses - 1];
3937 V->sortUseList([&](
const Use &L,
const Use &R) {
3948Error BitcodeReader::rememberAndSkipMetadata() {
3951 DeferredMetadataInfo.push_back(CurBit);
3959Error BitcodeReader::materializeMetadata() {
3960 for (uint64_t BitPos : DeferredMetadataInfo) {
3964 if (
Error Err = MDLoader->parseModuleMetadata())
3973 NamedMDNode *LinkerOpts =
3975 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
3980 DeferredMetadataInfo.clear();
3984void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
3988Error BitcodeReader::rememberAndSkipFunctionBody() {
3990 if (FunctionsWithBodies.empty())
3991 return error(
"Insufficient function protos");
3993 Function *Fn = FunctionsWithBodies.back();
3994 FunctionsWithBodies.pop_back();
3999 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4000 "Mismatch between VST and scanned function offsets");
4001 DeferredFunctionInfo[Fn] = CurBit;
4009Error BitcodeReader::globalCleanup() {
4011 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4013 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4014 return error(
"Malformed global initializer set");
4018 for (Function &
F : *TheModule) {
4019 MDLoader->upgradeDebugIntrinsics(
F);
4022 UpgradedIntrinsics[&
F] = NewFn;
4028 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4029 for (GlobalVariable &GV : TheModule->globals())
4031 UpgradedVariables.emplace_back(&GV, Upgraded);
4032 for (
auto &Pair : UpgradedVariables) {
4033 Pair.first->eraseFromParent();
4034 TheModule->insertGlobalVariable(Pair.second);
4039 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
4040 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4048Error BitcodeReader::rememberAndSkipFunctionBodies() {
4053 return error(
"Could not find function in stream");
4055 if (!SeenFirstFunctionBody)
4056 return error(
"Trying to materialize functions before seeing function blocks");
4060 assert(SeenValueSymbolTable);
4063 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4066 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4068 switch (
Entry.Kind) {
4070 return error(
"Expect SubBlock");
4074 return error(
"Expect function block");
4076 if (
Error Err = rememberAndSkipFunctionBody())
4085Error BitcodeReaderBase::readBlockInfo() {
4086 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4088 if (!MaybeNewBlockInfo)
4090 std::optional<BitstreamBlockInfo> NewBlockInfo =
4091 std::move(MaybeNewBlockInfo.
get());
4093 return error(
"Malformed block");
4094 BlockInfo = std::move(*NewBlockInfo);
4098Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4102 std::tie(Name, Record) = readNameFromStrtab(Record);
4105 return error(
"Invalid comdat record");
4107 std::string OldFormatName;
4110 return error(
"Invalid comdat record");
4111 unsigned ComdatNameSize =
Record[1];
4112 if (ComdatNameSize >
Record.size() - 2)
4113 return error(
"Comdat name size too large");
4114 OldFormatName.reserve(ComdatNameSize);
4115 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4116 OldFormatName += (
char)
Record[2 + i];
4117 Name = OldFormatName;
4119 Comdat *
C = TheModule->getOrInsertComdat(Name);
4120 C->setSelectionKind(SK);
4121 ComdatList.push_back(
C);
4135 Meta.NoAddress =
true;
4137 Meta.NoHWAddress =
true;
4141 Meta.IsDynInit =
true;
4145Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4153 std::tie(Name, Record) = readNameFromStrtab(Record);
4156 return error(
"Invalid global variable record");
4157 unsigned TyID =
Record[0];
4158 Type *Ty = getTypeByID(TyID);
4160 return error(
"Invalid global variable record");
4162 bool explicitType =
Record[1] & 2;
4168 return error(
"Invalid type for value");
4170 TyID = getContainedTypeID(TyID);
4171 Ty = getTypeByID(TyID);
4173 return error(
"Missing element type for old-style global");
4176 uint64_t RawLinkage =
Record[3];
4178 MaybeAlign Alignment;
4179 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4183 if (Record[5] - 1 >= SectionTable.size())
4184 return error(
"Invalid ID");
4193 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4201 bool ExternallyInitialized =
false;
4203 ExternallyInitialized =
Record[9];
4205 GlobalVariable *NewGV =
4215 if (
Record.size() > 10) {
4227 if (
unsigned InitID = Record[2])
4228 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4230 if (
Record.size() > 11) {
4231 if (
unsigned ComdatID = Record[11]) {
4232 if (ComdatID > ComdatList.size())
4233 return error(
"Invalid global variable comdat ID");
4234 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4237 ImplicitComdatObjects.
insert(NewGV);
4240 if (
Record.size() > 12) {
4245 if (
Record.size() > 13) {
4254 if (
Record.size() > 16 && Record[16]) {
4255 llvm::GlobalValue::SanitizerMetadata
Meta =
4260 if (
Record.size() > 17 && Record[17]) {
4264 return error(
"Invalid global variable code model");
4270void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4271 if (ValueTypeCallback) {
4272 (*ValueTypeCallback)(
4273 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4274 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4278Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4284 std::tie(Name, Record) = readNameFromStrtab(Record);
4287 return error(
"Invalid function record");
4288 unsigned FTyID =
Record[0];
4289 Type *FTy = getTypeByID(FTyID);
4291 return error(
"Invalid function record");
4293 FTyID = getContainedTypeID(FTyID, 0);
4294 FTy = getTypeByID(FTyID);
4296 return error(
"Missing element type for old-style function");
4300 return error(
"Invalid type for value");
4301 auto CC =
static_cast<CallingConv::ID
>(
Record[1]);
4302 if (CC & ~CallingConv::MaxID)
4303 return error(
"Invalid calling convention ID");
4305 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4311 AddrSpace, Name, TheModule);
4314 "Incorrect fully specified type provided for function");
4315 FunctionTypeIDs[
Func] = FTyID;
4317 Func->setCallingConv(CC);
4318 bool isProto =
Record[2];
4319 uint64_t RawLinkage =
Record[3];
4322 callValueTypeCallback(Func, FTyID);
4327 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4328 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4329 Attribute::InAlloca}) {
4330 if (!
Func->hasParamAttribute(i, Kind))
4333 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4336 Func->removeParamAttr(i, Kind);
4338 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4339 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4341 return error(
"Missing param element type for attribute upgrade");
4345 case Attribute::ByVal:
4346 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4348 case Attribute::StructRet:
4349 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4351 case Attribute::InAlloca:
4352 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4358 Func->addParamAttr(i, NewAttr);
4362 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4363 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4364 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4365 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4367 return error(
"Missing param element type for x86_intrcc upgrade");
4369 Func->addParamAttr(0, NewAttr);
4372 MaybeAlign Alignment;
4373 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4376 Func->setAlignment(*Alignment);
4378 if (Record[6] - 1 >= SectionTable.size())
4379 return error(
"Invalid ID");
4380 Func->setSection(SectionTable[Record[6] - 1]);
4384 if (!
Func->hasLocalLinkage())
4386 if (
Record.size() > 8 && Record[8]) {
4387 if (Record[8] - 1 >= GCTable.size())
4388 return error(
"Invalid ID");
4389 Func->setGC(GCTable[Record[8] - 1]);
4394 Func->setUnnamedAddr(UnnamedAddr);
4396 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4398 OperandInfo.Prologue =
Record[10];
4400 if (
Record.size() > 11) {
4402 if (!
Func->hasLocalLinkage()) {
4409 if (
Record.size() > 12) {
4410 if (
unsigned ComdatID = Record[12]) {
4411 if (ComdatID > ComdatList.size())
4412 return error(
"Invalid function comdat ID");
4413 Func->setComdat(ComdatList[ComdatID - 1]);
4416 ImplicitComdatObjects.
insert(Func);
4420 OperandInfo.Prefix =
Record[13];
4423 OperandInfo.PersonalityFn =
Record[14];
4425 if (
Record.size() > 15) {
4435 Record[17] + Record[18] <= Strtab.
size()) {
4436 Func->setPartition(StringRef(Strtab.
data() + Record[17], Record[18]));
4439 if (
Record.size() > 19) {
4440 MaybeAlign PrefAlignment;
4441 if (
Error Err = parseAlignmentValue(Record[19], PrefAlignment))
4443 Func->setPreferredAlignment(PrefAlignment);
4446 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4448 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4449 FunctionOperands.push_back(OperandInfo);
4454 Func->setIsMaterializable(
true);
4455 FunctionsWithBodies.push_back(Func);
4456 DeferredFunctionInfo[
Func] = 0;
4461Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4462 unsigned BitCode, ArrayRef<uint64_t> Record) {
4472 std::tie(Name, Record) = readNameFromStrtab(Record);
4475 if (
Record.size() < (3 + (
unsigned)NewRecord))
4476 return error(
"Invalid global indirect symbol record");
4481 return error(
"Invalid global indirect symbol record");
4487 return error(
"Invalid type for value");
4488 AddrSpace = PTy->getAddressSpace();
4490 Ty = getTypeByID(
TypeID);
4492 return error(
"Missing element type for old-style indirect symbol");
4494 AddrSpace =
Record[OpNum++];
4497 auto Val =
Record[OpNum++];
4506 nullptr, TheModule);
4510 if (OpNum !=
Record.size()) {
4511 auto VisInd = OpNum++;
4517 if (OpNum !=
Record.size()) {
4518 auto S =
Record[OpNum++];
4525 if (OpNum !=
Record.size())
4527 if (OpNum !=
Record.size())
4530 if (OpNum !=
Record.size())
4535 if (OpNum + 1 <
Record.size()) {
4537 if (Record[OpNum] + Record[OpNum + 1] > Strtab.
size())
4538 return error(
"Malformed partition, too large.");
4540 StringRef(Strtab.
data() + Record[OpNum], Record[OpNum + 1]));
4544 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4548Error BitcodeReader::parseModule(uint64_t ResumeBit,
4549 bool ShouldLazyLoadMetadata,
4550 ParserCallbacks Callbacks) {
4551 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4558 SmallVector<uint64_t, 64>
Record;
4562 bool ResolvedDataLayout =
false;
4567 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4569 auto ResolveDataLayout = [&]() ->
Error {
4570 if (ResolvedDataLayout)
4574 ResolvedDataLayout =
true;
4578 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4582 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4583 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4584 TentativeDataLayoutStr = *LayoutOverride;
4592 TheModule->setDataLayout(MaybeDL.
get());
4598 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4601 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4603 switch (
Entry.Kind) {
4605 return error(
"Malformed block");
4607 if (
Error Err = ResolveDataLayout())
4609 return globalCleanup();
4618 if (
Error Err = readBlockInfo())
4622 if (
Error Err = parseAttributeBlock())
4626 if (
Error Err = parseAttributeGroupBlock())
4630 if (
Error Err = parseTypeTable())
4634 if (!SeenValueSymbolTable) {
4640 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4641 if (
Error Err = parseValueSymbolTable())
4643 SeenValueSymbolTable =
true;
4653 if (
Error Err = parseConstants())
4655 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4659 if (ShouldLazyLoadMetadata) {
4660 if (
Error Err = rememberAndSkipMetadata())
4664 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4665 if (
Error Err = MDLoader->parseModuleMetadata())
4669 if (
Error Err = MDLoader->parseMetadataKinds())
4673 if (
Error Err = ResolveDataLayout())
4678 if (!SeenFirstFunctionBody) {
4679 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4680 if (
Error Err = globalCleanup())
4682 SeenFirstFunctionBody =
true;
4685 if (VSTOffset > 0) {
4689 if (!SeenValueSymbolTable) {
4690 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4692 SeenValueSymbolTable =
true;
4714 if (
Error Err = rememberAndSkipFunctionBody())
4721 if (SeenValueSymbolTable) {
4725 return globalCleanup();
4729 if (
Error Err = parseUseLists())
4733 if (
Error Err = parseOperandBundleTags())
4737 if (
Error Err = parseSyncScopeNames())
4749 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
4752 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4755 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4758 UseRelativeIDs = *VersionOrErr >= 1;
4762 if (ResolvedDataLayout)
4763 return error(
"target triple too late in module");
4766 return error(
"Invalid triple record");
4767 TheModule->setTargetTriple(Triple(std::move(S)));
4771 if (ResolvedDataLayout)
4772 return error(
"datalayout too late in module");
4774 return error(
"Invalid data layout record");
4780 return error(
"Invalid asm record");
4781 TheModule->setModuleInlineAsm(S);
4788 return error(
"Invalid deplib record");
4795 return error(
"Invalid section name record");
4796 SectionTable.push_back(S);
4802 return error(
"Invalid gcname record");
4803 GCTable.push_back(S);
4807 if (
Error Err = parseComdatRecord(Record))
4816 if (
Error Err = parseGlobalVarRecord(Record))
4820 if (
Error Err = ResolveDataLayout())
4822 if (
Error Err = parseFunctionRecord(Record))
4828 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4834 return error(
"Invalid vstoffset record");
4838 VSTOffset =
Record[0] - 1;
4844 return error(
"Invalid source filename record");
4845 TheModule->setSourceFileName(
ValueName);
4850 this->ValueTypeCallback = std::nullopt;
4854Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4856 ParserCallbacks Callbacks) {
4858 MetadataLoaderCallbacks MDCallbacks;
4859 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(
ID); };
4861 return getContainedTypeID(
I, J);
4864 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4865 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4868Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4870 return error(
"Load/Store operand is not a pointer type");
4871 if (!PointerType::isLoadableOrStorableType(ValType))
4872 return error(
"Cannot load/store from pointer");
4876Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4877 ArrayRef<unsigned> ArgTyIDs) {
4879 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4880 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4881 Attribute::InAlloca}) {
4882 if (!
Attrs.hasParamAttr(i, Kind) ||
4883 Attrs.getParamAttr(i, Kind).getValueAsType())
4886 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4888 return error(
"Missing element type for typed attribute upgrade");
4892 case Attribute::ByVal:
4893 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4895 case Attribute::StructRet:
4896 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4898 case Attribute::InAlloca:
4899 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4912 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
4916 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
4917 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4919 return error(
"Missing element type for inline asm upgrade");
4922 Attribute::get(
Context, Attribute::ElementType, ElemTy));
4930 case Intrinsic::preserve_array_access_index:
4931 case Intrinsic::preserve_struct_access_index:
4932 case Intrinsic::aarch64_ldaxr:
4933 case Intrinsic::aarch64_ldxr:
4934 case Intrinsic::aarch64_stlxr:
4935 case Intrinsic::aarch64_stxr:
4936 case Intrinsic::arm_ldaex:
4937 case Intrinsic::arm_ldrex:
4938 case Intrinsic::arm_stlex:
4939 case Intrinsic::arm_strex: {
4942 case Intrinsic::aarch64_stlxr:
4943 case Intrinsic::aarch64_stxr:
4944 case Intrinsic::arm_stlex:
4945 case Intrinsic::arm_strex:
4952 if (!
Attrs.getParamElementType(ArgNo)) {
4953 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4955 return error(
"Missing element type for elementtype upgrade");
4970Error BitcodeReader::parseFunctionBody(Function *
F) {
4975 if (MDLoader->hasFwdRefs())
4976 return error(
"Invalid function metadata: incoming forward references");
4978 InstructionList.
clear();
4979 unsigned ModuleValueListSize = ValueList.
size();
4980 unsigned ModuleMDLoaderSize = MDLoader->size();
4984 unsigned FTyID = FunctionTypeIDs[
F];
4985 for (Argument &
I :
F->args()) {
4986 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4987 assert(
I.getType() == getTypeByID(ArgTyID) &&
4988 "Incorrect fully specified type for Function Argument");
4992 unsigned NextValueNo = ValueList.
size();
4994 unsigned CurBBNo = 0;
4999 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
5003 auto getLastInstruction = [&]() -> Instruction * {
5004 if (CurBB && !CurBB->
empty())
5005 return &CurBB->
back();
5006 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5007 !FunctionBBs[CurBBNo - 1]->
empty())
5008 return &FunctionBBs[CurBBNo - 1]->back();
5012 std::vector<OperandBundleDef> OperandBundles;
5015 SmallVector<uint64_t, 64>
Record;
5018 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
5021 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
5023 switch (
Entry.Kind) {
5025 return error(
"Malformed block");
5027 goto OutOfRecordLoop;
5036 if (
Error Err = parseConstants())
5038 NextValueNo = ValueList.
size();
5041 if (
Error Err = parseValueSymbolTable())
5045 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
5049 assert(DeferredMetadataInfo.empty() &&
5050 "Must read all module-level metadata before function-level");
5051 if (
Error Err = MDLoader->parseFunctionMetadata())
5055 if (
Error Err = parseUseLists())
5069 unsigned ResTypeID = InvalidTypeID;
5070 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
5073 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5075 return error(
"Invalid value");
5077 if (
Record.empty() || Record[0] == 0)
5078 return error(
"Invalid declareblocks record");
5080 FunctionBBs.resize(Record[0]);
5083 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5084 if (BBFRI == BasicBlockFwdRefs.
end()) {
5085 for (BasicBlock *&BB : FunctionBBs)
5088 auto &BBRefs = BBFRI->second;
5090 if (BBRefs.size() > FunctionBBs.size())
5091 return error(
"Invalid ID");
5092 assert(!BBRefs.empty() &&
"Unexpected empty array");
5093 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5094 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5096 if (
I < RE && BBRefs[
I]) {
5097 BBRefs[
I]->insertInto(
F);
5098 FunctionBBs[
I] = BBRefs[
I];
5104 BasicBlockFwdRefs.
erase(BBFRI);
5107 CurBB = FunctionBBs[0];
5114 return error(
"Invalid blockaddr users record");
5128 for (uint64_t ValID : Record)
5130 BackwardRefFunctions.push_back(
F);
5132 return error(
"Invalid blockaddr users record");
5139 I = getLastInstruction();
5142 return error(
"Invalid debug_loc_again record");
5143 I->setDebugLoc(LastLoc);
5148 I = getLastInstruction();
5150 return error(
"Invalid debug loc record");
5155 uint64_t AtomGroup =
Record.size() == 7 ?
Record[5] : 0;
5158 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5161 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5163 return error(
"Invalid debug loc record");
5167 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5169 return error(
"Invalid debug loc record");
5172 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5173 isImplicitCode, AtomGroup, AtomRank);
5174 I->setDebugLoc(LastLoc);
5182 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5184 return error(
"Invalid unary operator record");
5188 return error(
"Invalid unary operator record");
5192 if (OpNum <
Record.size()) {
5196 I->setFastMathFlags(FMF);
5205 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5209 return error(
"Invalid binary operator record");
5213 return error(
"Invalid binary operator record");
5217 if (OpNum <
Record.size()) {
5218 if (
Opc == Instruction::Add ||
5219 Opc == Instruction::Sub ||
5220 Opc == Instruction::Mul ||
5221 Opc == Instruction::Shl) {
5226 }
else if (
Opc == Instruction::SDiv ||
5227 Opc == Instruction::UDiv ||
5228 Opc == Instruction::LShr ||
5229 Opc == Instruction::AShr) {
5232 }
else if (
Opc == Instruction::Or) {
5238 I->setFastMathFlags(FMF);
5247 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5248 OpNum + 1 >
Record.size())
5249 return error(
"Invalid cast record");
5251 ResTypeID =
Record[OpNum++];
5252 Type *ResTy = getTypeByID(ResTypeID);
5255 if (
Opc == -1 || !ResTy)
5256 return error(
"Invalid cast record");
5261 assert(CurBB &&
"No current BB?");
5267 return error(
"Invalid cast");
5271 if (OpNum <
Record.size()) {
5272 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5275 }
else if (
Opc == Instruction::Trunc) {
5284 I->setFastMathFlags(FMF);
5303 Ty = getTypeByID(TyID);
5307 TyID = InvalidTypeID;
5312 unsigned BasePtrTypeID;
5313 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5315 return error(
"Invalid gep record");
5318 TyID = getContainedTypeID(BasePtrTypeID);
5319 if (
BasePtr->getType()->isVectorTy())
5320 TyID = getContainedTypeID(TyID);
5321 Ty = getTypeByID(TyID);
5324 SmallVector<Value*, 16> GEPIdx;
5325 while (OpNum !=
Record.size()) {
5328 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5329 return error(
"Invalid gep record");
5340 unsigned SubType = 0;
5341 if (GTI.isStruct()) {
5343 Idx->getType()->isVectorTy()
5345 :
cast<ConstantInt>(Idx);
5348 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5355 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5356 if (
I->getType()->isVectorTy())
5357 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5360 GEP->setNoWrapFlags(NW);
5369 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5370 return error(
"Invalid extractvalue record");
5373 unsigned RecSize =
Record.size();
5374 if (OpNum == RecSize)
5375 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5377 SmallVector<unsigned, 4> EXTRACTVALIdx;
5378 ResTypeID = AggTypeID;
5379 for (; OpNum != RecSize; ++OpNum) {
5384 if (!IsStruct && !IsArray)
5385 return error(
"EXTRACTVAL: Invalid type");
5386 if ((
unsigned)Index != Index)
5387 return error(
"Invalid value");
5389 return error(
"EXTRACTVAL: Invalid struct index");
5391 return error(
"EXTRACTVAL: Invalid array index");
5392 EXTRACTVALIdx.
push_back((
unsigned)Index);
5396 ResTypeID = getContainedTypeID(ResTypeID, Index);
5399 ResTypeID = getContainedTypeID(ResTypeID);
5413 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5414 return error(
"Invalid insertvalue record");
5417 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5418 return error(
"Invalid insertvalue record");
5420 unsigned RecSize =
Record.size();
5421 if (OpNum == RecSize)
5422 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5424 SmallVector<unsigned, 4> INSERTVALIdx;
5426 for (; OpNum != RecSize; ++OpNum) {
5431 if (!IsStruct && !IsArray)
5432 return error(
"INSERTVAL: Invalid type");
5433 if ((
unsigned)Index != Index)
5434 return error(
"Invalid value");
5436 return error(
"INSERTVAL: Invalid struct index");
5438 return error(
"INSERTVAL: Invalid array index");
5440 INSERTVALIdx.
push_back((
unsigned)Index);
5448 return error(
"Inserted value type doesn't match aggregate type");
5451 ResTypeID = AggTypeID;
5463 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5465 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5467 popValue(Record, OpNum, NextValueNo, CondType,
5468 getVirtualTypeID(CondType),
Cond, CurBB))
5469 return error(
"Invalid select record");
5482 unsigned ValTypeID, CondTypeID;
5483 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5485 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5487 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5488 return error(
"Invalid vector select record");
5491 if (VectorType* vector_type =
5494 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5495 return error(
"Invalid type for value");
5499 return error(
"Invalid type for value");
5503 ResTypeID = ValTypeID;
5508 I->setFastMathFlags(FMF);
5516 unsigned VecTypeID, IdxTypeID;
5517 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5518 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5519 return error(
"Invalid extractelement record");
5521 return error(
"Invalid type for value");
5523 ResTypeID = getContainedTypeID(VecTypeID);
5530 Value *Vec, *Elt, *Idx;
5531 unsigned VecTypeID, IdxTypeID;
5532 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5533 return error(
"Invalid insertelement record");
5535 return error(
"Invalid type for value");
5536 if (popValue(Record, OpNum, NextValueNo,
5538 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5539 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5540 return error(
"Invalid insert element record");
5542 ResTypeID = VecTypeID;
5550 unsigned Vec1TypeID;
5551 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5553 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5555 return error(
"Invalid shufflevector record");
5557 unsigned MaskTypeID;
5558 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5559 return error(
"Invalid shufflevector record");
5561 return error(
"Invalid type for value");
5563 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5565 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5580 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5581 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5583 return error(
"Invalid comparison record");
5585 if (OpNum >=
Record.size())
5587 "Invalid record: operand number exceeded available operands");
5592 if (IsFP &&
Record.size() > OpNum+1)
5597 return error(
"Invalid fcmp predicate");
5598 I =
new FCmpInst(PredVal,
LHS,
RHS);
5601 return error(
"Invalid icmp predicate");
5602 I =
new ICmpInst(PredVal,
LHS,
RHS);
5603 if (
Record.size() > OpNum + 1 &&
5608 if (OpNum + 1 !=
Record.size())
5609 return error(
"Invalid comparison record");
5611 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5613 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5616 I->setFastMathFlags(FMF);
5633 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5634 return error(
"Invalid ret record");
5635 if (OpNum !=
Record.size())
5636 return error(
"Invalid ret record");
5644 return error(
"Invalid br record");
5645 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5647 return error(
"Invalid br record");
5649 if (
Record.size() == 1) {
5654 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5656 Value *
Cond = getValue(Record, 2, NextValueNo, CondType,
5657 getVirtualTypeID(CondType), CurBB);
5658 if (!FalseDest || !
Cond)
5659 return error(
"Invalid br record");
5667 return error(
"Invalid cleanupret record");
5670 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5671 getVirtualTypeID(TokenTy), CurBB);
5673 return error(
"Invalid cleanupret record");
5675 if (
Record.size() == 2) {
5676 UnwindDest = getBasicBlock(Record[Idx++]);
5678 return error(
"Invalid cleanupret record");
5687 return error(
"Invalid catchret record");
5690 Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5691 getVirtualTypeID(TokenTy), CurBB);
5693 return error(
"Invalid catchret record");
5694 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5696 return error(
"Invalid catchret record");
5705 return error(
"Invalid catchswitch record");
5710 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5711 getVirtualTypeID(TokenTy), CurBB);
5713 return error(
"Invalid catchswitch record");
5715 unsigned NumHandlers =
Record[Idx++];
5718 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5719 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5721 return error(
"Invalid catchswitch record");
5726 if (Idx + 1 ==
Record.size()) {
5727 UnwindDest = getBasicBlock(Record[Idx++]);
5729 return error(
"Invalid catchswitch record");
5732 if (
Record.size() != Idx)
5733 return error(
"Invalid catchswitch record");
5737 for (BasicBlock *Handler : Handlers)
5738 CatchSwitch->addHandler(Handler);
5740 ResTypeID = getVirtualTypeID(
I->getType());
5748 return error(
"Invalid catchpad/cleanuppad record");
5753 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5754 getVirtualTypeID(TokenTy), CurBB);
5756 return error(
"Invalid catchpad/cleanuppad record");
5758 unsigned NumArgOperands =
Record[Idx++];
5760 SmallVector<Value *, 2>
Args;
5761 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5764 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5765 return error(
"Invalid catchpad/cleanuppad record");
5766 Args.push_back(Val);
5769 if (
Record.size() != Idx)
5770 return error(
"Invalid catchpad/cleanuppad record");
5776 ResTypeID = getVirtualTypeID(
I->getType());
5782 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5788 unsigned OpTyID =
Record[1];
5789 Type *OpTy = getTypeByID(OpTyID);
5792 Value *
Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
5795 return error(
"Invalid switch record");
5797 unsigned NumCases =
Record[4];
5802 unsigned CurIdx = 5;
5803 for (
unsigned i = 0; i != NumCases; ++i) {
5805 unsigned NumItems =
Record[CurIdx++];
5806 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5807 bool isSingleNumber =
Record[CurIdx++];
5810 unsigned ActiveWords = 1;
5811 if (ValueBitWidth > 64)
5812 ActiveWords =
Record[CurIdx++];
5815 CurIdx += ActiveWords;
5817 if (!isSingleNumber) {
5819 if (ValueBitWidth > 64)
5820 ActiveWords =
Record[CurIdx++];
5823 CurIdx += ActiveWords;
5834 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5835 for (ConstantInt *Cst : CaseVals)
5836 SI->addCase(Cst, DestBB);
5845 return error(
"Invalid switch record");
5846 unsigned OpTyID =
Record[0];
5847 Type *OpTy = getTypeByID(OpTyID);
5848 Value *
Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5851 return error(
"Invalid switch record");
5852 unsigned NumCases = (
Record.size()-3)/2;
5855 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
5857 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
5858 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5859 if (!CaseVal || !DestBB) {
5861 return error(
"Invalid switch record");
5863 SI->addCase(CaseVal, DestBB);
5870 return error(
"Invalid indirectbr record");
5871 unsigned OpTyID =
Record[0];
5872 Type *OpTy = getTypeByID(OpTyID);
5873 Value *
Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5875 return error(
"Invalid indirectbr record");
5876 unsigned NumDests =
Record.size()-2;
5879 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
5880 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5884 return error(
"Invalid indirectbr record");
5894 return error(
"Invalid invoke record");
5897 unsigned CCInfo =
Record[OpNum++];
5898 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5899 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5901 unsigned FTyID = InvalidTypeID;
5902 FunctionType *FTy =
nullptr;
5903 if ((CCInfo >> 13) & 1) {
5907 return error(
"Explicit invoke type is not a function type");
5911 unsigned CalleeTypeID;
5912 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5914 return error(
"Invalid invoke record");
5918 return error(
"Callee is not a pointer");
5920 FTyID = getContainedTypeID(CalleeTypeID);
5923 return error(
"Callee is not of pointer to function type");
5925 if (
Record.size() < FTy->getNumParams() + OpNum)
5926 return error(
"Insufficient operands to call");
5928 SmallVector<Value*, 16>
Ops;
5929 SmallVector<unsigned, 16> ArgTyIDs;
5930 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5931 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5932 Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5936 return error(
"Invalid invoke record");
5939 if (!FTy->isVarArg()) {
5940 if (
Record.size() != OpNum)
5941 return error(
"Invalid invoke record");
5944 while (OpNum !=
Record.size()) {
5947 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5948 return error(
"Invalid invoke record");
5955 if (!OperandBundles.empty())
5960 ResTypeID = getContainedTypeID(FTyID);
5961 OperandBundles.clear();
5964 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
5975 Value *Val =
nullptr;
5977 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5978 return error(
"Invalid resume record");
5987 unsigned CCInfo =
Record[OpNum++];
5989 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5990 unsigned NumIndirectDests =
Record[OpNum++];
5991 SmallVector<BasicBlock *, 16> IndirectDests;
5992 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
5993 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
5995 unsigned FTyID = InvalidTypeID;
5996 FunctionType *FTy =
nullptr;
6001 return error(
"Explicit call type is not a function type");
6005 unsigned CalleeTypeID;
6006 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6008 return error(
"Invalid callbr record");
6012 return error(
"Callee is not a pointer type");
6014 FTyID = getContainedTypeID(CalleeTypeID);
6017 return error(
"Callee is not of pointer to function type");
6019 if (
Record.size() < FTy->getNumParams() + OpNum)
6020 return error(
"Insufficient operands to call");
6022 SmallVector<Value*, 16>
Args;
6023 SmallVector<unsigned, 16> ArgTyIDs;
6025 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6027 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6028 if (FTy->getParamType(i)->isLabelTy())
6029 Arg = getBasicBlock(Record[OpNum]);
6031 Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6034 return error(
"Invalid callbr record");
6035 Args.push_back(Arg);
6040 if (!FTy->isVarArg()) {
6041 if (OpNum !=
Record.size())
6042 return error(
"Invalid callbr record");
6044 while (OpNum !=
Record.size()) {
6047 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6048 return error(
"Invalid callbr record");
6055 if (!OperandBundles.empty())
6060 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6063 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6068 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6069 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6070 unsigned LabelNo = ArgNo - FirstBlockArg;
6072 if (!BA || BA->getFunction() !=
F ||
6073 LabelNo > IndirectDests.
size() ||
6074 BA->getBasicBlock() != IndirectDests[LabelNo])
6075 return error(
"callbr argument does not match indirect dest");
6080 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6084 for (
Value *Arg : Args)
6087 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6090 std::string Constraints =
IA->getConstraintString().str();
6093 for (
const auto &CI : ConstraintInfo) {
6095 if (ArgNo >= FirstBlockArg)
6096 Constraints.insert(Pos,
"!");
6101 Pos = Constraints.find(
',', Pos);
6102 if (Pos == std::string::npos)
6108 IA->hasSideEffects(),
IA->isAlignStack(),
6109 IA->getDialect(),
IA->canThrow());
6115 ResTypeID = getContainedTypeID(FTyID);
6116 OperandBundles.clear();
6133 return error(
"Invalid phi record");
6135 unsigned TyID =
Record[0];
6136 Type *Ty = getTypeByID(TyID);
6138 return error(
"Invalid phi record");
6143 size_t NumArgs = (
Record.size() - 1) / 2;
6147 return error(
"Invalid phi record");
6151 SmallDenseMap<BasicBlock *, Value *>
Args;
6152 for (
unsigned i = 0; i != NumArgs; i++) {
6153 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6156 return error(
"Invalid phi BB");
6163 auto It =
Args.find(BB);
6165 if (It !=
Args.end()) {
6179 if (!PhiConstExprBB)
6181 EdgeBB = PhiConstExprBB;
6189 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6191 V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6195 return error(
"Invalid phi record");
6198 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6199 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6200 PhiConstExprBB =
nullptr;
6203 Args.insert({BB,
V});
6209 if (
Record.size() % 2 == 0) {
6213 I->setFastMathFlags(FMF);
6225 return error(
"Invalid landingpad record");
6229 return error(
"Invalid landingpad record");
6231 ResTypeID =
Record[Idx++];
6232 Type *Ty = getTypeByID(ResTypeID);
6234 return error(
"Invalid landingpad record");
6236 Value *PersFn =
nullptr;
6237 unsigned PersFnTypeID;
6238 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6240 return error(
"Invalid landingpad record");
6242 if (!
F->hasPersonalityFn())
6245 return error(
"Personality function mismatch");
6248 bool IsCleanup = !!
Record[Idx++];
6249 unsigned NumClauses =
Record[Idx++];
6252 for (
unsigned J = 0; J != NumClauses; ++J) {
6258 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6261 return error(
"Invalid landingpad record");
6266 "Catch clause has a invalid type!");
6269 "Filter clause has invalid type!");
6280 return error(
"Invalid alloca record");
6281 using APV = AllocaPackedValues;
6282 const uint64_t Rec =
Record[3];
6285 unsigned TyID =
Record[0];
6286 Type *Ty = getTypeByID(TyID);
6288 TyID = getContainedTypeID(TyID);
6289 Ty = getTypeByID(TyID);
6291 return error(
"Missing element type for old-style alloca");
6293 unsigned OpTyID =
Record[1];
6294 Type *OpTy = getTypeByID(OpTyID);
6295 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6300 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6304 return error(
"Invalid alloca record");
6306 const DataLayout &
DL = TheModule->getDataLayout();
6307 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6309 SmallPtrSet<Type *, 4> Visited;
6310 if (!Align && !Ty->
isSized(&Visited))
6311 return error(
"alloca of unsized type");
6313 Align =
DL.getPrefTypeAlign(Ty);
6315 if (!
Size->getType()->isIntegerTy())
6316 return error(
"alloca element count must have integer type");
6318 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6322 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6330 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6331 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6332 return error(
"Invalid load record");
6335 return error(
"Load operand is not a pointer type");
6338 if (OpNum + 3 ==
Record.size()) {
6339 ResTypeID =
Record[OpNum++];
6340 Ty = getTypeByID(ResTypeID);
6342 ResTypeID = getContainedTypeID(OpTypeID);
6343 Ty = getTypeByID(ResTypeID);
6347 return error(
"Missing load type");
6349 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6353 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6355 SmallPtrSet<Type *, 4> Visited;
6356 if (!Align && !Ty->
isSized(&Visited))
6357 return error(
"load of unsized type");
6359 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6360 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6369 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6370 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size()))
6371 return error(
"Invalid load atomic record");
6374 return error(
"Load operand is not a pointer type");
6377 if (OpNum + 5 ==
Record.size()) {
6378 ResTypeID =
Record[OpNum++];
6379 Ty = getTypeByID(ResTypeID);
6381 ResTypeID = getContainedTypeID(OpTypeID);
6382 Ty = getTypeByID(ResTypeID);
6386 return error(
"Missing atomic load type");
6388 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6392 if (Ordering == AtomicOrdering::NotAtomic ||
6393 Ordering == AtomicOrdering::Release ||
6394 Ordering == AtomicOrdering::AcquireRelease)
6395 return error(
"Invalid load atomic record");
6396 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6397 return error(
"Invalid load atomic record");
6398 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6401 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6404 return error(
"Alignment missing from atomic load");
6405 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align, Ordering, SSID);
6413 unsigned PtrTypeID, ValTypeID;
6414 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6415 return error(
"Invalid store record");
6418 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6419 return error(
"Invalid store record");
6421 ValTypeID = getContainedTypeID(PtrTypeID);
6422 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6423 ValTypeID, Val, CurBB))
6424 return error(
"Invalid store record");
6427 if (OpNum + 2 !=
Record.size())
6428 return error(
"Invalid store record");
6433 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6435 SmallPtrSet<Type *, 4> Visited;
6437 return error(
"store of unsized type");
6439 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6440 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6449 unsigned PtrTypeID, ValTypeID;
6450 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6452 return error(
"Invalid store atomic record");
6454 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6455 return error(
"Invalid store atomic record");
6457 ValTypeID = getContainedTypeID(PtrTypeID);
6458 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6459 ValTypeID, Val, CurBB))
6460 return error(
"Invalid store atomic record");
6463 if (OpNum + 4 !=
Record.size())
6464 return error(
"Invalid store atomic record");
6469 if (Ordering == AtomicOrdering::NotAtomic ||
6470 Ordering == AtomicOrdering::Acquire ||
6471 Ordering == AtomicOrdering::AcquireRelease)
6472 return error(
"Invalid store atomic record");
6473 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6474 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6475 return error(
"Invalid store atomic record");
6478 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6481 return error(
"Alignment missing from atomic store");
6482 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6489 const size_t NumRecords =
Record.size();
6491 Value *Ptr =
nullptr;
6493 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6494 return error(
"Invalid cmpxchg record");
6497 return error(
"Cmpxchg operand is not a pointer type");
6500 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6501 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6502 CmpTypeID, Cmp, CurBB))
6503 return error(
"Invalid cmpxchg record");
6506 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6508 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6509 return error(
"Invalid cmpxchg record");
6513 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6514 SuccessOrdering == AtomicOrdering::Unordered)
6515 return error(
"Invalid cmpxchg record");
6517 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6519 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6527 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6528 FailureOrdering == AtomicOrdering::Unordered)
6529 return error(
"Invalid cmpxchg record");
6531 const Align Alignment(
6532 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6534 I =
new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6535 FailureOrdering, SSID);
6538 if (NumRecords < 8) {
6542 I->insertInto(CurBB, CurBB->
end());
6544 ResTypeID = CmpTypeID;
6547 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6548 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6557 const size_t NumRecords =
Record.size();
6559 Value *Ptr =
nullptr;
6561 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6562 return error(
"Invalid cmpxchg record");
6565 return error(
"Cmpxchg operand is not a pointer type");
6569 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6570 return error(
"Invalid cmpxchg record");
6572 Value *Val =
nullptr;
6573 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6575 return error(
"Invalid cmpxchg record");
6577 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6578 return error(
"Invalid cmpxchg record");
6580 const bool IsVol =
Record[OpNum];
6585 return error(
"Invalid cmpxchg success ordering");
6587 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6589 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6595 return error(
"Invalid cmpxchg failure ordering");
6597 const bool IsWeak =
Record[OpNum + 4];
6599 MaybeAlign Alignment;
6601 if (NumRecords == (OpNum + 6)) {
6602 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6607 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6609 I =
new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6610 FailureOrdering, SSID);
6614 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6615 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6624 const size_t NumRecords =
Record.size();
6627 Value *Ptr =
nullptr;
6629 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6630 return error(
"Invalid atomicrmw record");
6633 return error(
"Invalid atomicrmw record");
6635 Value *Val =
nullptr;
6636 unsigned ValTypeID = InvalidTypeID;
6638 ValTypeID = getContainedTypeID(PtrTypeID);
6639 if (popValue(Record, OpNum, NextValueNo,
6640 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6641 return error(
"Invalid atomicrmw record");
6643 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6644 return error(
"Invalid atomicrmw record");
6647 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6648 return error(
"Invalid atomicrmw record");
6654 return error(
"Invalid atomicrmw record");
6656 const bool IsVol =
Record[OpNum + 1];
6659 if (Ordering == AtomicOrdering::NotAtomic ||
6660 Ordering == AtomicOrdering::Unordered)
6661 return error(
"Invalid atomicrmw record");
6663 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6665 MaybeAlign Alignment;
6667 if (NumRecords == (OpNum + 5)) {
6668 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6674 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6676 I =
new AtomicRMWInst(
Operation, Ptr, Val, *Alignment, Ordering, SSID);
6677 ResTypeID = ValTypeID;
6685 return error(
"Invalid fence record");
6687 if (Ordering == AtomicOrdering::NotAtomic ||
6688 Ordering == AtomicOrdering::Unordered ||
6689 Ordering == AtomicOrdering::Monotonic)
6690 return error(
"Invalid fence record");
6692 I =
new FenceInst(
Context, Ordering, SSID);
6699 SeenDebugRecord =
true;
6702 return error(
"Invalid dbg record: missing instruction");
6705 Inst->
getParent()->insertDbgRecordBefore(
6716 SeenDebugRecord =
true;
6719 return error(
"Invalid dbg record: missing instruction");
6736 DILocalVariable *Var =
6738 DIExpression *Expr =
6751 unsigned SlotBefore =
Slot;
6752 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6753 return error(
"Invalid dbg record: invalid value");
6755 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6758 RawLocation = getFnMetadataByID(Record[Slot++]);
6761 DbgVariableRecord *DVR =
nullptr;
6765 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6766 DbgVariableRecord::LocationType::Value);
6769 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6770 DbgVariableRecord::LocationType::Declare);
6773 DVR =
new DbgVariableRecord(
6774 RawLocation, Var, Expr, DIL,
6775 DbgVariableRecord::LocationType::DeclareValue);
6779 DIExpression *AddrExpr =
6781 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6782 DVR =
new DbgVariableRecord(RawLocation, Var, Expr,
ID, Addr, AddrExpr,
6795 return error(
"Invalid call record");
6799 unsigned CCInfo =
Record[OpNum++];
6805 return error(
"Fast math flags indicator set for call with no FMF");
6808 unsigned FTyID = InvalidTypeID;
6809 FunctionType *FTy =
nullptr;
6814 return error(
"Explicit call type is not a function type");
6818 unsigned CalleeTypeID;
6819 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6821 return error(
"Invalid call record");
6825 return error(
"Callee is not a pointer type");
6827 FTyID = getContainedTypeID(CalleeTypeID);
6830 return error(
"Callee is not of pointer to function type");
6832 if (
Record.size() < FTy->getNumParams() + OpNum)
6833 return error(
"Insufficient operands to call");
6835 SmallVector<Value*, 16>
Args;
6836 SmallVector<unsigned, 16> ArgTyIDs;
6838 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6839 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6840 if (FTy->getParamType(i)->isLabelTy())
6841 Args.push_back(getBasicBlock(Record[OpNum]));
6843 Args.push_back(getValue(Record, OpNum, NextValueNo,
6844 FTy->getParamType(i), ArgTyID, CurBB));
6847 return error(
"Invalid call record");
6851 if (!FTy->isVarArg()) {
6852 if (OpNum !=
Record.size())
6853 return error(
"Invalid call record");
6855 while (OpNum !=
Record.size()) {
6858 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6859 return error(
"Invalid call record");
6866 if (!OperandBundles.empty())
6870 ResTypeID = getContainedTypeID(FTyID);
6871 OperandBundles.clear();
6885 SeenDebugIntrinsic =
true;
6892 return error(
"Fast-math-flags specified for call without "
6893 "floating-point scalar or vector return type");
6894 I->setFastMathFlags(FMF);
6900 return error(
"Invalid va_arg record");
6901 unsigned OpTyID =
Record[0];
6902 Type *OpTy = getTypeByID(OpTyID);
6903 Value *
Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6905 Type *ResTy = getTypeByID(ResTypeID);
6906 if (!OpTy || !
Op || !ResTy)
6907 return error(
"Invalid va_arg record");
6908 I =
new VAArgInst(
Op, ResTy);
6918 if (
Record.empty() || Record[0] >= BundleTags.size())
6919 return error(
"Invalid operand bundle record");
6921 std::vector<Value *> Inputs;
6924 while (OpNum !=
Record.size()) {
6926 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
6927 return error(
"Invalid operand bundle record");
6928 Inputs.push_back(
Op);
6931 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6939 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6940 return error(
"Invalid freeze record");
6941 if (OpNum !=
Record.size())
6942 return error(
"Invalid freeze record");
6944 I =
new FreezeInst(
Op);
6945 ResTypeID = OpTypeID;
6955 return error(
"Invalid instruction with no BB");
6957 if (!OperandBundles.empty()) {
6959 return error(
"Operand bundles found with no consumer");
6961 I->insertInto(CurBB, CurBB->
end());
6964 if (
I->isTerminator()) {
6966 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
6970 if (!
I->getType()->isVoidTy()) {
6971 assert(
I->getType() == getTypeByID(ResTypeID) &&
6972 "Incorrect result type ID");
6980 if (!OperandBundles.empty())
6981 return error(
"Operand bundles found with no consumer");
6985 if (!
A->getParent()) {
6987 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
6993 return error(
"Never resolved value found in function");
6998 if (MDLoader->hasFwdRefs())
6999 return error(
"Invalid function metadata: outgoing forward refs");
7004 for (
const auto &Pair : ConstExprEdgeBBs) {
7015 ValueList.
shrinkTo(ModuleValueListSize);
7016 MDLoader->shrinkTo(ModuleMDLoaderSize);
7017 std::vector<BasicBlock*>().swap(FunctionBBs);
7022Error BitcodeReader::findFunctionInStream(
7024 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7025 while (DeferredFunctionInfoIterator->second == 0) {
7030 assert(VSTOffset == 0 || !
F->hasName());
7033 if (
Error Err = rememberAndSkipFunctionBodies())
7039SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
7042 if (Val >= SSIDs.
size())
7051Error BitcodeReader::materialize(GlobalValue *GV) {
7054 if (!
F || !
F->isMaterializable())
7057 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.
find(
F);
7058 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
7061 if (DFII->second == 0)
7062 if (
Error Err = findFunctionInStream(
F, DFII))
7066 if (
Error Err = materializeMetadata())
7073 if (
Error Err = parseFunctionBody(
F))
7075 F->setIsMaterializable(
false);
7079 if (SeenDebugIntrinsic && SeenDebugRecord)
7080 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7086 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7087 F->setSubprogram(SP);
7090 if (!MDLoader->isStrippingTBAA()) {
7092 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7095 MDLoader->setStripTBAA(
true);
7102 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7103 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7109 unsigned ExpectedNumOperands = 0;
7111 ExpectedNumOperands = 2;
7113 ExpectedNumOperands =
SI->getNumSuccessors();
7115 ExpectedNumOperands = 1;
7119 ExpectedNumOperands = 2;
7126 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7127 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7133 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7134 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7136 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7137 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7138 CI->getArgOperand(ArgNo)->getType(),
7139 CI->getParamAttributes(ArgNo)));
7142 if (Function *OldFn = CI->getCalledFunction()) {
7143 auto It = UpgradedIntrinsics.find(OldFn);
7144 if (It != UpgradedIntrinsics.end())
7155 return materializeForwardReferencedFunctions();
7158Error BitcodeReader::materializeModule() {
7159 if (
Error Err = materializeMetadata())
7163 WillMaterializeAllForwardRefs =
true;
7167 for (Function &
F : *TheModule) {
7168 if (
Error Err = materialize(&
F))
7174 if (LastFunctionBlockBit || NextUnreadBit)
7176 ? LastFunctionBlockBit
7182 if (!BasicBlockFwdRefs.
empty())
7183 return error(
"Never resolved function from blockaddress");
7189 for (
auto &
I : UpgradedIntrinsics) {
7190 for (
auto *U :
I.first->users()) {
7194 if (
I.first !=
I.second) {
7195 if (!
I.first->use_empty())
7196 I.first->replaceAllUsesWith(
I.second);
7197 I.first->eraseFromParent();
7200 UpgradedIntrinsics.clear();
7215std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7216 return IdentifiedStructTypes;
7219ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7220 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7222 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7223 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7225void ModuleSummaryIndexBitcodeReader::addThisModule() {
7230ModuleSummaryIndexBitcodeReader::getThisModule() {
7234template <
bool AllowNullValueInfo>
7235std::pair<ValueInfo, GlobalValue::GUID>
7236ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7237 auto VGI = ValueIdToValueInfoMap[ValueId];
7244 assert(AllowNullValueInfo || std::get<0>(VGI));
7248void ModuleSummaryIndexBitcodeReader::setValueGUID(
7250 StringRef SourceFileName) {
7251 std::string GlobalId =
7254 auto OriginalNameID = ValueGUID;
7258 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7264 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7273Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7275 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7282 if (!MaybeCurrentBit)
7284 uint64_t CurrentBit = MaybeCurrentBit.
get();
7289 SmallVector<uint64_t, 64>
Record;
7298 BitstreamEntry
Entry = MaybeEntry.
get();
7300 switch (
Entry.Kind) {
7303 return error(
"Malformed block");
7319 switch (MaybeRecord.
get()) {
7324 return error(
"Invalid vst_code_entry record");
7325 unsigned ValueID =
Record[0];
7327 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7328 assert(VLI != ValueIdToLinkageMap.
end() &&
7329 "No linkage found for VST entry?");
7338 return error(
"Invalid vst_code_fnentry record");
7339 unsigned ValueID =
Record[0];
7341 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7342 assert(VLI != ValueIdToLinkageMap.
end() &&
7343 "No linkage found for VST entry?");
7351 unsigned ValueID =
Record[0];
7355 ValueIdToValueInfoMap[ValueID] =
7366Error ModuleSummaryIndexBitcodeReader::parseModule() {
7370 SmallVector<uint64_t, 64>
Record;
7371 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7372 unsigned ValueId = 0;
7376 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
7379 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7381 switch (
Entry.Kind) {
7383 return error(
"Malformed block");
7395 if (
Error Err = readBlockInfo())
7401 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7402 !SeenGlobalValSummary) &&
7403 "Expected early VST parse via VSTOffset record");
7410 if (!SourceFileName.
empty())
7412 assert(!SeenValueSymbolTable &&
7413 "Already read VST when parsing summary block?");
7418 if (VSTOffset > 0) {
7419 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7421 SeenValueSymbolTable =
true;
7423 SeenGlobalValSummary =
true;
7424 if (
Error Err = parseEntireSummary(
Entry.ID))
7428 if (
Error Err = parseModuleStringTable())
7436 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7439 switch (MaybeBitCode.
get()) {
7443 if (
Error Err = parseVersionRecord(Record).takeError())
7451 return error(
"Invalid source filename record");
7458 return error(
"Invalid hash length " + Twine(
Record.size()).str());
7459 auto &Hash = getThisModule()->second;
7461 for (
auto &Val : Record) {
7462 assert(!(Val >> 32) &&
"Unexpected high bits set");
7470 return error(
"Invalid vstoffset record");
7474 VSTOffset =
Record[0] - 1;
7484 ArrayRef<uint64_t> GVRecord;
7485 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7486 if (GVRecord.
size() <= 3)
7487 return error(
"Invalid global record");
7488 uint64_t RawLinkage = GVRecord[3];
7491 ValueIdToLinkageMap[ValueId++] =
Linkage;
7495 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7506ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7509 for (uint64_t RefValueId : Record)
7510 Ret.
push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7515ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7516 bool IsOldProfileFormat,
7517 bool HasProfile,
bool HasRelBF) {
7521 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7526 for (
unsigned I = 0,
E =
Record.size();
I !=
E; ++
I) {
7528 bool HasTailCall =
false;
7530 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7531 if (IsOldProfileFormat) {
7535 }
else if (HasProfile)
7536 std::tie(Hotness, HasTailCall) =
7570 static_cast<size_t>(
Record[Slot + 1])};
7593 while (Slot <
Record.size())
7597std::vector<FunctionSummary::ParamAccess>
7598ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7599 auto ReadRange = [&]() {
7601 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7603 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7610 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7611 while (!
Record.empty()) {
7612 PendingParamAccesses.emplace_back();
7613 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7615 ParamAccess.
Use = ReadRange();
7620 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7621 Call.Offsets = ReadRange();
7624 return PendingParamAccesses;
7627void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7628 ArrayRef<uint64_t> Record,
size_t &Slot,
7631 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7635void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7636 ArrayRef<uint64_t> Record) {
7644 while (Slot <
Record.size())
7645 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7648SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7649 ArrayRef<uint64_t> Record,
unsigned &
I) {
7650 SmallVector<unsigned> StackIdList;
7654 if (RadixArray.empty()) {
7655 unsigned NumStackEntries =
Record[
I++];
7657 StackIdList.
reserve(NumStackEntries);
7658 for (
unsigned J = 0; J < NumStackEntries; J++) {
7659 assert(Record[
I] < StackIds.size());
7660 StackIdList.
push_back(getStackIdIndex(Record[
I++]));
7663 unsigned RadixIndex =
Record[
I++];
7669 assert(RadixIndex < RadixArray.size());
7670 unsigned NumStackIds = RadixArray[RadixIndex++];
7671 StackIdList.
reserve(NumStackIds);
7672 while (NumStackIds--) {
7673 assert(RadixIndex < RadixArray.size());
7674 unsigned Elem = RadixArray[RadixIndex];
7675 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7676 RadixIndex = RadixIndex - Elem;
7677 assert(RadixIndex < RadixArray.size());
7678 Elem = RadixArray[RadixIndex];
7680 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7683 StackIdList.
push_back(getStackIdIndex(Elem));
7693 unsigned FirstWORef = Refs.
size() - WOCnt;
7694 unsigned RefNo = FirstWORef - ROCnt;
7695 for (; RefNo < FirstWORef; ++RefNo)
7696 Refs[RefNo].setReadOnly();
7697 for (; RefNo < Refs.
size(); ++RefNo)
7698 Refs[RefNo].setWriteOnly();
7703Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7706 SmallVector<uint64_t, 64>
Record;
7713 BitstreamEntry
Entry = MaybeEntry.
get();
7716 return error(
"Invalid Summary Block: record for version expected");
7721 return error(
"Invalid Summary Block: version expected");
7724 const bool IsOldProfileFormat =
Version == 1;
7727 const bool MemProfAfterFunctionSummary =
Version >= 13;
7729 return error(
"Invalid summary version " + Twine(
Version) +
7730 ". Version should be in the range [1-" +
7737 GlobalValueSummary *LastSeenSummary =
nullptr;
7747 FunctionSummary *CurrentPrevailingFS =
nullptr;
7752 std::vector<GlobalValue::GUID> PendingTypeTests;
7753 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7754 PendingTypeCheckedLoadVCalls;
7755 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7756 PendingTypeCheckedLoadConstVCalls;
7757 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7759 std::vector<CallsiteInfo> PendingCallsites;
7760 std::vector<AllocInfo> PendingAllocs;
7761 std::vector<uint64_t> PendingContextIds;
7767 BitstreamEntry
Entry = MaybeEntry.
get();
7769 switch (
Entry.Kind) {
7772 return error(
"Malformed block");
7788 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7791 unsigned BitCode = MaybeBitCode.
get();
7801 uint64_t ValueID =
Record[0];
7808 ValueIdToValueInfoMap[ValueID] =
7826 unsigned ValueID =
Record[0];
7827 uint64_t RawFlags =
Record[1];
7828 unsigned InstCount =
Record[2];
7829 uint64_t RawFunFlags = 0;
7830 unsigned NumRefs =
Record[3];
7831 unsigned NumRORefs = 0, NumWORefs = 0;
7832 int RefListStartIndex = 4;
7836 RefListStartIndex = 5;
7839 RefListStartIndex = 6;
7842 RefListStartIndex = 7;
7853 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7855 "Record size inconsistent with number of references");
7857 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7862 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7863 IsOldProfileFormat, HasProfile, HasRelBF);
7865 auto [
VI,
GUID] = getValueInfoFromValueId(ValueID);
7872 IsPrevailing(
VI.getGUID());
7878 assert(!MemProfAfterFunctionSummary ||
7879 (PendingCallsites.empty() && PendingAllocs.empty()));
7880 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
7881 PendingCallsites.clear();
7882 PendingAllocs.clear();
7885 auto FS = std::make_unique<FunctionSummary>(
7887 std::move(Calls), std::move(PendingTypeTests),
7888 std::move(PendingTypeTestAssumeVCalls),
7889 std::move(PendingTypeCheckedLoadVCalls),
7890 std::move(PendingTypeTestAssumeConstVCalls),
7891 std::move(PendingTypeCheckedLoadConstVCalls),
7892 std::move(PendingParamAccesses), std::move(PendingCallsites),
7893 std::move(PendingAllocs));
7894 FS->setModulePath(getThisModule()->first());
7895 FS->setOriginalName(GUID);
7898 if (MemProfAfterFunctionSummary) {
7899 if (IsPrevailingSym)
7900 CurrentPrevailingFS =
FS.get();
7902 CurrentPrevailingFS =
nullptr;
7911 unsigned ValueID =
Record[0];
7912 uint64_t RawFlags =
Record[1];
7913 unsigned AliaseeID =
Record[2];
7915 auto AS = std::make_unique<AliasSummary>(Flags);
7921 AS->setModulePath(getThisModule()->first());
7923 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7925 if (!AliaseeInModule)
7926 return error(
"Alias expects aliasee summary to be parsed");
7927 AS->setAliasee(AliaseeVI, AliaseeInModule);
7929 auto GUID = getValueInfoFromValueId(ValueID);
7930 AS->setOriginalName(std::get<1>(GUID));
7936 unsigned ValueID =
Record[0];
7937 uint64_t RawFlags =
Record[1];
7938 unsigned RefArrayStart = 2;
7939 GlobalVarSummary::GVarFlags GVF(
false,
7949 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7951 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7952 FS->setModulePath(getThisModule()->first());
7953 auto GUID = getValueInfoFromValueId(ValueID);
7954 FS->setOriginalName(std::get<1>(GUID));
7962 unsigned ValueID =
Record[0];
7963 uint64_t RawFlags =
Record[1];
7965 unsigned NumRefs =
Record[3];
7966 unsigned RefListStartIndex = 4;
7967 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7970 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7972 for (
unsigned I = VTableListStartIndex,
E =
Record.size();
I !=
E; ++
I) {
7973 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7978 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7979 VS->setModulePath(getThisModule()->first());
7980 VS->setVTableFuncs(VTableFuncs);
7981 auto GUID = getValueInfoFromValueId(ValueID);
7982 VS->setOriginalName(std::get<1>(GUID));
7994 unsigned ValueID =
Record[0];
7995 uint64_t ModuleId =
Record[1];
7996 uint64_t RawFlags =
Record[2];
7997 unsigned InstCount =
Record[3];
7998 uint64_t RawFunFlags = 0;
7999 unsigned NumRefs =
Record[4];
8000 unsigned NumRORefs = 0, NumWORefs = 0;
8001 int RefListStartIndex = 5;
8005 RefListStartIndex = 6;
8006 size_t NumRefsIndex = 5;
8008 unsigned NumRORefsOffset = 1;
8009 RefListStartIndex = 7;
8012 RefListStartIndex = 8;
8014 RefListStartIndex = 9;
8016 NumRORefsOffset = 2;
8019 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
8021 NumRefs =
Record[NumRefsIndex];
8025 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8027 "Record size inconsistent with number of references");
8029 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8032 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8033 IsOldProfileFormat, HasProfile,
false);
8034 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8036 auto FS = std::make_unique<FunctionSummary>(
8038 std::move(Edges), std::move(PendingTypeTests),
8039 std::move(PendingTypeTestAssumeVCalls),
8040 std::move(PendingTypeCheckedLoadVCalls),
8041 std::move(PendingTypeTestAssumeConstVCalls),
8042 std::move(PendingTypeCheckedLoadConstVCalls),
8043 std::move(PendingParamAccesses), std::move(PendingCallsites),
8044 std::move(PendingAllocs));
8045 LastSeenSummary =
FS.get();
8046 if (MemProfAfterFunctionSummary)
8047 CurrentPrevailingFS =
FS.get();
8048 LastSeenGUID =
VI.getGUID();
8049 FS->setModulePath(ModuleIdMap[ModuleId]);
8057 unsigned ValueID =
Record[0];
8058 uint64_t ModuleId =
Record[1];
8059 uint64_t RawFlags =
Record[2];
8060 unsigned AliaseeValueId =
Record[3];
8062 auto AS = std::make_unique<AliasSummary>(Flags);
8063 LastSeenSummary = AS.get();
8064 AS->setModulePath(ModuleIdMap[ModuleId]);
8066 auto AliaseeVI = std::get<0>(
8067 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8069 auto AliaseeInModule =
8071 AS->setAliasee(AliaseeVI, AliaseeInModule);
8073 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8074 LastSeenGUID =
VI.getGUID();
8080 unsigned ValueID =
Record[0];
8081 uint64_t ModuleId =
Record[1];
8082 uint64_t RawFlags =
Record[2];
8083 unsigned RefArrayStart = 3;
8084 GlobalVarSummary::GVarFlags GVF(
false,
8094 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8096 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8097 LastSeenSummary =
FS.get();
8098 FS->setModulePath(ModuleIdMap[ModuleId]);
8099 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8100 LastSeenGUID =
VI.getGUID();
8106 uint64_t OriginalName =
Record[0];
8107 if (!LastSeenSummary)
8108 return error(
"Name attachment that does not follow a combined record");
8112 LastSeenSummary =
nullptr;
8117 assert(PendingTypeTests.empty());
8122 assert(PendingTypeTestAssumeVCalls.empty());
8123 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8124 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8128 assert(PendingTypeCheckedLoadVCalls.empty());
8129 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8130 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8134 PendingTypeTestAssumeConstVCalls.push_back(
8139 PendingTypeCheckedLoadConstVCalls.push_back(
8145 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8147 static_cast<size_t>(Record[
I + 1]));
8153 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8155 static_cast<size_t>(Record[
I + 1]));
8164 parseTypeIdCompatibleVtableSummaryRecord(Record);
8172 PendingParamAccesses = parseParamAccesses(Record);
8179 assert(StackIds.empty());
8181 StackIds = ArrayRef<uint64_t>(Record);
8187 StackIds.reserve(
Record.size() / 2);
8188 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8189 StackIds.push_back(*R << 32 | *(R + 1));
8191 assert(StackIdToIndex.empty());
8193 StackIdToIndex.resize(StackIds.size(), UninitializedStackIdIndex);
8198 RadixArray = ArrayRef<uint64_t>(Record);
8205 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8207 unsigned ValueID =
Record[0];
8208 SmallVector<unsigned> StackIdList;
8210 assert(R < StackIds.size());
8211 StackIdList.
push_back(getStackIdIndex(R));
8213 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8214 if (MemProfAfterFunctionSummary)
8216 CallsiteInfo({
VI, std::move(StackIdList)}));
8218 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8225 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8226 auto RecordIter =
Record.begin();
8227 unsigned ValueID = *RecordIter++;
8228 unsigned NumStackIds = *RecordIter++;
8229 unsigned NumVersions = *RecordIter++;
8230 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8231 SmallVector<unsigned> StackIdList;
8232 for (
unsigned J = 0; J < NumStackIds; J++) {
8233 assert(*RecordIter < StackIds.size());
8234 StackIdList.
push_back(getStackIdIndex(*RecordIter++));
8236 SmallVector<unsigned> Versions;
8237 for (
unsigned J = 0; J < NumVersions; J++)
8239 ValueInfo
VI = std::get<0>(
8240 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8241 if (MemProfAfterFunctionSummary)
8243 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8245 PendingCallsites.push_back(
8246 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8253 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8258 PendingContextIds.reserve(
Record.size() / 2);
8259 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8260 PendingContextIds.push_back(*R << 32 | *(R + 1));
8267 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8268 PendingContextIds.clear();
8272 std::vector<MIBInfo> MIBs;
8273 unsigned NumMIBs = 0;
8276 unsigned MIBsRead = 0;
8277 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8281 auto StackIdList = parseAllocInfoContext(Record,
I);
8282 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8288 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8290 assert(!PendingContextIds.empty() &&
8291 "Missing context ids for alloc sizes");
8292 unsigned ContextIdIndex = 0;
8298 while (MIBsRead++ < NumMIBs) {
8300 unsigned NumContextSizeInfoEntries =
Record[
I++];
8302 std::vector<ContextTotalSize> ContextSizes;
8303 ContextSizes.reserve(NumContextSizeInfoEntries);
8304 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8305 assert(ContextIdIndex < PendingContextIds.size());
8307 if (PendingContextIds[ContextIdIndex] == 0) {
8316 ContextSizes.push_back(
8317 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8319 AllContextSizes.push_back(std::move(ContextSizes));
8321 PendingContextIds.clear();
8323 AllocInfo AI(std::move(MIBs));
8324 if (!AllContextSizes.empty()) {
8325 assert(AI.MIBs.size() == AllContextSizes.size());
8326 AI.ContextSizeInfos = std::move(AllContextSizes);
8329 if (MemProfAfterFunctionSummary)
8330 CurrentPrevailingFS->
addAlloc(std::move(AI));
8332 PendingAllocs.push_back(std::move(AI));
8340 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8342 std::vector<MIBInfo> MIBs;
8343 unsigned NumMIBs =
Record[
I++];
8344 unsigned NumVersions =
Record[
I++];
8345 unsigned MIBsRead = 0;
8346 while (MIBsRead++ < NumMIBs) {
8349 SmallVector<unsigned> StackIdList;
8351 StackIdList = parseAllocInfoContext(Record,
I);
8352 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8355 SmallVector<uint8_t> Versions;
8356 for (
unsigned J = 0; J < NumVersions; J++)
8359 AllocInfo AI(std::move(Versions), std::move(MIBs));
8360 if (MemProfAfterFunctionSummary)
8361 CurrentPrevailingFS->
addAlloc(std::move(AI));
8363 PendingAllocs.push_back(std::move(AI));
8373Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8377 SmallVector<uint64_t, 64>
Record;
8379 SmallString<128> ModulePath;
8386 BitstreamEntry
Entry = MaybeEntry.
get();
8388 switch (
Entry.Kind) {
8391 return error(
"Malformed block");
8403 switch (MaybeRecord.
get()) {
8408 uint64_t ModuleId =
Record[0];
8411 return error(
"Invalid code_entry record");
8413 LastSeenModule = TheIndex.
addModule(ModulePath);
8414 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8422 return error(
"Invalid hash length " + Twine(
Record.size()).str());
8423 if (!LastSeenModule)
8424 return error(
"Invalid hash that does not follow a module path");
8426 for (
auto &Val : Record) {
8427 assert(!(Val >> 32) &&
"Unexpected high bits set");
8428 LastSeenModule->
second[Pos++] = Val;
8431 LastSeenModule =
nullptr;
8444class BitcodeErrorCategoryType :
public std::error_category {
8445 const char *
name()
const noexcept
override {
8446 return "llvm.bitcode";
8449 std::string message(
int IE)
const override {
8452 case BitcodeError::CorruptedBitcode:
8453 return "Corrupted bitcode";
8462 static BitcodeErrorCategoryType ErrorCategory;
8463 return ErrorCategory;
8467 unsigned Block,
unsigned RecordID) {
8469 return std::move(Err);
8478 switch (Entry.Kind) {
8483 return error(
"Malformed block");
8487 return std::move(Err);
8497 if (MaybeRecord.
get() == RecordID)
8508Expected<std::vector<BitcodeModule>>
8512 return FOrErr.takeError();
8513 return std::move(FOrErr->Mods);
8538 switch (Entry.Kind) {
8541 return error(
"Malformed block");
8544 uint64_t IdentificationBit = -1ull;
8548 return std::move(Err);
8554 Entry = MaybeEntry.
get();
8559 return error(
"Malformed block");
8565 return std::move(Err);
8584 if (!
I.Strtab.empty())
8591 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8592 F.StrtabForSymtab = *Strtab;
8608 if (
F.Symtab.empty())
8609 F.Symtab = *SymtabOrErr;
8614 return std::move(Err);
8619 return std::move(E);
8634BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8635 bool ShouldLazyLoadMetadata,
bool IsImporting,
8639 std::string ProducerIdentification;
8640 if (IdentificationBit != -1ull) {
8642 return std::move(JumpFailed);
8645 return std::move(
E);
8649 return std::move(JumpFailed);
8650 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8653 std::unique_ptr<Module>
M =
8654 std::make_unique<Module>(ModuleIdentifier,
Context);
8655 M->setMaterializer(R);
8658 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8659 IsImporting, Callbacks))
8660 return std::move(Err);
8662 if (MaterializeAll) {
8664 if (
Error Err =
M->materializeAll())
8665 return std::move(Err);
8668 if (
Error Err =
R->materializeForwardReferencedFunctions())
8669 return std::move(Err);
8672 return std::move(M);
8675Expected<std::unique_ptr<Module>>
8678 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8693 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8694 ModulePath, IsPrevailing);
8695 return R.parseModule();
8702 return std::move(JumpFailed);
8704 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8705 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8706 ModuleIdentifier, 0);
8708 if (
Error Err = R.parseModule())
8709 return std::move(Err);
8711 return std::move(Index);
8717 return std::move(Err);
8723 return std::move(
E);
8725 switch (Entry.Kind) {
8728 return error(
"Malformed block");
8731 return std::make_pair(
false,
false);
8743 switch (MaybeBitCode.
get()) {
8749 assert(Flags <= 0x7ff &&
"Unexpected bits in flag");
8751 bool EnableSplitLTOUnit = Flags & 0x8;
8752 bool UnifiedLTO = Flags & 0x200;
8753 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8764 return std::move(JumpFailed);
8767 return std::move(Err);
8772 return std::move(E);
8774 switch (Entry.Kind) {
8776 return error(
"Malformed block");
8787 return Flags.takeError();
8797 return std::move(Err);
8804 return StreamFailed.takeError();
8814 if (MsOrErr->size() != 1)
8815 return error(
"Expected a single module");
8817 return (*MsOrErr)[0];
8820Expected<std::unique_ptr<Module>>
8822 bool ShouldLazyLoadMetadata,
bool IsImporting,
8828 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8833 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
8834 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
8836 IsImporting, Callbacks);
8838 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8844 return getModuleImpl(Context,
true,
false,
false, Callbacks);
8856 return BM->parseModule(Context, Callbacks);
8889 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8898 return BM->getSummary();
8906 return BM->getLTOInfo();
8911 bool IgnoreEmptyThinLTOIndexFile) {
8916 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...
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 std::pair< CalleeInfo::HotnessType, bool > getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)
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 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 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 Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val)
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 cl::opt< bool > ExpandConstantExprs("expand-constant-exprs", cl::Hidden, cl::desc("Expand constant expressions to instructions for testing purposes"))
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 bool isConstExprSupported(const BitcodeConstant *BC)
static int getDecodedCastOpcode(unsigned Val)
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
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")
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.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
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.
const SmallVectorImpl< MachineOperand > & Cond
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
bool empty() const
empty - 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,...
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
@ None
No attributes have been set.
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
@ 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.
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 Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(GlobalValue::GUID)> IsPrevailing=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
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.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
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.
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)
void emplace(Args &&...A)
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_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 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 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)
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
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 setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
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)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
bool hasDefaultVisibility() const
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.
LLVM_ABI StringRef getString() const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
ValueT lookup(const KeyT &Key) const
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()
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
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.
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)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
constexpr bool empty() const
empty - Check if the string is empty.
constexpr size_t size() const
size - Get the string size.
constexpr const char * data() const
data - 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
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.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
@ BasicBlock
Various leaf nodes.
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_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ 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
@ 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_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_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.
FunctionAddr VTableAddr Value
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.
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.
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...
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.
FunctionAddr VTableAddr uintptr_t uintptr_t Version
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.
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
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...
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
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.
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.
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