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;
584 std::optional<Triple> TargetTriple;
589 bool SeenValueSymbolTable =
false;
592 std::vector<std::string> SectionTable;
593 std::vector<std::string> GCTable;
595 std::vector<Type *> TypeList;
599 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
606 DenseMap<std::pair<Type *, unsigned>,
unsigned> VirtualTypeIDs;
607 DenseMap<Function *, unsigned> FunctionTypeIDs;
612 BitcodeReaderValueList ValueList;
613 std::optional<MetadataLoader> MDLoader;
614 std::vector<Comdat *> ComdatList;
615 DenseSet<GlobalObject *> ImplicitComdatObjects;
618 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
619 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
621 struct FunctionOperandInfo {
623 unsigned PersonalityFn;
627 std::vector<FunctionOperandInfo> FunctionOperands;
631 std::vector<AttributeList> MAttributes;
634 std::map<unsigned, AttributeList> MAttributeGroups;
638 std::vector<BasicBlock*> FunctionBBs;
642 std::vector<Function*> FunctionsWithBodies;
646 DenseMap<Function *, Function *> 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 std::vector<GlobalValue::GUID> GUIDList;
707 bool SkipDebugIntrinsicUpgrade =
false;
710 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
711 StringRef ProducerIdentification, LLVMContext &
Context);
713 Error materializeForwardReferencedFunctions();
715 Error materialize(GlobalValue *GV)
override;
716 Error materializeModule()
override;
717 std::vector<StructType *> getIdentifiedStructTypes()
const override;
721 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
722 bool IsImporting, ParserCallbacks Callbacks = {});
727 Error materializeMetadata()
override;
729 void setStripDebugInfo()
override;
732 std::vector<StructType *> IdentifiedStructTypes;
733 StructType *createIdentifiedStructType(LLVMContext &
Context, StringRef Name);
734 StructType *createIdentifiedStructType(LLVMContext &
Context);
736 static constexpr unsigned InvalidTypeID = ~0
u;
738 Type *getTypeByID(
unsigned ID);
739 Type *getPtrElementTypeByID(
unsigned ID);
740 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
741 unsigned getVirtualTypeID(
Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
744 Expected<Value *> materializeValue(
unsigned ValID, BasicBlock *InsertBB);
745 Expected<Constant *> getValueForInitializer(
unsigned ID);
747 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
748 BasicBlock *ConstExprInsertBB) {
754 Metadata *getFnMetadataByID(
unsigned ID) {
755 return MDLoader->getMetadataFwdRefOrLoad(ID);
758 BasicBlock *getBasicBlock(
unsigned ID)
const {
759 if (ID >= FunctionBBs.size())
return nullptr;
760 return FunctionBBs[
ID];
764 if (i-1 < MAttributes.size())
765 return MAttributes[i-1];
766 return AttributeList();
772 bool getValueTypePair(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
773 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
774 BasicBlock *ConstExprInsertBB) {
775 if (Slot ==
Record.size())
return true;
776 unsigned ValNo = (unsigned)Record[Slot++];
779 ValNo = InstNum - ValNo;
780 if (ValNo < InstNum) {
784 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
786 "Incorrect type ID stored for value");
787 return ResVal ==
nullptr;
789 if (Slot ==
Record.size())
792 TypeID = (unsigned)Record[Slot++];
793 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
795 return ResVal ==
nullptr;
798 bool getValueOrMetadata(
const SmallVectorImpl<uint64_t> &Record,
799 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
800 BasicBlock *ConstExprInsertBB) {
801 if (Slot ==
Record.size())
806 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
809 if (Slot ==
Record.size())
811 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
819 bool popValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
820 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
821 BasicBlock *ConstExprInsertBB) {
822 if (
getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
830 bool getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
831 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
832 BasicBlock *ConstExprInsertBB) {
833 ResVal =
getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
834 return ResVal ==
nullptr;
839 Value *
getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
840 unsigned InstNum,
Type *Ty,
unsigned TyID,
841 BasicBlock *ConstExprInsertBB) {
842 if (Slot ==
Record.size())
return nullptr;
843 unsigned ValNo = (unsigned)Record[Slot];
846 ValNo = InstNum - ValNo;
847 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
851 Value *getValueSigned(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
852 unsigned InstNum,
Type *Ty,
unsigned TyID,
853 BasicBlock *ConstExprInsertBB) {
854 if (Slot ==
Record.size())
return nullptr;
855 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
858 ValNo = InstNum - ValNo;
859 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
862 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
865 if (
Record.size() - OpNum < 2)
866 return error(
"Too few records for range");
868 unsigned LowerActiveWords =
Record[OpNum];
869 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
870 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
871 return error(
"Too few records for range");
874 OpNum += LowerActiveWords;
877 OpNum += UpperActiveWords;
880 int64_t
Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
881 int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
882 return ConstantRange(APInt(
BitWidth, Start,
true),
887 Expected<ConstantRange>
888 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,
unsigned &OpNum) {
889 if (
Record.size() - OpNum < 1)
890 return error(
"Too few records for range");
892 return readConstantRange(Record, OpNum,
BitWidth);
896 const Triple &getTargetTriple() {
898 BitstreamCursor TripleStream(Stream.getBitcodeBytes());
899 if (Expected<std::string> TripleStr =
readTriple(TripleStream))
900 TargetTriple.emplace(std::move(*TripleStr));
903 TargetTriple.emplace();
906 return *TargetTriple;
912 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
918 Error parseAttrKind(
uint64_t Code, Attribute::AttrKind *Kind);
920 ParserCallbacks Callbacks = {});
922 Error parseComdatRecord(ArrayRef<uint64_t> Record);
923 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
924 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
925 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
926 ArrayRef<uint64_t> Record);
928 Error parseAttributeBlock();
929 Error parseAttributeGroupBlock();
930 Error parseTypeTable();
931 Error parseTypeTableBody();
932 Error parseOperandBundleTags();
933 Error parseSyncScopeNames();
935 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
936 unsigned NameIndex, Triple &TT);
937 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
Function *
F,
938 ArrayRef<uint64_t> Record);
940 Error parseGlobalValueSymbolTable();
941 Error parseConstants();
942 Error rememberAndSkipFunctionBodies();
943 Error rememberAndSkipFunctionBody();
945 Error rememberAndSkipMetadata();
948 Error globalCleanup();
949 Error resolveGlobalAndIndirectSymbolInits();
950 Error parseUseLists();
951 Error findFunctionInStream(
953 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
960class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
962 ModuleSummaryIndex &TheIndex;
966 bool SeenGlobalValSummary =
false;
969 bool SeenValueSymbolTable =
false;
983 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
984 ValueIdToValueInfoMap;
990 DenseMap<uint64_t, StringRef> ModuleIdMap;
993 std::string SourceFileName;
997 StringRef ModulePath;
1001 std::function<bool(StringRef)> IsPrevailing =
nullptr;
1004 std::function<void(ValueInfo)> OnValueInfo =
nullptr;
1008 std::vector<uint64_t> StackIds;
1012 std::vector<uint64_t> RadixArray;
1017 std::vector<unsigned> StackIdToIndex;
1020 std::vector<uint64_t> DefinedGUIDs;
1023 ModuleSummaryIndexBitcodeReader(
1024 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
1025 StringRef ModulePath,
1026 std::function<
bool(StringRef)> IsPrevailing =
nullptr,
1027 std::function<
void(ValueInfo)> OnValueInfo =
nullptr);
1034 StringRef SourceFileName);
1035 Error parseValueSymbolTable(
1037 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1040 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1041 bool HasProfile,
bool HasRelBF);
1042 Error parseEntireSummary(
unsigned ID);
1043 Error parseModuleStringTable();
1044 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1045 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1047 std::vector<FunctionSummary::ParamAccess>
1048 parseParamAccesses(ArrayRef<uint64_t> Record);
1049 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1053 static constexpr unsigned UninitializedStackIdIndex =
1054 std::numeric_limits<unsigned>::max();
1056 unsigned getStackIdIndex(
unsigned LocalIndex) {
1057 unsigned &
Index = StackIdToIndex[LocalIndex];
1060 if (Index == UninitializedStackIdIndex)
1065 template <
bool AllowNullValueInfo = false>
1066 std::pair<ValueInfo, GlobalValue::GUID>
1067 getValueInfoFromValueId(
unsigned ValueId);
1069 void addThisModule();
1085 return std::error_code();
1091 : BitcodeReaderBase(
std::
move(Stream), Strtab), Context(Context),
1092 ValueList(this->Stream.SizeInBytes(),
1094 return materializeValue(
ValID, InsertBB);
1096 this->ProducerIdentification = std::string(ProducerIdentification);
1099Error BitcodeReader::materializeForwardReferencedFunctions() {
1100 if (WillMaterializeAllForwardRefs)
1104 WillMaterializeAllForwardRefs =
true;
1106 while (!BasicBlockFwdRefQueue.empty()) {
1107 Function *
F = BasicBlockFwdRefQueue.front();
1108 BasicBlockFwdRefQueue.pop_front();
1109 assert(
F &&
"Expected valid function");
1110 if (!BasicBlockFwdRefs.
count(
F))
1118 if (!
F->isMaterializable())
1119 return error(
"Never resolved function from blockaddress");
1122 if (
Error Err = materialize(
F))
1125 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1127 for (
Function *
F : BackwardRefFunctions)
1128 if (
Error Err = materialize(
F))
1130 BackwardRefFunctions.clear();
1133 WillMaterializeAllForwardRefs =
false;
1198 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1199 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1200 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1201 Flags.NoInline = (RawFlags >> 4) & 0x1;
1202 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1203 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1204 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1205 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1206 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1222 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1);
1223 RawFlags = RawFlags >> 4;
1224 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1228 bool Live = (RawFlags & 0x2) || Version < 3;
1229 bool Local = (RawFlags & 0x4);
1230 bool AutoHide = (RawFlags & 0x8);
1233 Live,
Local, AutoHide, IK,
1234 NoRenameOnPromotion);
1240 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1241 (RawFlags & 0x4) ?
true :
false,
1245static std::pair<CalleeInfo::HotnessType, bool>
1249 bool HasTailCall = (RawFlags & 0x8);
1250 return {Hotness, HasTailCall};
1255 bool &HasTailCall) {
1256 static constexpr unsigned RelBlockFreqBits = 28;
1257 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1258 RelBF = RawFlags & RelBlockFreqMask;
1259 HasTailCall = (RawFlags & (1 << RelBlockFreqBits));
1284 case 0:
return false;
1285 case 1:
return true;
1347 bool IsFP = Ty->isFPOrFPVectorTy();
1349 if (!IsFP && !Ty->isIntOrIntVectorTy())
1356 return IsFP ? Instruction::FNeg : -1;
1361 bool IsFP = Ty->isFPOrFPVectorTy();
1363 if (!IsFP && !Ty->isIntOrIntVectorTy())
1370 return IsFP ? Instruction::FAdd : Instruction::Add;
1372 return IsFP ? Instruction::FSub : Instruction::Sub;
1374 return IsFP ? Instruction::FMul : Instruction::Mul;
1376 return IsFP ? -1 : Instruction::UDiv;
1378 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1380 return IsFP ? -1 : Instruction::URem;
1382 return IsFP ? Instruction::FRem : Instruction::SRem;
1384 return IsFP ? -1 : Instruction::Shl;
1386 return IsFP ? -1 : Instruction::LShr;
1388 return IsFP ? -1 : Instruction::AShr;
1390 return IsFP ? -1 : Instruction::And;
1392 return IsFP ? -1 : Instruction::Or;
1394 return IsFP ? -1 : Instruction::Xor;
1399 bool &IsElementwise) {
1497Type *BitcodeReader::getTypeByID(
unsigned ID) {
1499 if (ID >= TypeList.size())
1502 if (
Type *Ty = TypeList[ID])
1507 return TypeList[
ID] = createIdentifiedStructType(
Context);
1510unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1511 auto It = ContainedTypeIDs.
find(ID);
1512 if (It == ContainedTypeIDs.
end())
1513 return InvalidTypeID;
1515 if (Idx >= It->second.size())
1516 return InvalidTypeID;
1518 return It->second[Idx];
1521Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1522 if (ID >= TypeList.size())
1529 return getTypeByID(getContainedTypeID(ID, 0));
1532unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1533 ArrayRef<unsigned> ChildTypeIDs) {
1534 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1535 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1536 auto It = VirtualTypeIDs.
find(CacheKey);
1537 if (It != VirtualTypeIDs.
end()) {
1543 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1544 "Incorrect cached contained type IDs");
1548 unsigned TypeID = TypeList.size();
1549 TypeList.push_back(Ty);
1550 if (!ChildTypeIDs.
empty())
1571 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1585 if (Opcode == Instruction::GetElementPtr)
1589 case Instruction::FNeg:
1590 case Instruction::Select:
1591 case Instruction::ICmp:
1592 case Instruction::FCmp:
1599Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1600 BasicBlock *InsertBB) {
1602 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1604 return ValueList[StartValID];
1606 SmallDenseMap<unsigned, Value *> MaterializedValues;
1607 SmallVector<unsigned> Worklist;
1609 while (!Worklist.
empty()) {
1610 unsigned ValID = Worklist.
back();
1611 if (MaterializedValues.
count(ValID)) {
1617 if (ValID >= ValueList.
size() || !ValueList[ValID])
1618 return error(
"Invalid value ID");
1620 Value *
V = ValueList[ValID];
1623 MaterializedValues.
insert({ValID,
V});
1631 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1632 auto It = MaterializedValues.
find(OpID);
1633 if (It != MaterializedValues.
end())
1634 Ops.push_back(It->second);
1641 if (
Ops.size() != BC->getOperandIDs().size())
1643 std::reverse(
Ops.begin(),
Ops.end());
1660 switch (BC->Opcode) {
1661 case BitcodeConstant::ConstantPtrAuthOpcode: {
1664 return error(
"ptrauth key operand must be ConstantInt");
1668 return error(
"ptrauth disc operand must be ConstantInt");
1671 ConstOps.
size() > 4 ? ConstOps[4]
1676 "ptrauth deactivation symbol operand must be a pointer");
1679 DeactivationSymbol);
1682 case BitcodeConstant::NoCFIOpcode: {
1685 return error(
"no_cfi operand must be GlobalValue");
1689 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1692 return error(
"dso_local operand must be GlobalValue");
1696 case BitcodeConstant::BlockAddressOpcode: {
1699 return error(
"blockaddress operand must be a function");
1704 unsigned BBID = BC->BlockAddressBB;
1707 return error(
"Invalid ID");
1710 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1712 return error(
"Invalid ID");
1719 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1721 BasicBlockFwdRefQueue.push_back(Fn);
1722 if (FwdBBs.size() < BBID + 1)
1723 FwdBBs.resize(BBID + 1);
1731 case BitcodeConstant::ConstantStructOpcode: {
1733 if (
ST->getNumElements() != ConstOps.
size())
1734 return error(
"Invalid number of elements in struct initializer");
1736 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1737 if (
Op->getType() != Ty)
1738 return error(
"Incorrect type in struct initializer");
1743 case BitcodeConstant::ConstantArrayOpcode: {
1745 if (AT->getNumElements() != ConstOps.
size())
1746 return error(
"Invalid number of elements in array initializer");
1748 for (Constant *
Op : ConstOps)
1749 if (
Op->getType() != AT->getElementType())
1750 return error(
"Incorrect type in array initializer");
1755 case BitcodeConstant::ConstantVectorOpcode: {
1757 if (VT->getNumElements() != ConstOps.size())
1758 return error(
"Invalid number of elements in vector initializer");
1760 for (Constant *
Op : ConstOps)
1761 if (
Op->getType() != VT->getElementType())
1762 return error(
"Incorrect type in vector initializer");
1767 case Instruction::GetElementPtr:
1769 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1772 case Instruction::ExtractElement:
1775 case Instruction::InsertElement:
1779 case Instruction::ShuffleVector: {
1780 SmallVector<int, 16>
Mask;
1792 MaterializedValues.
insert({ValID,
C});
1798 return error(Twine(
"Value referenced by initializer is an unsupported "
1799 "constant expression of type ") +
1800 BC->getOpcodeName());
1806 BC->getType(),
"constexpr", InsertBB);
1809 "constexpr", InsertBB);
1812 Ops[1],
"constexpr", InsertBB);
1815 I->setHasNoSignedWrap();
1817 I->setHasNoUnsignedWrap();
1823 switch (BC->Opcode) {
1824 case BitcodeConstant::ConstantVectorOpcode: {
1825 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1828 Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1835 case BitcodeConstant::ConstantStructOpcode:
1836 case BitcodeConstant::ConstantArrayOpcode: {
1840 "constexpr.ins", InsertBB);
1844 case Instruction::ICmp:
1845 case Instruction::FCmp:
1848 "constexpr", InsertBB);
1850 case Instruction::GetElementPtr:
1856 case Instruction::Select:
1859 case Instruction::ExtractElement:
1862 case Instruction::InsertElement:
1866 case Instruction::ShuffleVector:
1867 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1875 MaterializedValues.
insert({ValID,
I});
1879 return MaterializedValues[StartValID];
1882Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1883 Expected<Value *> MaybeV = materializeValue(ID,
nullptr);
1891StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1894 IdentifiedStructTypes.push_back(Ret);
1898StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1900 IdentifiedStructTypes.push_back(Ret);
1916 case Attribute::ZExt:
return 1 << 0;
1917 case Attribute::SExt:
return 1 << 1;
1918 case Attribute::NoReturn:
return 1 << 2;
1919 case Attribute::InReg:
return 1 << 3;
1920 case Attribute::StructRet:
return 1 << 4;
1921 case Attribute::NoUnwind:
return 1 << 5;
1922 case Attribute::NoAlias:
return 1 << 6;
1923 case Attribute::ByVal:
return 1 << 7;
1924 case Attribute::Nest:
return 1 << 8;
1925 case Attribute::ReadNone:
return 1 << 9;
1926 case Attribute::ReadOnly:
return 1 << 10;
1927 case Attribute::NoInline:
return 1 << 11;
1928 case Attribute::AlwaysInline:
return 1 << 12;
1929 case Attribute::OptimizeForSize:
return 1 << 13;
1930 case Attribute::StackProtect:
return 1 << 14;
1931 case Attribute::StackProtectReq:
return 1 << 15;
1932 case Attribute::Alignment:
return 31 << 16;
1934 case Attribute::NoRedZone:
return 1 << 22;
1935 case Attribute::NoImplicitFloat:
return 1 << 23;
1936 case Attribute::Naked:
return 1 << 24;
1937 case Attribute::InlineHint:
return 1 << 25;
1938 case Attribute::StackAlignment:
return 7 << 26;
1939 case Attribute::ReturnsTwice:
return 1 << 29;
1940 case Attribute::UWTable:
return 1 << 30;
1941 case Attribute::NonLazyBind:
return 1U << 31;
1942 case Attribute::SanitizeAddress:
return 1ULL << 32;
1943 case Attribute::MinSize:
return 1ULL << 33;
1944 case Attribute::NoDuplicate:
return 1ULL << 34;
1945 case Attribute::StackProtectStrong:
return 1ULL << 35;
1946 case Attribute::SanitizeThread:
return 1ULL << 36;
1947 case Attribute::SanitizeMemory:
return 1ULL << 37;
1948 case Attribute::NoBuiltin:
return 1ULL << 38;
1949 case Attribute::Returned:
return 1ULL << 39;
1950 case Attribute::Cold:
return 1ULL << 40;
1951 case Attribute::Builtin:
return 1ULL << 41;
1952 case Attribute::OptimizeNone:
return 1ULL << 42;
1953 case Attribute::InAlloca:
return 1ULL << 43;
1954 case Attribute::NonNull:
return 1ULL << 44;
1955 case Attribute::JumpTable:
return 1ULL << 45;
1956 case Attribute::Convergent:
return 1ULL << 46;
1957 case Attribute::SafeStack:
return 1ULL << 47;
1958 case Attribute::NoRecurse:
return 1ULL << 48;
1961 case Attribute::SwiftSelf:
return 1ULL << 51;
1962 case Attribute::SwiftError:
return 1ULL << 52;
1963 case Attribute::WriteOnly:
return 1ULL << 53;
1964 case Attribute::Speculatable:
return 1ULL << 54;
1965 case Attribute::StrictFP:
return 1ULL << 55;
1966 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1967 case Attribute::NoCfCheck:
return 1ULL << 57;
1968 case Attribute::OptForFuzzing:
return 1ULL << 58;
1969 case Attribute::ShadowCallStack:
return 1ULL << 59;
1970 case Attribute::SpeculativeLoadHardening:
1972 case Attribute::ImmArg:
1974 case Attribute::WillReturn:
1976 case Attribute::NoFree:
1992 if (
I == Attribute::Alignment)
1993 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
1994 else if (
I == Attribute::StackAlignment)
1995 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
1997 B.addTypeAttr(
I,
nullptr);
2011 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
2013 "Alignment must be a power of two.");
2016 B.addAlignmentAttr(Alignment);
2018 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
2019 (EncodedAttrs & 0xffff);
2021 if (AttrIdx == AttributeList::FunctionIndex) {
2024 if (Attrs & (1ULL << 9)) {
2026 Attrs &= ~(1ULL << 9);
2029 if (Attrs & (1ULL << 10)) {
2031 Attrs &= ~(1ULL << 10);
2034 if (Attrs & (1ULL << 49)) {
2036 Attrs &= ~(1ULL << 49);
2039 if (Attrs & (1ULL << 50)) {
2041 Attrs &= ~(1ULL << 50);
2044 if (Attrs & (1ULL << 53)) {
2046 Attrs &= ~(1ULL << 53);
2050 B.addMemoryAttr(ME);
2054 if (Attrs & (1ULL << 21)) {
2055 Attrs &= ~(1ULL << 21);
2062Error BitcodeReader::parseAttributeBlock() {
2066 if (!MAttributes.empty())
2067 return error(
"Invalid multiple blocks");
2069 SmallVector<uint64_t, 64>
Record;
2078 BitstreamEntry
Entry = MaybeEntry.
get();
2080 switch (
Entry.Kind) {
2083 return error(
"Malformed block");
2096 switch (MaybeRecord.
get()) {
2102 return error(
"Invalid parameter attribute record");
2104 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2110 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2115 Attrs.push_back(MAttributeGroups[Val]);
2117 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2130 return Attribute::Alignment;
2132 return Attribute::AlwaysInline;
2134 return Attribute::Builtin;
2136 return Attribute::ByVal;
2138 return Attribute::InAlloca;
2140 return Attribute::Cold;
2142 return Attribute::Convergent;
2144 return Attribute::DisableSanitizerInstrumentation;
2146 return Attribute::ElementType;
2148 return Attribute::FnRetThunkExtern;
2150 return Attribute::Flatten;
2152 return Attribute::HybridPatchable;
2154 return Attribute::InlineHint;
2156 return Attribute::InReg;
2158 return Attribute::JumpTable;
2160 return Attribute::Memory;
2162 return Attribute::NoFPClass;
2164 return Attribute::MinSize;
2166 return Attribute::Naked;
2168 return Attribute::Nest;
2170 return Attribute::NoAlias;
2172 return Attribute::NoBuiltin;
2174 return Attribute::NoCallback;
2176 return Attribute::NoDivergenceSource;
2178 return Attribute::NoDuplicate;
2180 return Attribute::NoFree;
2182 return Attribute::NoFreeObj;
2184 return Attribute::NoImplicitFloat;
2186 return Attribute::NoInline;
2188 return Attribute::NoRecurse;
2190 return Attribute::NoMerge;
2192 return Attribute::NonLazyBind;
2194 return Attribute::NonNull;
2196 return Attribute::Dereferenceable;
2198 return Attribute::DereferenceableOrNull;
2200 return Attribute::AllocAlign;
2202 return Attribute::AllocKind;
2204 return Attribute::AllocSize;
2206 return Attribute::AllocatedPointer;
2208 return Attribute::NoRedZone;
2210 return Attribute::NoReturn;
2212 return Attribute::NoSync;
2214 return Attribute::NoCfCheck;
2216 return Attribute::NoProfile;
2218 return Attribute::SkipProfile;
2220 return Attribute::NoUnwind;
2222 return Attribute::NoSanitizeBounds;
2224 return Attribute::NoSanitizeCoverage;
2226 return Attribute::NullPointerIsValid;
2228 return Attribute::OptimizeForDebugging;
2230 return Attribute::OptForFuzzing;
2232 return Attribute::OptimizeForSize;
2234 return Attribute::OptimizeNone;
2236 return Attribute::ReadNone;
2238 return Attribute::ReadOnly;
2240 return Attribute::Returned;
2242 return Attribute::ReturnsTwice;
2244 return Attribute::SExt;
2246 return Attribute::Speculatable;
2248 return Attribute::StackAlignment;
2250 return Attribute::StackProtect;
2252 return Attribute::StackProtectReq;
2254 return Attribute::StackProtectStrong;
2256 return Attribute::SafeStack;
2258 return Attribute::ShadowCallStack;
2260 return Attribute::StrictFP;
2262 return Attribute::StructRet;
2264 return Attribute::SanitizeAddress;
2266 return Attribute::SanitizeHWAddress;
2268 return Attribute::SanitizeThread;
2270 return Attribute::SanitizeType;
2272 return Attribute::SanitizeMemory;
2274 return Attribute::SanitizeNumericalStability;
2276 return Attribute::SanitizeRealtime;
2278 return Attribute::SanitizeRealtimeBlocking;
2280 return Attribute::SanitizeAllocToken;
2282 return Attribute::SpeculativeLoadHardening;
2284 return Attribute::SwiftError;
2286 return Attribute::SwiftSelf;
2288 return Attribute::SwiftAsync;
2290 return Attribute::UWTable;
2292 return Attribute::VScaleRange;
2294 return Attribute::WillReturn;
2296 return Attribute::WriteOnly;
2298 return Attribute::ZExt;
2300 return Attribute::ImmArg;
2302 return Attribute::SanitizeMemTag;
2304 return Attribute::Preallocated;
2306 return Attribute::NoUndef;
2308 return Attribute::ByRef;
2310 return Attribute::MustProgress;
2312 return Attribute::Hot;
2314 return Attribute::PresplitCoroutine;
2316 return Attribute::Writable;
2318 return Attribute::CoroDestroyOnlyWhenComplete;
2320 return Attribute::DeadOnUnwind;
2322 return Attribute::Range;
2324 return Attribute::Initializes;
2326 return Attribute::CoroElideSafe;
2328 return Attribute::NoExt;
2330 return Attribute::Captures;
2332 return Attribute::DeadOnReturn;
2334 return Attribute::NoCreateUndefOrPoison;
2336 return Attribute::DenormalFPEnv;
2338 return Attribute::NoOutline;
2340 return Attribute::NoIPA;
2345 MaybeAlign &Alignment) {
2348 if (
Exponent > Value::MaxAlignmentExponent + 1)
2349 return error(
"Invalid alignment value");
2354Error BitcodeReader::parseAttrKind(
uint64_t Code, Attribute::AttrKind *Kind) {
2356 if (*Kind == Attribute::None)
2357 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2362 switch (EncodedKind) {
2386Error BitcodeReader::parseAttributeGroupBlock() {
2390 if (!MAttributeGroups.empty())
2391 return error(
"Invalid multiple blocks");
2393 SmallVector<uint64_t, 64>
Record;
2400 BitstreamEntry
Entry = MaybeEntry.
get();
2402 switch (
Entry.Kind) {
2405 return error(
"Malformed block");
2418 switch (MaybeRecord.
get()) {
2423 return error(
"Invalid grp record");
2430 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2431 if (Record[i] == 0) {
2432 Attribute::AttrKind
Kind;
2434 if (Idx == AttributeList::FunctionIndex &&
2443 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2449 if (Kind == Attribute::ByVal)
2450 B.addByValAttr(
nullptr);
2451 else if (Kind == Attribute::StructRet)
2452 B.addStructRetAttr(
nullptr);
2453 else if (Kind == Attribute::InAlloca)
2454 B.addInAllocaAttr(
nullptr);
2455 else if (Kind == Attribute::UWTable)
2456 B.addUWTableAttr(UWTableKind::Default);
2457 else if (Kind == Attribute::DeadOnReturn)
2458 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2459 else if (Attribute::isEnumAttrKind(Kind))
2460 B.addAttribute(Kind);
2462 return error(
"Not an enum attribute");
2463 }
else if (Record[i] == 1) {
2464 Attribute::AttrKind
Kind;
2465 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2467 if (!Attribute::isIntAttrKind(Kind))
2468 return error(
"Not an int attribute");
2469 if (Kind == Attribute::Alignment)
2470 B.addAlignmentAttr(Record[++i]);
2471 else if (Kind == Attribute::StackAlignment)
2472 B.addStackAlignmentAttr(Record[++i]);
2473 else if (Kind == Attribute::Dereferenceable)
2474 B.addDereferenceableAttr(Record[++i]);
2475 else if (Kind == Attribute::DereferenceableOrNull)
2476 B.addDereferenceableOrNullAttr(Record[++i]);
2477 else if (Kind == Attribute::DeadOnReturn)
2478 B.addDeadOnReturnAttr(
2480 else if (Kind == Attribute::AllocSize)
2481 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2482 else if (Kind == Attribute::VScaleRange)
2483 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2484 else if (Kind == Attribute::UWTable)
2486 else if (Kind == Attribute::AllocKind)
2487 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2488 else if (Kind == Attribute::Memory) {
2490 const uint8_t
Version = (EncodedME >> 56);
2504 if (getTargetTriple().isAArch64())
2509 B.addMemoryAttr(ME);
2514 EncodedME & 0x00FFFFFFFFFFFFFFULL);
2517 if (
Version == 1 && getTargetTriple().isAArch64())
2519 IRMemLocation::TargetMem0,
2520 ME.
getModRef(IRMemLocation::InaccessibleMem)) |
2522 IRMemLocation::TargetMem1,
2523 ME.
getModRef(IRMemLocation::InaccessibleMem));
2524 B.addMemoryAttr(ME);
2526 }
else if (Kind == Attribute::Captures)
2528 else if (Kind == Attribute::NoFPClass)
2531 else if (Kind == Attribute::DenormalFPEnv) {
2532 B.addDenormalFPEnvAttr(
2535 }
else if (Record[i] == 3 || Record[i] == 4) {
2537 SmallString<64> KindStr;
2538 SmallString<64> ValStr;
2540 while (Record[i] != 0 && i != e)
2542 assert(Record[i] == 0 &&
"Kind string not null terminated");
2547 while (Record[i] != 0 && i != e)
2549 assert(Record[i] == 0 &&
"Value string not null terminated");
2552 B.addAttribute(KindStr.
str(), ValStr.
str());
2553 }
else if (Record[i] == 5 || Record[i] == 6) {
2554 bool HasType =
Record[i] == 6;
2555 Attribute::AttrKind
Kind;
2556 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2558 if (!Attribute::isTypeAttrKind(Kind))
2559 return error(
"Not a type attribute");
2561 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2562 }
else if (Record[i] == 7) {
2563 Attribute::AttrKind
Kind;
2566 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2568 if (!Attribute::isConstantRangeAttrKind(Kind))
2569 return error(
"Not a ConstantRange attribute");
2571 Expected<ConstantRange> MaybeCR =
2572 readBitWidthAndConstantRange(Record, i);
2577 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2578 }
else if (Record[i] == 8) {
2579 Attribute::AttrKind
Kind;
2582 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2584 if (!Attribute::isConstantRangeListAttrKind(Kind))
2585 return error(
"Not a constant range list attribute");
2589 return error(
"Too few records for constant range list");
2590 unsigned RangeSize =
Record[i++];
2592 for (
unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2593 Expected<ConstantRange> MaybeCR =
2594 readConstantRange(Record, i,
BitWidth);
2602 return error(
"Invalid (unordered or overlapping) range list");
2603 B.addConstantRangeListAttr(Kind, Val);
2605 return error(
"Invalid attribute group entry");
2610 B.addMemoryAttr(ME);
2613 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2620Error BitcodeReader::parseTypeTable() {
2624 return parseTypeTableBody();
2627Error BitcodeReader::parseTypeTableBody() {
2628 if (!TypeList.empty())
2629 return error(
"Invalid multiple blocks");
2631 SmallVector<uint64_t, 64>
Record;
2632 unsigned NumRecords = 0;
2641 BitstreamEntry
Entry = MaybeEntry.
get();
2643 switch (
Entry.Kind) {
2646 return error(
"Malformed block");
2648 if (NumRecords != TypeList.size())
2649 return error(
"Malformed block");
2658 Type *ResultTy =
nullptr;
2659 SmallVector<unsigned> ContainedIDs;
2663 switch (MaybeRecord.
get()) {
2665 return error(
"Invalid value");
2670 return error(
"Invalid numentry record");
2671 TypeList.resize(Record[0]);
2674 ResultTy = Type::getVoidTy(
Context);
2677 ResultTy = Type::getHalfTy(
Context);
2680 ResultTy = Type::getBFloatTy(
Context);
2683 ResultTy = Type::getFloatTy(
Context);
2686 ResultTy = Type::getDoubleTy(
Context);
2689 ResultTy = Type::getX86_FP80Ty(
Context);
2692 ResultTy = Type::getFP128Ty(
Context);
2695 ResultTy = Type::getPPC_FP128Ty(
Context);
2698 ResultTy = Type::getLabelTy(
Context);
2701 ResultTy = Type::getMetadataTy(
Context);
2709 ResultTy = Type::getX86_AMXTy(
Context);
2712 ResultTy = Type::getTokenTy(
Context);
2716 return error(
"Invalid record");
2721 return error(
"Bitwidth for byte type out of range");
2727 return error(
"Invalid integer record");
2732 return error(
"Bitwidth for integer type out of range");
2739 return error(
"Invalid pointer record");
2743 ResultTy = getTypeByID(Record[0]);
2745 !PointerType::isValidElementType(ResultTy))
2746 return error(
"Invalid type");
2753 return error(
"Invalid opaque pointer record");
2762 return error(
"Invalid function record");
2764 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2765 if (
Type *
T = getTypeByID(Record[i]))
2771 ResultTy = getTypeByID(Record[2]);
2772 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2773 return error(
"Invalid type");
2776 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2782 return error(
"Invalid function record");
2784 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2785 if (
Type *
T = getTypeByID(Record[i])) {
2786 if (!FunctionType::isValidArgumentType(
T))
2787 return error(
"Invalid function argument type");
2794 ResultTy = getTypeByID(Record[1]);
2795 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2796 return error(
"Invalid type");
2799 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2804 return error(
"Invalid anon struct record");
2806 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2807 if (
Type *
T = getTypeByID(Record[i]))
2813 return error(
"Invalid type");
2820 return error(
"Invalid struct name record");
2825 return error(
"Invalid named struct record");
2827 if (NumRecords >= TypeList.size())
2828 return error(
"Invalid TYPE table");
2834 TypeList[NumRecords] =
nullptr;
2836 Res = createIdentifiedStructType(
Context, TypeName);
2840 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2841 if (
Type *
T = getTypeByID(Record[i]))
2847 return error(
"Invalid named struct record");
2856 return error(
"Invalid opaque type record");
2858 if (NumRecords >= TypeList.size())
2859 return error(
"Invalid TYPE table");
2865 TypeList[NumRecords] =
nullptr;
2867 Res = createIdentifiedStructType(
Context, TypeName);
2874 return error(
"Invalid target extension type record");
2876 if (NumRecords >= TypeList.size())
2877 return error(
"Invalid TYPE table");
2879 if (Record[0] >=
Record.size())
2880 return error(
"Too many type parameters");
2882 unsigned NumTys =
Record[0];
2884 SmallVector<unsigned, 8> IntParams;
2885 for (
unsigned i = 0; i < NumTys; i++) {
2886 if (
Type *
T = getTypeByID(Record[i + 1]))
2889 return error(
"Invalid type");
2892 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2893 if (Record[i] > UINT_MAX)
2894 return error(
"Integer parameter too large");
2899 if (
auto E = TTy.takeError())
2907 return error(
"Invalid array type record");
2908 ResultTy = getTypeByID(Record[1]);
2909 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2910 return error(
"Invalid type");
2912 ResultTy = ArrayType::get(ResultTy, Record[0]);
2917 return error(
"Invalid vector type record");
2919 return error(
"Invalid vector length");
2920 ResultTy = getTypeByID(Record[1]);
2921 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2922 return error(
"Invalid type");
2925 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2929 if (NumRecords >= TypeList.size())
2930 return error(
"Invalid TYPE table");
2931 if (TypeList[NumRecords])
2933 "Invalid TYPE table: Only named structs can be forward referenced");
2934 assert(ResultTy &&
"Didn't read a type?");
2935 TypeList[NumRecords] = ResultTy;
2936 if (!ContainedIDs.
empty())
2937 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2942Error BitcodeReader::parseOperandBundleTags() {
2946 if (!BundleTags.empty())
2947 return error(
"Invalid multiple blocks");
2949 SmallVector<uint64_t, 64>
Record;
2955 BitstreamEntry
Entry = MaybeEntry.
get();
2957 switch (
Entry.Kind) {
2960 return error(
"Malformed block");
2974 return error(
"Invalid operand bundle record");
2977 BundleTags.emplace_back();
2979 return error(
"Invalid operand bundle record");
2984Error BitcodeReader::parseSyncScopeNames() {
2989 return error(
"Invalid multiple synchronization scope names blocks");
2991 SmallVector<uint64_t, 64>
Record;
2996 BitstreamEntry
Entry = MaybeEntry.
get();
2998 switch (
Entry.Kind) {
3001 return error(
"Malformed block");
3004 return error(
"Invalid empty synchronization scope names block");
3018 return error(
"Invalid sync scope record");
3020 SmallString<16> SSN;
3022 return error(
"Invalid sync scope record");
3030Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
3031 unsigned NameIndex, Triple &TT) {
3034 return error(
"Invalid record");
3035 unsigned ValueID =
Record[0];
3036 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3037 return error(
"Invalid record");
3038 Value *
V = ValueList[ValueID];
3041 if (NameStr.contains(0))
3042 return error(
"Invalid value name");
3043 V->setName(NameStr);
3045 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
3058 return std::move(JumpFailed);
3064 return error(
"Expected value symbol table subblock");
3068void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
3070 ArrayRef<uint64_t> Record) {
3075 uint64_t FuncBitOffset = FuncWordOffset * 32;
3076 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3080 if (FuncBitOffset > LastFunctionBlockBit)
3081 LastFunctionBlockBit = FuncBitOffset;
3085Error BitcodeReader::parseGlobalValueSymbolTable() {
3086 unsigned FuncBitcodeOffsetDelta =
3092 SmallVector<uint64_t, 64>
Record;
3097 BitstreamEntry
Entry = MaybeEntry.
get();
3099 switch (
Entry.Kind) {
3102 return error(
"Malformed block");
3113 switch (MaybeRecord.
get()) {
3115 unsigned ValueID =
Record[0];
3116 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3117 return error(
"Invalid value reference in symbol table");
3118 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3135 if (!MaybeCurrentBit)
3137 CurrentBit = MaybeCurrentBit.
get();
3140 if (
Error Err = parseGlobalValueSymbolTable())
3161 unsigned FuncBitcodeOffsetDelta =
3167 SmallVector<uint64_t, 64>
Record;
3178 BitstreamEntry
Entry = MaybeEntry.
get();
3180 switch (
Entry.Kind) {
3183 return error(
"Malformed block");
3199 switch (MaybeRecord.
get()) {
3203 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3211 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3219 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3224 return error(
"Invalid bbentry record");
3227 return error(
"Invalid bbentry record");
3249Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3250 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3251 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3252 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3254 GlobalInitWorklist.swap(GlobalInits);
3255 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3256 FunctionOperandWorklist.swap(FunctionOperands);
3258 while (!GlobalInitWorklist.empty()) {
3259 unsigned ValID = GlobalInitWorklist.back().second;
3260 if (ValID >= ValueList.
size()) {
3262 GlobalInits.push_back(GlobalInitWorklist.back());
3264 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3267 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3269 GlobalInitWorklist.pop_back();
3272 while (!IndirectSymbolInitWorklist.empty()) {
3273 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3274 if (ValID >= ValueList.
size()) {
3275 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3277 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3281 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3284 return error(
"Alias and aliasee types don't match");
3289 return error(
"Expected an alias or an ifunc");
3292 IndirectSymbolInitWorklist.pop_back();
3295 while (!FunctionOperandWorklist.empty()) {
3296 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3297 if (
Info.PersonalityFn) {
3298 unsigned ValID =
Info.PersonalityFn - 1;
3299 if (ValID < ValueList.
size()) {
3300 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3303 Info.F->setPersonalityFn(MaybeC.
get());
3304 Info.PersonalityFn = 0;
3308 unsigned ValID =
Info.Prefix - 1;
3309 if (ValID < ValueList.
size()) {
3310 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3313 Info.F->setPrefixData(MaybeC.
get());
3317 if (
Info.Prologue) {
3318 unsigned ValID =
Info.Prologue - 1;
3319 if (ValID < ValueList.
size()) {
3320 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3323 Info.F->setPrologueData(MaybeC.
get());
3327 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3328 FunctionOperands.push_back(Info);
3329 FunctionOperandWorklist.pop_back();
3338 BitcodeReader::decodeSignRotatedValue);
3340 return APInt(TypeBits, Words);
3343Error BitcodeReader::parseConstants() {
3351 unsigned Int32TyID = getVirtualTypeID(CurTy);
3352 unsigned CurTyID = Int32TyID;
3353 Type *CurElemTy =
nullptr;
3354 unsigned NextCstNo = ValueList.
size();
3362 switch (Entry.Kind) {
3365 return error(
"Malformed block");
3367 if (NextCstNo != ValueList.
size())
3368 return error(
"Invalid constant reference");
3379 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
3382 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3392 return error(
"Invalid settype record");
3393 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3394 return error(
"Invalid settype record");
3395 if (TypeList[Record[0]] == VoidType)
3396 return error(
"Invalid constant type");
3398 CurTy = TypeList[CurTyID];
3399 CurElemTy = getPtrElementTypeByID(CurTyID);
3403 return error(
"Invalid type for a constant null value");
3406 return error(
"Invalid type for a constant null value");
3411 return error(
"Invalid integer const record");
3416 return error(
"Invalid wide integer const record");
3419 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3420 V = ConstantInt::get(CurTy, VInt);
3425 return error(
"Invalid byte const record");
3426 V = ConstantByte::get(CurTy, decodeSignRotatedValue(Record[0]),
3431 return error(
"Invalid wide byte const record");
3434 APInt VByte =
readWideAPInt(Record, ScalarTy->getBitWidth());
3435 V = ConstantByte::get(CurTy, VByte);
3440 return error(
"Invalid float const record");
3443 if (ScalarTy->isHalfTy())
3444 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3445 APInt(16, (uint16_t)Record[0])));
3446 else if (ScalarTy->isBFloatTy())
3447 V = ConstantFP::get(
3448 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3449 else if (ScalarTy->isFloatTy())
3450 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3451 APInt(32, (uint32_t)Record[0])));
3452 else if (ScalarTy->isDoubleTy())
3453 V = ConstantFP::get(
3454 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3455 else if (ScalarTy->isX86_FP80Ty()) {
3458 Rearrange[0] = (
Record[1] & 0xffffLL) | (Record[0] << 16);
3459 Rearrange[1] =
Record[0] >> 48;
3460 V = ConstantFP::get(
3461 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3462 }
else if (ScalarTy->isFP128Ty())
3463 V = ConstantFP::get(CurTy,
3464 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3465 else if (ScalarTy->isPPC_FP128Ty())
3466 V = ConstantFP::get(
3467 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3475 return error(
"Invalid aggregate record");
3477 SmallVector<unsigned, 16> Elts;
3481 V = BitcodeConstant::create(
3482 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3484 V = BitcodeConstant::create(
Alloc, CurTy,
3485 BitcodeConstant::ConstantArrayOpcode, Elts);
3487 V = BitcodeConstant::create(
3488 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3497 return error(
"Invalid string record");
3507 return error(
"Invalid data record");
3511 return error(
"Invalid type for value");
3514 SmallString<128> RawData;
3517 const char *Src =
reinterpret_cast<const char *
>(&Val);
3519 Src +=
sizeof(
uint64_t) - EltBytes;
3520 RawData.
append(Src, Src + EltBytes);
3525 : ConstantDataArray::getRaw(RawData.str(),
Record.
size(), EltTy);
3530 return error(
"Invalid unary op constexpr record");
3535 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3541 return error(
"Invalid binary op constexpr record");
3547 if (
Record.size() >= 4) {
3548 if (
Opc == Instruction::Add ||
3549 Opc == Instruction::Sub ||
3550 Opc == Instruction::Mul ||
3551 Opc == Instruction::Shl) {
3556 }
else if (
Opc == Instruction::SDiv ||
3557 Opc == Instruction::UDiv ||
3558 Opc == Instruction::LShr ||
3559 Opc == Instruction::AShr) {
3564 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3565 {(unsigned)Record[1], (
unsigned)
Record[2]});
3571 return error(
"Invalid cast constexpr record");
3576 unsigned OpTyID =
Record[1];
3577 Type *OpTy = getTypeByID(OpTyID);
3579 return error(
"Invalid cast constexpr record");
3580 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3592 return error(
"Constant GEP record must have at least two elements");
3594 Type *PointeeType =
nullptr;
3598 PointeeType = getTypeByID(Record[OpNum++]);
3601 std::optional<ConstantRange>
InRange;
3605 unsigned InRangeIndex =
Op >> 1;
3611 Expected<ConstantRange> MaybeInRange =
3612 readBitWidthAndConstantRange(Record, OpNum);
3621 SmallVector<unsigned, 16> Elts;
3622 unsigned BaseTypeID =
Record[OpNum];
3623 while (OpNum !=
Record.size()) {
3624 unsigned ElTyID =
Record[OpNum++];
3625 Type *ElTy = getTypeByID(ElTyID);
3627 return error(
"Invalid getelementptr constexpr record");
3631 if (Elts.
size() < 1)
3632 return error(
"Invalid gep with no operands");
3636 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3637 BaseType = getTypeByID(BaseTypeID);
3642 return error(
"GEP base operand must be pointer or vector of pointer");
3645 PointeeType = getPtrElementTypeByID(BaseTypeID);
3647 return error(
"Missing element type for old-style constant GEP");
3650 V = BitcodeConstant::create(
3652 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3658 return error(
"Invalid select constexpr record");
3660 V = BitcodeConstant::create(
3661 Alloc, CurTy, Instruction::Select,
3662 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3668 return error(
"Invalid extractelement constexpr record");
3669 unsigned OpTyID =
Record[0];
3673 return error(
"Invalid extractelement constexpr record");
3675 if (
Record.size() == 4) {
3676 unsigned IdxTyID =
Record[2];
3677 Type *IdxTy = getTypeByID(IdxTyID);
3679 return error(
"Invalid extractelement constexpr record");
3685 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3686 {(unsigned)Record[1], IdxRecord});
3692 if (
Record.size() < 3 || !OpTy)
3693 return error(
"Invalid insertelement constexpr record");
3695 if (
Record.size() == 4) {
3696 unsigned IdxTyID =
Record[2];
3697 Type *IdxTy = getTypeByID(IdxTyID);
3699 return error(
"Invalid insertelement constexpr record");
3705 V = BitcodeConstant::create(
3706 Alloc, CurTy, Instruction::InsertElement,
3707 {(unsigned)Record[0], (
unsigned)
Record[1], IdxRecord});
3712 if (
Record.size() < 3 || !OpTy)
3713 return error(
"Invalid shufflevector constexpr record");
3714 V = BitcodeConstant::create(
3715 Alloc, CurTy, Instruction::ShuffleVector,
3716 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3723 if (
Record.size() < 4 || !RTy || !OpTy)
3724 return error(
"Invalid shufflevector constexpr record");
3725 V = BitcodeConstant::create(
3726 Alloc, CurTy, Instruction::ShuffleVector,
3727 {(unsigned)Record[1], (
unsigned)
Record[2], (unsigned)Record[3]});
3732 return error(
"Invalid cmp constexpt record");
3733 unsigned OpTyID =
Record[0];
3734 Type *OpTy = getTypeByID(OpTyID);
3736 return error(
"Invalid cmp constexpr record");
3737 V = BitcodeConstant::create(
3740 : Instruction::ICmp),
3741 (uint8_t)Record[3]},
3742 {(unsigned)Record[1], (
unsigned)
Record[2]});
3749 return error(
"Invalid inlineasm record");
3750 std::string AsmStr, ConstrStr;
3751 bool HasSideEffects =
Record[0] & 1;
3752 bool IsAlignStack =
Record[0] >> 1;
3753 unsigned AsmStrSize =
Record[1];
3754 if (2+AsmStrSize >=
Record.size())
3755 return error(
"Invalid inlineasm record");
3756 unsigned ConstStrSize =
Record[2+AsmStrSize];
3757 if (3+AsmStrSize+ConstStrSize >
Record.size())
3758 return error(
"Invalid inlineasm record");
3760 for (
unsigned i = 0; i != AsmStrSize; ++i)
3761 AsmStr += (
char)
Record[2+i];
3762 for (
unsigned i = 0; i != ConstStrSize; ++i)
3763 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3766 return error(
"Missing element type for old-style inlineasm");
3768 HasSideEffects, IsAlignStack);
3775 return error(
"Invalid inlineasm record");
3776 std::string AsmStr, ConstrStr;
3777 bool HasSideEffects =
Record[0] & 1;
3778 bool IsAlignStack = (
Record[0] >> 1) & 1;
3779 unsigned AsmDialect =
Record[0] >> 2;
3780 unsigned AsmStrSize =
Record[1];
3781 if (2+AsmStrSize >=
Record.size())
3782 return error(
"Invalid inlineasm record");
3783 unsigned ConstStrSize =
Record[2+AsmStrSize];
3784 if (3+AsmStrSize+ConstStrSize >
Record.size())
3785 return error(
"Invalid inlineasm record");
3787 for (
unsigned i = 0; i != AsmStrSize; ++i)
3788 AsmStr += (
char)
Record[2+i];
3789 for (
unsigned i = 0; i != ConstStrSize; ++i)
3790 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3793 return error(
"Missing element type for old-style inlineasm");
3795 HasSideEffects, IsAlignStack,
3802 return error(
"Invalid inlineasm record");
3804 std::string AsmStr, ConstrStr;
3805 bool HasSideEffects =
Record[OpNum] & 1;
3806 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3807 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3808 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3810 unsigned AsmStrSize =
Record[OpNum];
3812 if (OpNum + AsmStrSize >=
Record.size())
3813 return error(
"Invalid inlineasm record");
3814 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3815 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3816 return error(
"Invalid inlineasm record");
3818 for (
unsigned i = 0; i != AsmStrSize; ++i)
3819 AsmStr += (
char)
Record[OpNum + i];
3821 for (
unsigned i = 0; i != ConstStrSize; ++i)
3822 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3825 return error(
"Missing element type for old-style inlineasm");
3827 HasSideEffects, IsAlignStack,
3834 return error(
"Invalid inlineasm record");
3839 return error(
"Invalid inlineasm record");
3840 std::string AsmStr, ConstrStr;
3841 bool HasSideEffects =
Record[OpNum] & 1;
3842 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3843 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3844 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3846 unsigned AsmStrSize =
Record[OpNum];
3848 if (OpNum + AsmStrSize >=
Record.size())
3849 return error(
"Invalid inlineasm record");
3850 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3851 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3852 return error(
"Invalid inlineasm record");
3854 for (
unsigned i = 0; i != AsmStrSize; ++i)
3855 AsmStr += (
char)
Record[OpNum + i];
3857 for (
unsigned i = 0; i != ConstStrSize; ++i)
3858 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3860 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3866 return error(
"Invalid blockaddress record");
3867 unsigned FnTyID =
Record[0];
3868 Type *FnTy = getTypeByID(FnTyID);
3870 return error(
"Invalid blockaddress record");
3871 V = BitcodeConstant::create(
3873 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3879 return error(
"Invalid dso_local record");
3880 unsigned GVTyID =
Record[0];
3881 Type *GVTy = getTypeByID(GVTyID);
3883 return error(
"Invalid dso_local record");
3884 V = BitcodeConstant::create(
3885 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3890 return error(
"Invalid no_cfi record");
3891 unsigned GVTyID =
Record[0];
3892 Type *GVTy = getTypeByID(GVTyID);
3894 return error(
"Invalid no_cfi record");
3895 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3901 return error(
"Invalid ptrauth record");
3903 V = BitcodeConstant::create(
Alloc, CurTy,
3904 BitcodeConstant::ConstantPtrAuthOpcode,
3905 {(unsigned)Record[0], (
unsigned)
Record[1],
3906 (unsigned)Record[2], (
unsigned)
Record[3]});
3911 return error(
"Invalid ptrauth record");
3913 V = BitcodeConstant::create(
3914 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3915 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2],
3916 (
unsigned)
Record[3], (unsigned)Record[4]});
3921 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3928Error BitcodeReader::parseUseLists() {
3933 SmallVector<uint64_t, 64>
Record;
3939 BitstreamEntry
Entry = MaybeEntry.
get();
3941 switch (
Entry.Kind) {
3944 return error(
"Malformed block");
3958 switch (MaybeRecord.
get()) {
3966 if (RecordLength < 3)
3968 return error(
"Invalid uselist record");
3969 unsigned ID =
Record.pop_back_val();
3973 assert(ID < FunctionBBs.size() &&
"Basic block not found");
3974 V = FunctionBBs[
ID];
3978 if (!
V->hasUseList())
3981 unsigned NumUses = 0;
3982 SmallDenseMap<const Use *, unsigned, 16> Order;
3983 for (
const Use &U :
V->materialized_uses()) {
3984 if (++NumUses >
Record.size())
3986 Order[&
U] =
Record[NumUses - 1];
3993 V->sortUseList([&](
const Use &L,
const Use &R) {
4004Error BitcodeReader::rememberAndSkipMetadata() {
4007 DeferredMetadataInfo.push_back(CurBit);
4015Error BitcodeReader::materializeMetadata() {
4016 for (
uint64_t BitPos : DeferredMetadataInfo) {
4020 if (
Error Err = MDLoader->parseModuleMetadata())
4029 NamedMDNode *LinkerOpts =
4031 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
4038 DeferredMetadataInfo.clear();
4042void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
4046Error BitcodeReader::rememberAndSkipFunctionBody() {
4048 if (FunctionsWithBodies.empty())
4049 return error(
"Insufficient function protos");
4051 Function *Fn = FunctionsWithBodies.back();
4052 FunctionsWithBodies.pop_back();
4057 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4058 "Mismatch between VST and scanned function offsets");
4059 DeferredFunctionInfo[Fn] = CurBit;
4067Error BitcodeReader::globalCleanup() {
4069 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4071 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4072 return error(
"Malformed global initializer set");
4077 MDLoader->upgradeDebugIntrinsics(
F);
4081 !SkipDebugIntrinsicUpgrade))
4082 UpgradedIntrinsics[&
F] = NewFn;
4088 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4089 for (GlobalVariable &GV : TheModule->globals())
4091 UpgradedVariables.emplace_back(&GV, Upgraded);
4092 for (
auto &Pair : UpgradedVariables) {
4093 Pair.first->eraseFromParent();
4094 TheModule->insertGlobalVariable(Pair.second);
4097 for (
size_t ValueID = 0; ValueID < GUIDList.size(); ValueID++) {
4098 const auto GUID = GUIDList[ValueID];
4102 const auto *
Value = ValueList[ValueID];
4103 TheModule->insertGUID(
Value, GUID);
4108 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
4109 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4117Error BitcodeReader::rememberAndSkipFunctionBodies() {
4122 return error(
"Could not find function in stream");
4124 if (!SeenFirstFunctionBody)
4125 return error(
"Trying to materialize functions before seeing function blocks");
4129 assert(SeenValueSymbolTable);
4132 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4135 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4137 switch (
Entry.Kind) {
4139 return error(
"Expect SubBlock");
4143 return error(
"Expect function block");
4145 if (
Error Err = rememberAndSkipFunctionBody())
4154Error BitcodeReaderBase::readBlockInfo() {
4155 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4157 if (!MaybeNewBlockInfo)
4159 std::optional<BitstreamBlockInfo> NewBlockInfo =
4160 std::move(MaybeNewBlockInfo.
get());
4162 return error(
"Malformed block");
4163 BlockInfo = std::move(*NewBlockInfo);
4167Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4171 std::tie(Name, Record) = readNameFromStrtab(Record);
4174 return error(
"Invalid comdat record");
4176 std::string OldFormatName;
4179 return error(
"Invalid comdat record");
4180 unsigned ComdatNameSize =
Record[1];
4181 if (ComdatNameSize >
Record.size() - 2)
4182 return error(
"Comdat name size too large");
4183 OldFormatName.reserve(ComdatNameSize);
4184 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4185 OldFormatName += (
char)
Record[2 + i];
4186 Name = OldFormatName;
4188 Comdat *
C = TheModule->getOrInsertComdat(Name);
4189 C->setSelectionKind(SK);
4190 ComdatList.push_back(
C);
4204 Meta.NoAddress =
true;
4206 Meta.NoHWAddress =
true;
4210 Meta.IsDynInit =
true;
4214Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4222 std::tie(Name, Record) = readNameFromStrtab(Record);
4225 return error(
"Invalid global variable record");
4226 unsigned TyID =
Record[0];
4227 Type *Ty = getTypeByID(TyID);
4229 return error(
"Invalid global variable record");
4231 bool explicitType =
Record[1] & 2;
4237 return error(
"Invalid type for value");
4239 TyID = getContainedTypeID(TyID);
4240 Ty = getTypeByID(TyID);
4242 return error(
"Missing element type for old-style global");
4248 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4252 if (Record[5] - 1 >= SectionTable.size())
4253 return error(
"Invalid ID");
4262 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4270 bool ExternallyInitialized =
false;
4272 ExternallyInitialized =
Record[9];
4274 GlobalVariable *NewGV =
4284 if (
Record.size() > 10) {
4296 if (
unsigned InitID = Record[2])
4297 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4299 if (
Record.size() > 11) {
4300 if (
unsigned ComdatID = Record[11]) {
4301 if (ComdatID > ComdatList.size())
4302 return error(
"Invalid global variable comdat ID");
4303 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4306 ImplicitComdatObjects.
insert(NewGV);
4309 if (
Record.size() > 12) {
4314 if (
Record.size() > 13) {
4323 if (
Record.size() > 16 && Record[16]) {
4324 llvm::GlobalValue::SanitizerMetadata
Meta =
4329 if (
Record.size() > 17 && Record[17]) {
4333 return error(
"Invalid global variable code model");
4339void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4340 if (ValueTypeCallback) {
4341 (*ValueTypeCallback)(
4342 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4343 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4347Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4353 std::tie(Name, Record) = readNameFromStrtab(Record);
4356 return error(
"Invalid function record");
4357 unsigned FTyID =
Record[0];
4358 Type *FTy = getTypeByID(FTyID);
4360 return error(
"Invalid function record");
4362 FTyID = getContainedTypeID(FTyID, 0);
4363 FTy = getTypeByID(FTyID);
4365 return error(
"Missing element type for old-style function");
4369 return error(
"Invalid type for value");
4370 auto CC =
static_cast<CallingConv::ID
>(
Record[1]);
4371 if (CC & ~CallingConv::MaxID)
4372 return error(
"Invalid calling convention ID");
4374 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4380 AddrSpace, Name, TheModule);
4383 "Incorrect fully specified type provided for function");
4384 FunctionTypeIDs[
Func] = FTyID;
4386 Func->setCallingConv(CC);
4387 bool isProto =
Record[2];
4391 callValueTypeCallback(Func, FTyID);
4396 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4397 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4398 Attribute::InAlloca}) {
4399 if (!
Func->hasParamAttribute(i, Kind))
4402 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4405 Func->removeParamAttr(i, Kind);
4407 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4408 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4410 return error(
"Missing param element type for attribute upgrade");
4414 case Attribute::ByVal:
4415 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4417 case Attribute::StructRet:
4418 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4420 case Attribute::InAlloca:
4421 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4427 Func->addParamAttr(i, NewAttr);
4431 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4432 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4433 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4434 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4436 return error(
"Missing param element type for x86_intrcc upgrade");
4438 Func->addParamAttr(0, NewAttr);
4442 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4445 Func->setAlignment(*Alignment);
4447 if (Record[6] - 1 >= SectionTable.size())
4448 return error(
"Invalid ID");
4449 Func->setSection(SectionTable[Record[6] - 1]);
4453 if (!
Func->hasLocalLinkage())
4455 if (
Record.size() > 8 && Record[8]) {
4456 if (Record[8] - 1 >= GCTable.size())
4457 return error(
"Invalid ID");
4458 Func->setGC(GCTable[Record[8] - 1]);
4463 Func->setUnnamedAddr(UnnamedAddr);
4465 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4467 OperandInfo.Prologue =
Record[10];
4469 if (
Record.size() > 11) {
4471 if (!
Func->hasLocalLinkage()) {
4478 if (
Record.size() > 12) {
4479 if (
unsigned ComdatID = Record[12]) {
4480 if (ComdatID > ComdatList.size())
4481 return error(
"Invalid function comdat ID");
4482 Func->setComdat(ComdatList[ComdatID - 1]);
4485 ImplicitComdatObjects.
insert(Func);
4489 OperandInfo.Prefix =
Record[13];
4492 OperandInfo.PersonalityFn =
Record[14];
4494 if (
Record.size() > 15) {
4504 Record[17] + Record[18] <= Strtab.
size()) {
4505 Func->setPartition(StringRef(Strtab.
data() + Record[17], Record[18]));
4508 if (
Record.size() > 19) {
4509 MaybeAlign PrefAlignment;
4510 if (
Error Err = parseAlignmentValue(Record[19], PrefAlignment))
4512 Func->setPreferredAlignment(PrefAlignment);
4515 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4517 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4518 FunctionOperands.push_back(OperandInfo);
4523 Func->setIsMaterializable(
true);
4524 FunctionsWithBodies.push_back(Func);
4525 DeferredFunctionInfo[
Func] = 0;
4530Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4531 unsigned BitCode, ArrayRef<uint64_t> Record) {
4541 std::tie(Name, Record) = readNameFromStrtab(Record);
4544 if (
Record.size() < (3 + (
unsigned)NewRecord))
4545 return error(
"Invalid global indirect symbol record");
4550 return error(
"Invalid global indirect symbol record");
4556 return error(
"Invalid type for value");
4557 AddrSpace = PTy->getAddressSpace();
4559 Ty = getTypeByID(
TypeID);
4561 return error(
"Missing element type for old-style indirect symbol");
4563 AddrSpace =
Record[OpNum++];
4566 auto Val =
Record[OpNum++];
4575 nullptr, TheModule);
4579 if (OpNum !=
Record.size()) {
4580 auto VisInd = OpNum++;
4586 if (OpNum !=
Record.size()) {
4587 auto S =
Record[OpNum++];
4594 if (OpNum !=
Record.size())
4596 if (OpNum !=
Record.size())
4599 if (OpNum !=
Record.size())
4604 if (OpNum + 1 <
Record.size()) {
4606 if (Record[OpNum] + Record[OpNum + 1] > Strtab.
size())
4607 return error(
"Malformed partition, too large.");
4609 StringRef(Strtab.
data() + Record[OpNum], Record[OpNum + 1]));
4613 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4618 bool ShouldLazyLoadMetadata,
4619 ParserCallbacks Callbacks) {
4620 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4627 SmallVector<uint64_t, 64>
Record;
4631 bool ResolvedDataLayout =
false;
4636 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4639 Module::GlobalAsmProperties Props;
4641 auto ResolveDataLayout = [&]() ->
Error {
4642 if (ResolvedDataLayout)
4646 ResolvedDataLayout =
true;
4650 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4654 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4655 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4656 TentativeDataLayoutStr = *LayoutOverride;
4664 TheModule->setDataLayout(MaybeDL.
get());
4670 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4673 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4675 switch (
Entry.Kind) {
4677 return error(
"Malformed block");
4679 if (
Error Err = ResolveDataLayout())
4681 return globalCleanup();
4690 if (
Error Err = readBlockInfo())
4694 if (
Error Err = parseAttributeBlock())
4698 if (
Error Err = parseAttributeGroupBlock())
4702 if (
Error Err = parseTypeTable())
4706 if (!SeenValueSymbolTable) {
4712 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4713 if (
Error Err = parseValueSymbolTable())
4715 SeenValueSymbolTable =
true;
4725 if (
Error Err = parseConstants())
4727 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4731 if (ShouldLazyLoadMetadata) {
4732 if (
Error Err = rememberAndSkipMetadata())
4736 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4737 if (
Error Err = MDLoader->parseModuleMetadata())
4741 if (
Error Err = MDLoader->parseMetadataKinds())
4745 if (
Error Err = ResolveDataLayout())
4750 if (!SeenFirstFunctionBody) {
4751 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4752 if (
Error Err = globalCleanup())
4754 SeenFirstFunctionBody =
true;
4757 if (VSTOffset > 0) {
4761 if (!SeenValueSymbolTable) {
4762 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4764 SeenValueSymbolTable =
true;
4786 if (
Error Err = rememberAndSkipFunctionBody())
4793 if (SeenValueSymbolTable) {
4797 return globalCleanup();
4801 if (
Error Err = parseUseLists())
4805 if (
Error Err = parseOperandBundleTags())
4809 if (
Error Err = parseSyncScopeNames())
4821 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
4824 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4827 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4830 UseRelativeIDs = *VersionOrErr >= 1;
4834 if (ResolvedDataLayout)
4835 return error(
"target triple too late in module");
4838 return error(
"Invalid triple record");
4839 TheModule->setTargetTriple(Triple(std::move(S)));
4843 if (ResolvedDataLayout)
4844 return error(
"datalayout too late in module");
4846 return error(
"Invalid data layout record");
4852 return error(
"Invalid module asm record");
4853 size_t SepPos = Str.find(
'\0');
4854 if (SepPos == std::string::npos)
4855 return error(
"Invalid module asm record");
4856 if (!Props.
set(StringRef(Str.data(), SepPos), Str.substr(SepPos + 1)))
4857 return error(
"Unknown module asm property");
4863 return error(
"Invalid asm record");
4864 TheModule->appendModuleInlineAsm(Module::GlobalAsmFragment(S, Props));
4872 return error(
"Invalid deplib record");
4879 return error(
"Invalid section name record");
4880 SectionTable.push_back(S);
4886 return error(
"Invalid gcname record");
4887 GCTable.push_back(S);
4891 if (
Error Err = parseComdatRecord(Record))
4900 if (
Error Err = parseGlobalVarRecord(Record))
4904 if (
Error Err = ResolveDataLayout())
4906 if (
Error Err = parseFunctionRecord(Record))
4912 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4918 return error(
"Invalid vstoffset record");
4922 VSTOffset =
Record[0] - 1;
4927 GUIDList.reserve(GUIDList.size() +
Record.size() / 2);
4928 for (
size_t i = 0; i <
Record.size(); i += 2)
4929 GUIDList.push_back(Record[i] << 32 | Record[i + 1]);
4935 return error(
"Invalid source filename record");
4936 TheModule->setSourceFileName(
ValueName);
4942 this->ValueTypeCallback = std::nullopt;
4946Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4948 ParserCallbacks Callbacks) {
4950 MetadataLoaderCallbacks MDCallbacks;
4951 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(ID); };
4953 return getContainedTypeID(
I, J);
4956 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4958 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4961Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4963 return error(
"Load/Store operand is not a pointer type");
4964 if (!PointerType::isLoadableOrStorableType(ValType))
4965 return error(
"Cannot load/store from pointer");
4969Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4970 ArrayRef<unsigned> ArgTyIDs) {
4972 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4973 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4974 Attribute::InAlloca}) {
4975 if (!
Attrs.hasParamAttr(i, Kind) ||
4976 Attrs.getParamAttr(i, Kind).getValueAsType())
4979 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4981 return error(
"Missing element type for typed attribute upgrade");
4985 case Attribute::ByVal:
4986 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4988 case Attribute::StructRet:
4989 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4991 case Attribute::InAlloca:
4992 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
5005 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
5009 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
5010 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5012 return error(
"Missing element type for inline asm upgrade");
5015 Attribute::get(
Context, Attribute::ElementType, ElemTy));
5023 case Intrinsic::preserve_array_access_index:
5024 case Intrinsic::preserve_struct_access_index:
5025 case Intrinsic::aarch64_ldaxr:
5026 case Intrinsic::aarch64_ldxr:
5027 case Intrinsic::aarch64_stlxr:
5028 case Intrinsic::aarch64_stxr:
5029 case Intrinsic::arm_ldaex:
5030 case Intrinsic::arm_ldrex:
5031 case Intrinsic::arm_stlex:
5032 case Intrinsic::arm_strex: {
5035 case Intrinsic::aarch64_stlxr:
5036 case Intrinsic::aarch64_stxr:
5037 case Intrinsic::arm_stlex:
5038 case Intrinsic::arm_strex:
5045 if (!
Attrs.getParamElementType(ArgNo)) {
5046 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5048 return error(
"Missing element type for elementtype upgrade");
5068 if (MDLoader->hasFwdRefs())
5069 return error(
"Invalid function metadata: incoming forward references");
5071 InstructionList.
clear();
5072 unsigned ModuleValueListSize = ValueList.
size();
5073 unsigned ModuleMDLoaderSize = MDLoader->size();
5077 unsigned FTyID = FunctionTypeIDs[
F];
5078 for (Argument &
I :
F->args()) {
5079 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
5080 assert(
I.getType() == getTypeByID(ArgTyID) &&
5081 "Incorrect fully specified type for Function Argument");
5085 unsigned NextValueNo = ValueList.
size();
5087 unsigned CurBBNo = 0;
5092 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
5096 auto getLastInstruction = [&]() -> Instruction * {
5097 if (CurBB && !CurBB->
empty())
5098 return &CurBB->
back();
5099 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5100 !FunctionBBs[CurBBNo - 1]->
empty())
5101 return &FunctionBBs[CurBBNo - 1]->back();
5105 std::vector<OperandBundleDef> OperandBundles;
5108 SmallVector<uint64_t, 64>
Record;
5111 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
5114 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
5116 switch (
Entry.Kind) {
5118 return error(
"Malformed block");
5120 goto OutOfRecordLoop;
5129 if (
Error Err = parseConstants())
5131 NextValueNo = ValueList.
size();
5134 if (
Error Err = parseValueSymbolTable())
5138 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
5142 assert(DeferredMetadataInfo.empty() &&
5143 "Must read all module-level metadata before function-level");
5144 if (
Error Err = MDLoader->parseFunctionMetadata())
5148 if (
Error Err = parseUseLists())
5162 unsigned ResTypeID = InvalidTypeID;
5163 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
5166 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5168 return error(
"Invalid value");
5170 if (
Record.empty() || Record[0] == 0)
5171 return error(
"Invalid declareblocks record");
5173 FunctionBBs.resize(Record[0]);
5176 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5177 if (BBFRI == BasicBlockFwdRefs.
end()) {
5178 for (BasicBlock *&BB : FunctionBBs)
5181 auto &BBRefs = BBFRI->second;
5183 if (BBRefs.size() > FunctionBBs.size())
5184 return error(
"Invalid ID");
5185 assert(!BBRefs.empty() &&
"Unexpected empty array");
5186 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5187 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5189 if (
I < RE && BBRefs[
I]) {
5190 BBRefs[
I]->insertInto(
F);
5191 FunctionBBs[
I] = BBRefs[
I];
5197 BasicBlockFwdRefs.
erase(BBFRI);
5200 CurBB = FunctionBBs[0];
5207 return error(
"Invalid blockaddr users record");
5223 BackwardRefFunctions.push_back(
F);
5225 return error(
"Invalid blockaddr users record");
5232 I = getLastInstruction();
5235 return error(
"Invalid debug_loc_again record");
5236 I->setDebugLoc(LastLoc);
5241 I = getLastInstruction();
5243 return error(
"Invalid debug loc record");
5251 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5254 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5256 return error(
"Invalid debug loc record");
5260 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5262 return error(
"Invalid debug loc record");
5265 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5266 isImplicitCode, AtomGroup, AtomRank);
5267 I->setDebugLoc(LastLoc);
5275 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5277 return error(
"Invalid unary operator record");
5281 return error(
"Invalid unary operator record");
5285 if (OpNum <
Record.size()) {
5289 I->setFastMathFlags(FMF);
5298 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5302 return error(
"Invalid binary operator record");
5306 return error(
"Invalid binary operator record");
5310 if (OpNum <
Record.size()) {
5311 if (
Opc == Instruction::Add ||
5312 Opc == Instruction::Sub ||
5313 Opc == Instruction::Mul ||
5314 Opc == Instruction::Shl) {
5319 }
else if (
Opc == Instruction::SDiv ||
5320 Opc == Instruction::UDiv ||
5321 Opc == Instruction::LShr ||
5322 Opc == Instruction::AShr) {
5325 }
else if (
Opc == Instruction::Or) {
5331 I->setFastMathFlags(FMF);
5340 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5341 OpNum + 1 >
Record.size())
5342 return error(
"Invalid cast record");
5344 ResTypeID =
Record[OpNum++];
5345 Type *ResTy = getTypeByID(ResTypeID);
5348 if (
Opc == -1 || !ResTy)
5349 return error(
"Invalid cast record");
5354 assert(CurBB &&
"No current BB?");
5360 return error(
"Invalid cast");
5364 if (OpNum <
Record.size()) {
5365 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5368 }
else if (
Opc == Instruction::Trunc) {
5373 }
else if (
Opc == Instruction::AddrSpaceCast) {
5383 I->setFastMathFlags(FMF);
5402 Ty = getTypeByID(TyID);
5406 TyID = InvalidTypeID;
5411 unsigned BasePtrTypeID;
5412 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5414 return error(
"Invalid gep record");
5417 TyID = getContainedTypeID(BasePtrTypeID);
5418 if (
BasePtr->getType()->isVectorTy())
5419 TyID = getContainedTypeID(TyID);
5420 Ty = getTypeByID(TyID);
5423 SmallVector<Value*, 16> GEPIdx;
5424 while (OpNum !=
Record.size()) {
5427 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5428 return error(
"Invalid gep record");
5439 unsigned SubType = 0;
5440 if (GTI.isStruct()) {
5442 Idx->getType()->isVectorTy()
5444 :
cast<ConstantInt>(Idx);
5447 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5454 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5455 if (
I->getType()->isVectorTy())
5456 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5459 GEP->setNoWrapFlags(NW);
5468 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5469 return error(
"Invalid extractvalue record");
5472 unsigned RecSize =
Record.size();
5473 if (OpNum == RecSize)
5474 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5476 SmallVector<unsigned, 4> EXTRACTVALIdx;
5477 ResTypeID = AggTypeID;
5478 for (; OpNum != RecSize; ++OpNum) {
5483 if (!IsStruct && !IsArray)
5484 return error(
"EXTRACTVAL: Invalid type");
5485 if ((
unsigned)Index != Index)
5486 return error(
"Invalid value");
5488 return error(
"EXTRACTVAL: Invalid struct index");
5490 return error(
"EXTRACTVAL: Invalid array index");
5491 EXTRACTVALIdx.
push_back((
unsigned)Index);
5495 ResTypeID = getContainedTypeID(ResTypeID, Index);
5498 ResTypeID = getContainedTypeID(ResTypeID);
5512 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5513 return error(
"Invalid insertvalue record");
5516 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5517 return error(
"Invalid insertvalue record");
5519 unsigned RecSize =
Record.size();
5520 if (OpNum == RecSize)
5521 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5523 SmallVector<unsigned, 4> INSERTVALIdx;
5525 for (; OpNum != RecSize; ++OpNum) {
5530 if (!IsStruct && !IsArray)
5531 return error(
"INSERTVAL: Invalid type");
5532 if ((
unsigned)Index != Index)
5533 return error(
"Invalid value");
5535 return error(
"INSERTVAL: Invalid struct index");
5537 return error(
"INSERTVAL: Invalid array index");
5539 INSERTVALIdx.
push_back((
unsigned)Index);
5547 return error(
"Inserted value type doesn't match aggregate type");
5550 ResTypeID = AggTypeID;
5562 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5564 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5566 popValue(Record, OpNum, NextValueNo, CondType,
5567 getVirtualTypeID(CondType),
Cond, CurBB))
5568 return error(
"Invalid select record");
5581 unsigned ValTypeID, CondTypeID;
5582 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5584 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5586 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5587 return error(
"Invalid vector select record");
5590 if (VectorType* vector_type =
5593 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5594 return error(
"Invalid type for value");
5598 return error(
"Invalid type for value");
5602 ResTypeID = ValTypeID;
5607 I->setFastMathFlags(FMF);
5615 unsigned VecTypeID, IdxTypeID;
5616 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5617 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5618 return error(
"Invalid extractelement record");
5620 return error(
"Invalid type for value");
5622 ResTypeID = getContainedTypeID(VecTypeID);
5629 Value *Vec, *Elt, *Idx;
5630 unsigned VecTypeID, IdxTypeID;
5631 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5632 return error(
"Invalid insertelement record");
5634 return error(
"Invalid type for value");
5635 if (popValue(Record, OpNum, NextValueNo,
5637 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5638 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5639 return error(
"Invalid insert element record");
5641 ResTypeID = VecTypeID;
5649 unsigned Vec1TypeID;
5650 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5652 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5654 return error(
"Invalid shufflevector record");
5656 unsigned MaskTypeID;
5657 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5658 return error(
"Invalid shufflevector record");
5660 return error(
"Invalid type for value");
5662 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5664 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5679 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5680 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5682 return error(
"Invalid comparison record");
5684 if (OpNum >=
Record.size())
5686 "Invalid record: operand number exceeded available operands");
5691 if (IsFP &&
Record.size() > OpNum+1)
5696 return error(
"Invalid fcmp predicate");
5697 I =
new FCmpInst(PredVal,
LHS,
RHS);
5700 return error(
"Invalid icmp predicate");
5701 I =
new ICmpInst(PredVal,
LHS,
RHS);
5702 if (
Record.size() > OpNum + 1 &&
5707 if (OpNum + 1 !=
Record.size())
5708 return error(
"Invalid comparison record");
5710 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5712 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5715 I->setFastMathFlags(FMF);
5732 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5733 return error(
"Invalid ret record");
5734 if (OpNum !=
Record.size())
5735 return error(
"Invalid ret record");
5743 return error(
"Invalid br record");
5744 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5746 return error(
"Invalid br record");
5748 if (
Record.size() == 1) {
5753 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5756 getVirtualTypeID(CondType), CurBB);
5757 if (!FalseDest || !
Cond)
5758 return error(
"Invalid br record");
5766 return error(
"Invalid cleanupret record");
5769 Value *CleanupPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5770 getVirtualTypeID(TokenTy), CurBB);
5772 return error(
"Invalid cleanupret record");
5774 if (
Record.size() == 2) {
5775 UnwindDest = getBasicBlock(Record[Idx++]);
5777 return error(
"Invalid cleanupret record");
5786 return error(
"Invalid catchret record");
5789 Value *CatchPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5790 getVirtualTypeID(TokenTy), CurBB);
5792 return error(
"Invalid catchret record");
5793 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5795 return error(
"Invalid catchret record");
5804 return error(
"Invalid catchswitch record");
5809 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5810 getVirtualTypeID(TokenTy), CurBB);
5812 return error(
"Invalid catchswitch record");
5814 unsigned NumHandlers =
Record[Idx++];
5817 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5818 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5820 return error(
"Invalid catchswitch record");
5825 if (Idx + 1 ==
Record.size()) {
5826 UnwindDest = getBasicBlock(Record[Idx++]);
5828 return error(
"Invalid catchswitch record");
5831 if (
Record.size() != Idx)
5832 return error(
"Invalid catchswitch record");
5836 for (BasicBlock *Handler : Handlers)
5837 CatchSwitch->addHandler(Handler);
5839 ResTypeID = getVirtualTypeID(
I->getType());
5847 return error(
"Invalid catchpad/cleanuppad record");
5852 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5853 getVirtualTypeID(TokenTy), CurBB);
5855 return error(
"Invalid catchpad/cleanuppad record");
5857 unsigned NumArgOperands =
Record[Idx++];
5859 SmallVector<Value *, 2>
Args;
5860 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5863 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5864 return error(
"Invalid catchpad/cleanuppad record");
5865 Args.push_back(Val);
5868 if (
Record.size() != Idx)
5869 return error(
"Invalid catchpad/cleanuppad record");
5875 ResTypeID = getVirtualTypeID(
I->getType());
5881 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5887 unsigned OpTyID =
Record[1];
5888 Type *OpTy = getTypeByID(OpTyID);
5894 return error(
"Invalid switch record");
5896 unsigned NumCases =
Record[4];
5901 unsigned CurIdx = 5;
5902 for (
unsigned i = 0; i != NumCases; ++i) {
5904 unsigned NumItems =
Record[CurIdx++];
5905 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5906 bool isSingleNumber =
Record[CurIdx++];
5909 unsigned ActiveWords = 1;
5910 if (ValueBitWidth > 64)
5911 ActiveWords =
Record[CurIdx++];
5914 CurIdx += ActiveWords;
5916 if (!isSingleNumber) {
5918 if (ValueBitWidth > 64)
5919 ActiveWords =
Record[CurIdx++];
5922 CurIdx += ActiveWords;
5933 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5934 for (ConstantInt *Cst : CaseVals)
5935 SI->addCase(Cst, DestBB);
5944 return error(
"Invalid switch record");
5945 unsigned OpTyID =
Record[0];
5946 Type *OpTy = getTypeByID(OpTyID);
5950 return error(
"Invalid switch record");
5951 unsigned NumCases = (
Record.size()-3)/2;
5954 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
5956 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
5957 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5958 if (!CaseVal || !DestBB) {
5960 return error(
"Invalid switch record");
5962 SI->addCase(CaseVal, DestBB);
5969 return error(
"Invalid indirectbr record");
5970 unsigned OpTyID =
Record[0];
5971 Type *OpTy = getTypeByID(OpTyID);
5974 return error(
"Invalid indirectbr record");
5975 unsigned NumDests =
Record.size()-2;
5978 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
5979 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5983 return error(
"Invalid indirectbr record");
5993 return error(
"Invalid invoke record");
5996 unsigned CCInfo =
Record[OpNum++];
5997 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5998 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
6000 unsigned FTyID = InvalidTypeID;
6001 FunctionType *FTy =
nullptr;
6002 if ((CCInfo >> 13) & 1) {
6006 return error(
"Explicit invoke type is not a function type");
6010 unsigned CalleeTypeID;
6011 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6013 return error(
"Invalid invoke record");
6017 return error(
"Callee is not a pointer");
6019 FTyID = getContainedTypeID(CalleeTypeID);
6022 return error(
"Callee is not of pointer to function type");
6024 if (
Record.size() < FTy->getNumParams() + OpNum)
6025 return error(
"Insufficient operands to call");
6027 SmallVector<Value*, 16>
Ops;
6028 SmallVector<unsigned, 16> ArgTyIDs;
6029 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6030 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6031 Ops.push_back(
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6035 return error(
"Invalid invoke record");
6038 if (!FTy->isVarArg()) {
6039 if (
Record.size() != OpNum)
6040 return error(
"Invalid invoke record");
6043 while (OpNum !=
Record.size()) {
6046 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6047 return error(
"Invalid invoke record");
6054 if (!OperandBundles.empty())
6059 ResTypeID = getContainedTypeID(FTyID);
6060 OperandBundles.clear();
6063 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
6074 Value *Val =
nullptr;
6076 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
6077 return error(
"Invalid resume record");
6086 unsigned CCInfo =
Record[OpNum++];
6088 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
6089 unsigned NumIndirectDests =
Record[OpNum++];
6090 SmallVector<BasicBlock *, 16> IndirectDests;
6091 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
6092 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
6094 unsigned FTyID = InvalidTypeID;
6095 FunctionType *FTy =
nullptr;
6100 return error(
"Explicit call type is not a function type");
6104 unsigned CalleeTypeID;
6105 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6107 return error(
"Invalid callbr record");
6111 return error(
"Callee is not a pointer type");
6113 FTyID = getContainedTypeID(CalleeTypeID);
6116 return error(
"Callee is not of pointer to function type");
6118 if (
Record.size() < FTy->getNumParams() + OpNum)
6119 return error(
"Insufficient operands to call");
6121 SmallVector<Value*, 16>
Args;
6122 SmallVector<unsigned, 16> ArgTyIDs;
6124 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6126 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6127 if (FTy->getParamType(i)->isLabelTy())
6128 Arg = getBasicBlock(Record[OpNum]);
6130 Arg =
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6133 return error(
"Invalid callbr record");
6134 Args.push_back(Arg);
6139 if (!FTy->isVarArg()) {
6140 if (OpNum !=
Record.size())
6141 return error(
"Invalid callbr record");
6143 while (OpNum !=
Record.size()) {
6146 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6147 return error(
"Invalid callbr record");
6154 if (!OperandBundles.empty())
6159 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6162 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6167 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6168 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6169 unsigned LabelNo = ArgNo - FirstBlockArg;
6171 if (!BA || BA->getFunction() !=
F ||
6172 LabelNo > IndirectDests.
size() ||
6173 BA->getBasicBlock() != IndirectDests[LabelNo])
6174 return error(
"callbr argument does not match indirect dest");
6179 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6183 for (
Value *Arg : Args)
6186 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6189 std::string Constraints =
IA->getConstraintString().str();
6192 for (
const auto &CI : ConstraintInfo) {
6194 if (ArgNo >= FirstBlockArg)
6195 Constraints.insert(Pos,
"!");
6200 Pos = Constraints.find(
',', Pos);
6201 if (Pos == std::string::npos)
6207 IA->hasSideEffects(),
IA->isAlignStack(),
6208 IA->getDialect(),
IA->canThrow());
6214 ResTypeID = getContainedTypeID(FTyID);
6215 OperandBundles.clear();
6232 return error(
"Invalid phi record");
6234 unsigned TyID =
Record[0];
6235 Type *Ty = getTypeByID(TyID);
6237 return error(
"Invalid phi record");
6242 size_t NumArgs = (
Record.size() - 1) / 2;
6246 return error(
"Invalid phi record");
6250 SmallDenseMap<BasicBlock *, Value *>
Args;
6251 for (
unsigned i = 0; i != NumArgs; i++) {
6252 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6255 return error(
"Invalid phi BB");
6262 auto It =
Args.find(BB);
6264 if (It !=
Args.end()) {
6278 if (!PhiConstExprBB)
6280 EdgeBB = PhiConstExprBB;
6288 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6290 V =
getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6294 return error(
"Invalid phi record");
6297 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6298 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6299 PhiConstExprBB =
nullptr;
6302 Args.insert({BB,
V});
6308 if (
Record.size() % 2 == 0) {
6312 I->setFastMathFlags(FMF);
6324 return error(
"Invalid landingpad record");
6328 return error(
"Invalid landingpad record");
6330 ResTypeID =
Record[Idx++];
6331 Type *Ty = getTypeByID(ResTypeID);
6333 return error(
"Invalid landingpad record");
6335 Value *PersFn =
nullptr;
6336 unsigned PersFnTypeID;
6337 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6339 return error(
"Invalid landingpad record");
6341 if (!
F->hasPersonalityFn())
6344 return error(
"Personality function mismatch");
6347 bool IsCleanup = !!
Record[Idx++];
6348 unsigned NumClauses =
Record[Idx++];
6351 for (
unsigned J = 0; J != NumClauses; ++J) {
6357 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6360 return error(
"Invalid landingpad record");
6365 "Catch clause has a invalid type!");
6368 "Filter clause has invalid type!");
6379 return error(
"Invalid alloca record");
6380 using APV = AllocaPackedValues;
6384 unsigned TyID =
Record[0];
6385 Type *Ty = getTypeByID(TyID);
6387 TyID = getContainedTypeID(TyID);
6388 Ty = getTypeByID(TyID);
6390 return error(
"Missing element type for old-style alloca");
6392 unsigned OpTyID =
Record[1];
6393 Type *OpTy = getTypeByID(OpTyID);
6394 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6399 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6403 return error(
"Invalid alloca record");
6405 const DataLayout &
DL = TheModule->getDataLayout();
6406 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6408 SmallPtrSet<Type *, 4> Visited;
6409 if (!Align && !Ty->
isSized(&Visited))
6410 return error(
"alloca of unsized type");
6412 Align =
DL.getPrefTypeAlign(Ty);
6414 if (!
Size->getType()->isIntegerTy())
6415 return error(
"alloca element count must have integer type");
6417 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6421 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6429 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6430 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6431 return error(
"Invalid load record");
6434 return error(
"Load operand is not a pointer type");
6437 if (OpNum + 3 ==
Record.size()) {
6438 ResTypeID =
Record[OpNum++];
6439 Ty = getTypeByID(ResTypeID);
6441 ResTypeID = getContainedTypeID(OpTypeID);
6442 Ty = getTypeByID(ResTypeID);
6446 return error(
"Missing load type");
6448 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6452 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6454 SmallPtrSet<Type *, 4> Visited;
6455 if (!Align && !Ty->
isSized(&Visited))
6456 return error(
"load of unsized type");
6458 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6459 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6468 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6469 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size() &&
6470 OpNum + 6 !=
Record.size()))
6471 return error(
"Invalid load atomic record");
6474 return error(
"Load operand is not a pointer type");
6477 if (
Record.size() >= OpNum + 5) {
6478 ResTypeID =
Record[OpNum++];
6479 Ty = getTypeByID(ResTypeID);
6481 ResTypeID = getContainedTypeID(OpTypeID);
6482 Ty = getTypeByID(ResTypeID);
6486 return error(
"Missing atomic load type");
6488 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6492 if (Ordering == AtomicOrdering::NotAtomic ||
6493 Ordering == AtomicOrdering::Release ||
6494 Ordering == AtomicOrdering::AcquireRelease)
6495 return error(
"Invalid load atomic record");
6496 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6497 return error(
"Invalid load atomic record");
6498 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6499 bool IsElementwise =
Record.size() > OpNum + 4 &&
Record[OpNum + 4];
6502 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6505 return error(
"Alignment missing from atomic load");
6508 LoadStoreInstProperties{
Record[OpNum + 1] != 0, *
Align,
6518 unsigned PtrTypeID, ValTypeID;
6519 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6520 return error(
"Invalid store record");
6523 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6524 return error(
"Invalid store record");
6526 ValTypeID = getContainedTypeID(PtrTypeID);
6527 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6528 ValTypeID, Val, CurBB))
6529 return error(
"Invalid store record");
6532 if (OpNum + 2 !=
Record.size())
6533 return error(
"Invalid store record");
6538 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6540 SmallPtrSet<Type *, 4> Visited;
6542 return error(
"store of unsized type");
6544 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6545 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6555 unsigned PtrTypeID, ValTypeID;
6556 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6558 return error(
"Invalid store atomic record");
6560 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6561 return error(
"Invalid store atomic record");
6563 ValTypeID = getContainedTypeID(PtrTypeID);
6564 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6565 ValTypeID, Val, CurBB))
6566 return error(
"Invalid store atomic record");
6569 if (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size())
6570 return error(
"Invalid store atomic record");
6575 if (Ordering == AtomicOrdering::NotAtomic ||
6576 Ordering == AtomicOrdering::Acquire ||
6577 Ordering == AtomicOrdering::AcquireRelease)
6578 return error(
"Invalid store atomic record");
6579 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6580 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6581 return error(
"Invalid store atomic record");
6584 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6587 return error(
"Alignment missing from atomic store");
6589 bool IsElementwise =
Record.size() > OpNum + 4 &&
Record[OpNum + 4];
6593 LoadStoreInstProperties{
Record[OpNum + 1] != 0, *
Align,
6602 const size_t NumRecords =
Record.size();
6604 Value *Ptr =
nullptr;
6606 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6607 return error(
"Invalid cmpxchg record");
6610 return error(
"Cmpxchg operand is not a pointer type");
6613 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6614 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6615 CmpTypeID, Cmp, CurBB))
6616 return error(
"Invalid cmpxchg record");
6619 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6621 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6622 return error(
"Invalid cmpxchg record");
6626 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6627 SuccessOrdering == AtomicOrdering::Unordered)
6628 return error(
"Invalid cmpxchg record");
6630 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6632 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6640 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6641 FailureOrdering == AtomicOrdering::Unordered)
6642 return error(
"Invalid cmpxchg record");
6645 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6647 I =
new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6648 FailureOrdering, SSID);
6651 if (NumRecords < 8) {
6655 I->insertInto(CurBB, CurBB->
end());
6657 ResTypeID = CmpTypeID;
6660 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6661 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6670 const size_t NumRecords =
Record.size();
6672 Value *Ptr =
nullptr;
6674 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6675 return error(
"Invalid cmpxchg record");
6678 return error(
"Cmpxchg operand is not a pointer type");
6682 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6683 return error(
"Invalid cmpxchg record");
6685 Value *Val =
nullptr;
6686 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6688 return error(
"Invalid cmpxchg record");
6690 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6691 return error(
"Invalid cmpxchg record");
6693 const bool IsVol =
Record[OpNum];
6698 return error(
"Invalid cmpxchg success ordering");
6700 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6702 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6708 return error(
"Invalid cmpxchg failure ordering");
6710 const bool IsWeak =
Record[OpNum + 4];
6714 if (NumRecords == (OpNum + 6)) {
6715 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6720 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6722 I =
new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6723 FailureOrdering, SSID);
6727 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6728 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6737 const size_t NumRecords =
Record.size();
6740 Value *Ptr =
nullptr;
6742 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6743 return error(
"Invalid atomicrmw record");
6746 return error(
"Invalid atomicrmw record");
6748 Value *Val =
nullptr;
6749 unsigned ValTypeID = InvalidTypeID;
6751 ValTypeID = getContainedTypeID(PtrTypeID);
6752 if (popValue(Record, OpNum, NextValueNo,
6753 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6754 return error(
"Invalid atomicrmw record");
6756 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6757 return error(
"Invalid atomicrmw record");
6760 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6761 return error(
"Invalid atomicrmw record");
6763 bool IsElementwise =
false;
6768 return error(
"Invalid atomicrmw record");
6770 const bool IsVol =
Record[OpNum + 1];
6773 if (Ordering == AtomicOrdering::NotAtomic ||
6774 Ordering == AtomicOrdering::Unordered)
6775 return error(
"Invalid atomicrmw record");
6777 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6781 if (NumRecords == (OpNum + 5)) {
6782 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6788 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6790 I =
new AtomicRMWInst(
Operation, Ptr, Val, *Alignment, Ordering, SSID,
6792 ResTypeID = ValTypeID;
6800 return error(
"Invalid fence record");
6802 if (Ordering == AtomicOrdering::NotAtomic ||
6803 Ordering == AtomicOrdering::Unordered ||
6804 Ordering == AtomicOrdering::Monotonic)
6805 return error(
"Invalid fence record");
6807 I =
new FenceInst(
Context, Ordering, SSID);
6814 SeenDebugRecord =
true;
6817 return error(
"Invalid dbg record: missing instruction");
6820 Inst->
getParent()->insertDbgRecordBefore(
6831 SeenDebugRecord =
true;
6834 return error(
"Invalid dbg record: missing instruction");
6851 DILocalVariable *Var =
6853 DIExpression *Expr =
6866 unsigned SlotBefore =
Slot;
6867 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6868 return error(
"Invalid dbg record: invalid value");
6870 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6873 RawLocation = getFnMetadataByID(Record[Slot++]);
6876 DbgVariableRecord *DVR =
nullptr;
6880 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6881 DbgVariableRecord::LocationType::Value);
6884 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6885 DbgVariableRecord::LocationType::Declare);
6888 DVR =
new DbgVariableRecord(
6889 RawLocation, Var, Expr, DIL,
6890 DbgVariableRecord::LocationType::DeclareValue);
6894 DIExpression *AddrExpr =
6896 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6897 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
6910 return error(
"Invalid call record");
6914 unsigned CCInfo =
Record[OpNum++];
6920 return error(
"Fast math flags indicator set for call with no FMF");
6923 unsigned FTyID = InvalidTypeID;
6924 FunctionType *FTy =
nullptr;
6929 return error(
"Explicit call type is not a function type");
6933 unsigned CalleeTypeID;
6934 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6936 return error(
"Invalid call record");
6940 return error(
"Callee is not a pointer type");
6942 FTyID = getContainedTypeID(CalleeTypeID);
6945 return error(
"Callee is not of pointer to function type");
6947 if (
Record.size() < FTy->getNumParams() + OpNum)
6948 return error(
"Insufficient operands to call");
6950 SmallVector<Value*, 16>
Args;
6951 SmallVector<unsigned, 16> ArgTyIDs;
6953 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6954 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6955 if (FTy->getParamType(i)->isLabelTy())
6956 Args.push_back(getBasicBlock(Record[OpNum]));
6959 FTy->getParamType(i), ArgTyID, CurBB));
6962 return error(
"Invalid call record");
6966 if (!FTy->isVarArg()) {
6967 if (OpNum !=
Record.size())
6968 return error(
"Invalid call record");
6970 while (OpNum !=
Record.size()) {
6973 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6974 return error(
"Invalid call record");
6981 if (!OperandBundles.empty())
6985 ResTypeID = getContainedTypeID(FTyID);
6986 OperandBundles.clear();
7000 SeenDebugIntrinsic =
true;
7007 return error(
"Fast-math-flags specified for call without "
7008 "floating-point scalar or vector return type");
7009 I->setFastMathFlags(FMF);
7015 return error(
"Invalid va_arg record");
7016 unsigned OpTyID =
Record[0];
7017 Type *OpTy = getTypeByID(OpTyID);
7020 Type *ResTy = getTypeByID(ResTypeID);
7021 if (!OpTy || !
Op || !ResTy)
7022 return error(
"Invalid va_arg record");
7023 I =
new VAArgInst(
Op, ResTy);
7033 if (
Record.empty() || Record[0] >= BundleTags.size())
7034 return error(
"Invalid operand bundle record");
7036 std::vector<Value *> Inputs;
7039 while (OpNum !=
Record.size()) {
7041 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
7042 return error(
"Invalid operand bundle record");
7043 Inputs.push_back(
Op);
7046 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
7054 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
7055 return error(
"Invalid freeze record");
7056 if (OpNum !=
Record.size())
7057 return error(
"Invalid freeze record");
7059 I =
new FreezeInst(
Op);
7060 ResTypeID = OpTypeID;
7070 return error(
"Invalid instruction with no BB");
7072 if (!OperandBundles.empty()) {
7074 return error(
"Operand bundles found with no consumer");
7076 I->insertInto(CurBB, CurBB->
end());
7079 if (
I->isTerminator()) {
7081 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
7085 if (!
I->getType()->isVoidTy()) {
7086 assert(
I->getType() == getTypeByID(ResTypeID) &&
7087 "Incorrect result type ID");
7095 if (!OperandBundles.empty())
7096 return error(
"Operand bundles found with no consumer");
7100 if (!
A->getParent()) {
7102 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
7108 return error(
"Never resolved value found in function");
7113 if (MDLoader->hasFwdRefs())
7114 return error(
"Invalid function metadata: outgoing forward refs");
7119 for (
const auto &Pair : ConstExprEdgeBBs) {
7130 ValueList.
shrinkTo(ModuleValueListSize);
7131 MDLoader->shrinkTo(ModuleMDLoaderSize);
7132 std::vector<BasicBlock*>().swap(FunctionBBs);
7137Error BitcodeReader::findFunctionInStream(
7139 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7140 while (DeferredFunctionInfoIterator->second == 0) {
7145 assert(VSTOffset == 0 || !
F->hasName());
7148 if (
Error Err = rememberAndSkipFunctionBodies())
7154SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
7157 if (Val >= SSIDs.
size())
7166Error BitcodeReader::materialize(GlobalValue *GV) {
7169 if (!
F || !
F->isMaterializable())
7172 auto DFII = DeferredFunctionInfo.
find(
F);
7173 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
7176 if (DFII->second == 0)
7177 if (
Error Err = findFunctionInStream(
F, DFII))
7181 if (
Error Err = materializeMetadata())
7188 if (
Error Err = parseFunctionBody(
F))
7190 F->setIsMaterializable(
false);
7194 if (SeenDebugIntrinsic && SeenDebugRecord)
7195 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7201 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7202 F->setSubprogram(SP);
7205 if (!MDLoader->isStrippingTBAA()) {
7207 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7210 MDLoader->setStripTBAA(
true);
7217 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7218 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7224 unsigned ExpectedNumOperands = 0;
7226 ExpectedNumOperands = 2;
7228 ExpectedNumOperands =
SI->getNumSuccessors();
7230 ExpectedNumOperands = 1;
7234 ExpectedNumOperands = 2;
7241 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7242 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7248 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7249 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7251 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7252 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7253 CI->getArgOperand(ArgNo)->getType(),
7254 CI->getParamAttributes(ArgNo)));
7257 if (
Function *OldFn = CI->getCalledFunction()) {
7258 auto It = UpgradedIntrinsics.
find(OldFn);
7259 if (It != UpgradedIntrinsics.
end())
7263 BC && BC->getSrcTy() == BC->getDestTy() &&
7269 CI && CI->isMustTailCall() && CI->getNextNode() == BC) {
7270 BC->replaceAllUsesWith(CI);
7271 BC->eraseFromParent();
7281 return materializeForwardReferencedFunctions();
7284Error BitcodeReader::materializeModule() {
7285 if (
Error Err = materializeMetadata())
7289 WillMaterializeAllForwardRefs =
true;
7294 if (
Error Err = materialize(&
F))
7300 if (LastFunctionBlockBit || NextUnreadBit)
7302 ? LastFunctionBlockBit
7308 if (!BasicBlockFwdRefs.
empty())
7309 return error(
"Never resolved function from blockaddress");
7315 for (
auto &[OldFn, NewFn] : UpgradedIntrinsics) {
7316 for (User *U : OldFn->users()) {
7320 if (OldFn != NewFn) {
7321 if (!OldFn->use_empty())
7322 OldFn->replaceAllUsesWith(NewFn);
7323 OldFn->eraseFromParent();
7326 UpgradedIntrinsics.clear();
7341std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7342 return IdentifiedStructTypes;
7345ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7346 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7347 StringRef ModulePath, std::function<
bool(StringRef)> IsPrevailing,
7348 std::function<
void(ValueInfo)> OnValueInfo)
7349 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7350 ModulePath(ModulePath), IsPrevailing(IsPrevailing),
7351 OnValueInfo(OnValueInfo) {}
7353void ModuleSummaryIndexBitcodeReader::addThisModule() {
7358ModuleSummaryIndexBitcodeReader::getThisModule() {
7362template <
bool AllowNullValueInfo>
7363std::pair<ValueInfo, GlobalValue::GUID>
7364ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7365 auto VGI = ValueIdToValueInfoMap[ValueId];
7372 assert(AllowNullValueInfo || std::get<0>(VGI));
7376void ModuleSummaryIndexBitcodeReader::setValueGUID(
7378 StringRef SourceFileName) {
7380 if (ValueID < DefinedGUIDs.size())
7381 ValueGUID = DefinedGUIDs[ValueID];
7388 auto OriginalNameID = ValueGUID;
7392 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7400 ValueIdToValueInfoMap[ValueID] = std::make_pair(VI, OriginalNameID);
7408Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7410 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7417 if (!MaybeCurrentBit)
7424 SmallVector<uint64_t, 64>
Record;
7433 BitstreamEntry
Entry = MaybeEntry.
get();
7435 switch (
Entry.Kind) {
7438 return error(
"Malformed block");
7454 switch (MaybeRecord.
get()) {
7459 return error(
"Invalid vst_code_entry record");
7460 unsigned ValueID =
Record[0];
7462 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7463 assert(VLI != ValueIdToLinkageMap.
end() &&
7464 "No linkage found for VST entry?");
7473 return error(
"Invalid vst_code_fnentry record");
7474 unsigned ValueID =
Record[0];
7476 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7477 assert(VLI != ValueIdToLinkageMap.
end() &&
7478 "No linkage found for VST entry?");
7486 unsigned ValueID =
Record[0];
7490 ValueIdToValueInfoMap[ValueID] =
7501Error ModuleSummaryIndexBitcodeReader::parseModule() {
7505 SmallVector<uint64_t, 64>
Record;
7506 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7507 unsigned ValueId = 0;
7511 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
7514 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7516 switch (
Entry.Kind) {
7518 return error(
"Malformed block");
7530 if (
Error Err = readBlockInfo())
7536 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7537 !SeenGlobalValSummary) &&
7538 "Expected early VST parse via VSTOffset record");
7545 if (!SourceFileName.
empty())
7547 assert(!SeenValueSymbolTable &&
7548 "Already read VST when parsing summary block?");
7553 if (VSTOffset > 0) {
7554 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7556 SeenValueSymbolTable =
true;
7558 SeenGlobalValSummary =
true;
7559 if (
Error Err = parseEntireSummary(
Entry.ID))
7563 if (
Error Err = parseModuleStringTable())
7571 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7574 switch (MaybeBitCode.
get()) {
7578 if (
Error Err = parseVersionRecord(Record).takeError())
7586 return error(
"Invalid source filename record");
7593 return error(
"Invalid hash length " + Twine(
Record.size()));
7594 auto &Hash = getThisModule()->second;
7596 for (
auto &Val : Record) {
7597 assert(!(Val >> 32) &&
"Unexpected high bits set");
7605 return error(
"Invalid vstoffset record");
7609 VSTOffset =
Record[0] - 1;
7614 DefinedGUIDs.reserve(DefinedGUIDs.size() +
Record.size() / 2);
7615 for (
size_t i = 0; i <
Record.size(); i += 2)
7616 DefinedGUIDs.push_back(Record[i] << 32 | Record[i + 1]);
7626 ArrayRef<uint64_t> GVRecord;
7627 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7628 if (GVRecord.
size() <= 3)
7629 return error(
"Invalid global record");
7633 ValueIdToLinkageMap[ValueId++] =
Linkage;
7637 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7648ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7652 Ret.
push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7657ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7658 bool IsOldProfileFormat,
7659 bool HasProfile,
bool HasRelBF) {
7663 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7668 for (
unsigned I = 0,
E =
Record.size();
I !=
E; ++
I) {
7670 bool HasTailCall =
false;
7672 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7673 if (IsOldProfileFormat) {
7677 }
else if (HasProfile)
7678 std::tie(Hotness, HasTailCall) =
7712 static_cast<size_t>(
Record[Slot + 1])};
7735 while (Slot <
Record.size())
7739std::vector<FunctionSummary::ParamAccess>
7740ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7741 auto ReadRange = [&]() {
7743 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7745 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7752 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7753 while (!
Record.empty()) {
7754 PendingParamAccesses.emplace_back();
7755 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7757 ParamAccess.
Use = ReadRange();
7762 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7763 Call.Offsets = ReadRange();
7766 return PendingParamAccesses;
7769void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7770 ArrayRef<uint64_t> Record,
size_t &Slot,
7773 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7777void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7778 ArrayRef<uint64_t> Record) {
7786 while (Slot <
Record.size())
7787 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7790SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7791 ArrayRef<uint64_t> Record,
unsigned &
I) {
7792 SmallVector<unsigned> StackIdList;
7796 if (RadixArray.empty()) {
7797 unsigned NumStackEntries =
Record[
I++];
7799 StackIdList.
reserve(NumStackEntries);
7800 for (
unsigned J = 0; J < NumStackEntries; J++) {
7801 assert(Record[
I] < StackIds.size());
7802 StackIdList.
push_back(getStackIdIndex(Record[
I++]));
7805 unsigned RadixIndex =
Record[
I++];
7811 assert(RadixIndex < RadixArray.size());
7812 unsigned NumStackIds = RadixArray[RadixIndex++];
7813 StackIdList.
reserve(NumStackIds);
7814 while (NumStackIds--) {
7815 assert(RadixIndex < RadixArray.size());
7816 unsigned Elem = RadixArray[RadixIndex];
7817 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7818 RadixIndex = RadixIndex - Elem;
7819 assert(RadixIndex < RadixArray.size());
7820 Elem = RadixArray[RadixIndex];
7822 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7825 StackIdList.
push_back(getStackIdIndex(Elem));
7835 unsigned FirstWORef = Refs.
size() - WOCnt;
7836 unsigned RefNo = FirstWORef - ROCnt;
7837 for (; RefNo < FirstWORef; ++RefNo)
7838 Refs[RefNo].setReadOnly();
7839 for (; RefNo < Refs.
size(); ++RefNo)
7840 Refs[RefNo].setWriteOnly();
7845Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7848 SmallVector<uint64_t, 64>
Record;
7855 BitstreamEntry
Entry = MaybeEntry.
get();
7858 return error(
"Invalid Summary Block: record for version expected");
7863 return error(
"Invalid Summary Block: version expected");
7866 const bool IsOldProfileFormat =
Version == 1;
7869 const bool MemProfAfterFunctionSummary =
Version >= 13;
7871 return error(
"Invalid summary version " + Twine(
Version) +
" in module '" +
7872 ModulePath +
"'. Version should be in the range [1-" +
7878 GlobalValueSummary *LastSeenSummary =
nullptr;
7888 FunctionSummary *CurrentPrevailingFS =
nullptr;
7893 std::vector<GlobalValue::GUID> PendingTypeTests;
7894 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7895 PendingTypeCheckedLoadVCalls;
7896 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7897 PendingTypeCheckedLoadConstVCalls;
7898 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7900 std::vector<CallsiteInfo> PendingCallsites;
7901 std::vector<AllocInfo> PendingAllocs;
7902 std::vector<uint64_t> PendingContextIds;
7908 BitstreamEntry
Entry = MaybeEntry.
get();
7910 switch (
Entry.Kind) {
7913 return error(
"Malformed block");
7929 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7932 unsigned BitCode = MaybeBitCode.
get();
7949 ValueIdToValueInfoMap[ValueID] =
7967 unsigned ValueID =
Record[0];
7969 unsigned InstCount =
Record[2];
7971 unsigned NumRefs =
Record[3];
7972 unsigned NumRORefs = 0, NumWORefs = 0;
7973 int RefListStartIndex = 4;
7977 RefListStartIndex = 5;
7980 RefListStartIndex = 6;
7983 RefListStartIndex = 7;
7994 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7996 "Record size inconsistent with number of references");
7998 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8003 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8004 IsOldProfileFormat, HasProfile, HasRelBF);
8006 auto [
VI,
GUID] = getValueInfoFromValueId(ValueID);
8013 IsPrevailing(
VI.name());
8019 assert(!MemProfAfterFunctionSummary ||
8020 (PendingCallsites.empty() && PendingAllocs.empty()));
8021 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
8022 PendingCallsites.clear();
8023 PendingAllocs.clear();
8026 auto FS = std::make_unique<FunctionSummary>(
8028 std::move(Calls), std::move(PendingTypeTests),
8029 std::move(PendingTypeTestAssumeVCalls),
8030 std::move(PendingTypeCheckedLoadVCalls),
8031 std::move(PendingTypeTestAssumeConstVCalls),
8032 std::move(PendingTypeCheckedLoadConstVCalls),
8033 std::move(PendingParamAccesses), std::move(PendingCallsites),
8034 std::move(PendingAllocs));
8035 FS->setModulePath(getThisModule()->first());
8036 FS->setOriginalName(GUID);
8039 if (MemProfAfterFunctionSummary) {
8040 if (IsPrevailingSym)
8041 CurrentPrevailingFS =
FS.get();
8043 CurrentPrevailingFS =
nullptr;
8052 unsigned ValueID =
Record[0];
8054 unsigned AliaseeID =
Record[2];
8056 auto AS = std::make_unique<AliasSummary>(Flags);
8062 AS->setModulePath(getThisModule()->first());
8064 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
8066 if (!AliaseeInModule)
8067 return error(
"Alias expects aliasee summary to be parsed");
8068 AS->setAliasee(AliaseeVI, AliaseeInModule);
8070 auto GUID = getValueInfoFromValueId(ValueID);
8071 AS->setOriginalName(std::get<1>(GUID));
8077 unsigned ValueID =
Record[0];
8079 unsigned RefArrayStart = 2;
8080 GlobalVarSummary::GVarFlags GVF(
false,
8090 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8092 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8093 FS->setModulePath(getThisModule()->first());
8094 auto GUID = getValueInfoFromValueId(ValueID);
8095 FS->setOriginalName(std::get<1>(GUID));
8103 unsigned ValueID =
Record[0];
8106 unsigned NumRefs =
Record[3];
8107 unsigned RefListStartIndex = 4;
8108 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
8111 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8113 for (
unsigned I = VTableListStartIndex,
E =
Record.size();
I !=
E; ++
I) {
8114 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
8119 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8120 VS->setModulePath(getThisModule()->first());
8121 VS->setVTableFuncs(VTableFuncs);
8122 auto GUID = getValueInfoFromValueId(ValueID);
8123 VS->setOriginalName(std::get<1>(GUID));
8135 unsigned ValueID =
Record[0];
8138 unsigned InstCount =
Record[3];
8140 unsigned NumRefs =
Record[4];
8141 unsigned NumRORefs = 0, NumWORefs = 0;
8142 int RefListStartIndex = 5;
8146 RefListStartIndex = 6;
8147 size_t NumRefsIndex = 5;
8149 unsigned NumRORefsOffset = 1;
8150 RefListStartIndex = 7;
8153 RefListStartIndex = 8;
8155 RefListStartIndex = 9;
8157 NumRORefsOffset = 2;
8160 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
8162 NumRefs =
Record[NumRefsIndex];
8166 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8168 "Record size inconsistent with number of references");
8170 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8173 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8174 IsOldProfileFormat, HasProfile,
false);
8175 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8177 auto FS = std::make_unique<FunctionSummary>(
8179 std::move(Edges), std::move(PendingTypeTests),
8180 std::move(PendingTypeTestAssumeVCalls),
8181 std::move(PendingTypeCheckedLoadVCalls),
8182 std::move(PendingTypeTestAssumeConstVCalls),
8183 std::move(PendingTypeCheckedLoadConstVCalls),
8184 std::move(PendingParamAccesses), std::move(PendingCallsites),
8185 std::move(PendingAllocs));
8186 LastSeenSummary =
FS.get();
8187 if (MemProfAfterFunctionSummary)
8188 CurrentPrevailingFS =
FS.get();
8189 LastSeenGUID =
VI.getGUID();
8190 FS->setModulePath(ModuleIdMap[ModuleId]);
8198 unsigned ValueID =
Record[0];
8201 unsigned AliaseeValueId =
Record[3];
8203 auto AS = std::make_unique<AliasSummary>(Flags);
8204 LastSeenSummary = AS.get();
8205 AS->setModulePath(ModuleIdMap[ModuleId]);
8207 auto AliaseeVI = std::get<0>(
8208 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8210 auto AliaseeInModule =
8212 AS->setAliasee(AliaseeVI, AliaseeInModule);
8214 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8215 LastSeenGUID =
VI.getGUID();
8221 unsigned ValueID =
Record[0];
8224 unsigned RefArrayStart = 3;
8225 GlobalVarSummary::GVarFlags GVF(
false,
8235 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8237 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8238 LastSeenSummary =
FS.get();
8239 FS->setModulePath(ModuleIdMap[ModuleId]);
8240 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8241 LastSeenGUID =
VI.getGUID();
8248 if (!LastSeenSummary)
8249 return error(
"Name attachment that does not follow a combined record");
8253 LastSeenSummary =
nullptr;
8258 assert(PendingTypeTests.empty());
8263 assert(PendingTypeTestAssumeVCalls.empty());
8264 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8265 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8269 assert(PendingTypeCheckedLoadVCalls.empty());
8270 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8271 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8275 PendingTypeTestAssumeConstVCalls.push_back(
8280 PendingTypeCheckedLoadConstVCalls.push_back(
8287 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8288 StringRef
Name(Strtab.
data() + Record[
I],
8289 static_cast<size_t>(Record[
I + 1]));
8292 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, GUID);
8295 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8297 StringRef
Name(Strtab.
data() + Record[
I + 1],
8298 static_cast<size_t>(Record[
I + 2]));
8299 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8308 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8309 StringRef
Name(Strtab.
data() + Record[
I],
8310 static_cast<size_t>(Record[
I + 1]));
8313 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, GUID);
8316 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8318 StringRef
Name(Strtab.
data() + Record[
I + 1],
8319 static_cast<size_t>(Record[
I + 2]));
8320 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8331 parseTypeIdCompatibleVtableSummaryRecord(Record);
8339 PendingParamAccesses = parseParamAccesses(Record);
8346 assert(StackIds.empty());
8348 StackIds = ArrayRef<uint64_t>(Record);
8354 StackIds.reserve(
Record.size() / 2);
8355 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8356 StackIds.push_back(*R << 32 | *(R + 1));
8358 assert(StackIdToIndex.empty());
8360 StackIdToIndex.resize(StackIds.size(), UninitializedStackIdIndex);
8365 RadixArray = ArrayRef<uint64_t>(Record);
8372 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8374 unsigned ValueID =
Record[0];
8375 SmallVector<unsigned> StackIdList;
8377 assert(R < StackIds.size());
8378 StackIdList.
push_back(getStackIdIndex(R));
8380 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8381 if (MemProfAfterFunctionSummary)
8383 CallsiteInfo({
VI, std::move(StackIdList)}));
8385 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8392 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8393 auto RecordIter =
Record.begin();
8394 unsigned ValueID = *RecordIter++;
8395 unsigned NumStackIds = *RecordIter++;
8396 unsigned NumVersions = *RecordIter++;
8397 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8398 SmallVector<unsigned> StackIdList;
8399 for (
unsigned J = 0; J < NumStackIds; J++) {
8400 assert(*RecordIter < StackIds.size());
8401 StackIdList.
push_back(getStackIdIndex(*RecordIter++));
8403 SmallVector<unsigned> Versions;
8404 for (
unsigned J = 0; J < NumVersions; J++)
8406 ValueInfo
VI = std::get<0>(
8407 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8408 if (MemProfAfterFunctionSummary)
8410 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8412 PendingCallsites.push_back(
8413 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8420 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8425 PendingContextIds.reserve(
Record.size() / 2);
8426 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8427 PendingContextIds.push_back(*R << 32 | *(R + 1));
8434 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8435 PendingContextIds.clear();
8439 std::vector<MIBInfo> MIBs;
8440 unsigned NumMIBs = 0;
8443 unsigned MIBsRead = 0;
8444 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8448 auto StackIdList = parseAllocInfoContext(Record,
I);
8449 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8455 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8457 assert(!PendingContextIds.empty() &&
8458 "Missing context ids for alloc sizes");
8459 unsigned ContextIdIndex = 0;
8465 while (MIBsRead++ < NumMIBs) {
8467 unsigned NumContextSizeInfoEntries =
Record[
I++];
8469 std::vector<ContextTotalSize> ContextSizes;
8470 ContextSizes.reserve(NumContextSizeInfoEntries);
8471 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8472 assert(ContextIdIndex < PendingContextIds.size());
8474 if (PendingContextIds[ContextIdIndex] == 0) {
8483 ContextSizes.push_back(
8484 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8486 AllContextSizes.push_back(std::move(ContextSizes));
8488 PendingContextIds.clear();
8490 AllocInfo AI(std::move(MIBs));
8491 if (!AllContextSizes.empty()) {
8492 assert(AI.MIBs.size() == AllContextSizes.size());
8493 AI.ContextSizeInfos = std::move(AllContextSizes);
8496 if (MemProfAfterFunctionSummary)
8497 CurrentPrevailingFS->
addAlloc(std::move(AI));
8499 PendingAllocs.push_back(std::move(AI));
8507 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8509 std::vector<MIBInfo> MIBs;
8510 unsigned NumMIBs =
Record[
I++];
8511 unsigned NumVersions =
Record[
I++];
8512 unsigned MIBsRead = 0;
8513 while (MIBsRead++ < NumMIBs) {
8516 SmallVector<unsigned> StackIdList;
8518 StackIdList = parseAllocInfoContext(Record,
I);
8519 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8522 SmallVector<uint8_t> Versions;
8523 for (
unsigned J = 0; J < NumVersions; J++)
8526 AllocInfo AI(std::move(Versions), std::move(MIBs));
8527 if (MemProfAfterFunctionSummary)
8528 CurrentPrevailingFS->
addAlloc(std::move(AI));
8530 PendingAllocs.push_back(std::move(AI));
8540Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8544 SmallVector<uint64_t, 64>
Record;
8546 SmallString<128> ModulePath;
8553 BitstreamEntry
Entry = MaybeEntry.
get();
8555 switch (
Entry.Kind) {
8558 return error(
"Malformed block");
8570 switch (MaybeRecord.
get()) {
8578 return error(
"Invalid code_entry record");
8580 LastSeenModule = TheIndex.
addModule(ModulePath);
8581 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8589 return error(
"Invalid hash length " + Twine(
Record.size()));
8590 if (!LastSeenModule)
8591 return error(
"Invalid hash that does not follow a module path");
8593 for (
auto &Val : Record) {
8594 assert(!(Val >> 32) &&
"Unexpected high bits set");
8595 LastSeenModule->
second[Pos++] = Val;
8598 LastSeenModule =
nullptr;
8611class BitcodeErrorCategoryType :
public std::error_category {
8612 const char *
name()
const noexcept
override {
8613 return "llvm.bitcode";
8616 std::string message(
int IE)
const override {
8619 case BitcodeError::CorruptedBitcode:
8620 return "Corrupted bitcode";
8629 static BitcodeErrorCategoryType ErrorCategory;
8630 return ErrorCategory;
8634 unsigned Block,
unsigned RecordID) {
8636 return std::move(Err);
8645 switch (Entry.Kind) {
8650 return error(
"Malformed block");
8654 return std::move(Err);
8664 if (MaybeRecord.
get() == RecordID)
8675Expected<std::vector<BitcodeModule>>
8679 return FOrErr.takeError();
8680 return std::move(FOrErr->Mods);
8705 switch (Entry.Kind) {
8708 return error(
"Malformed block");
8711 uint64_t IdentificationBit = -1ull;
8715 return std::move(Err);
8721 Entry = MaybeEntry.
get();
8726 return error(
"Malformed block");
8732 return std::move(Err);
8751 if (!
I.Strtab.empty())
8758 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8759 F.StrtabForSymtab = *Strtab;
8775 if (
F.Symtab.empty())
8776 F.Symtab = *SymtabOrErr;
8781 return std::move(Err);
8786 return std::move(E);
8801BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8802 bool ShouldLazyLoadMetadata,
bool IsImporting,
8806 std::string ProducerIdentification;
8807 if (IdentificationBit != -1ull) {
8809 return std::move(JumpFailed);
8812 return std::move(
E);
8816 return std::move(JumpFailed);
8817 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8820 std::unique_ptr<Module>
M =
8821 std::make_unique<Module>(ModuleIdentifier,
Context);
8822 M->setMaterializer(R);
8825 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8826 IsImporting, Callbacks))
8827 return std::move(Err);
8829 if (MaterializeAll) {
8831 if (
Error Err =
M->materializeAll())
8832 return std::move(Err);
8835 if (
Error Err =
R->materializeForwardReferencedFunctions())
8836 return std::move(Err);
8839 return std::move(M);
8842Expected<std::unique_ptr<Module>>
8845 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8855 std::function<
bool(
StringRef)> IsPrevailing,
8856 std::function<
void(
ValueInfo)> OnValueInfo) {
8861 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8862 ModulePath, IsPrevailing, OnValueInfo);
8863 return R.parseModule();
8870 return std::move(JumpFailed);
8872 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8873 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8874 ModuleIdentifier, 0);
8876 if (
Error Err = R.parseModule())
8877 return std::move(Err);
8879 return std::move(Index);
8885 return std::move(Err);
8891 return std::move(
E);
8893 switch (Entry.Kind) {
8896 return error(
"Malformed block");
8899 return std::make_pair(
false,
false);
8911 switch (MaybeBitCode.
get()) {
8917 assert(Flags <= 0x7ff &&
"Unexpected bits in flag");
8919 bool EnableSplitLTOUnit = Flags & 0x8;
8920 bool UnifiedLTO = Flags & 0x200;
8921 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8932 return std::move(JumpFailed);
8935 return std::move(Err);
8940 return std::move(E);
8942 switch (Entry.Kind) {
8944 return error(
"Malformed block");
8955 return Flags.takeError();
8965 return std::move(Err);
8972 return StreamFailed.takeError();
8982 if (MsOrErr->size() != 1)
8983 return error(
"Expected a single module");
8985 return (*MsOrErr)[0];
8988Expected<std::unique_ptr<Module>>
8990 bool ShouldLazyLoadMetadata,
bool IsImporting,
8996 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
9001 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
9002 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
9004 IsImporting, Callbacks);
9006 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
9012 return getModuleImpl(Context,
true,
false,
false, Callbacks);
9024 return BM->parseModule(Context, Callbacks);
9057 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
9066 return BM->getSummary();
9074 return BM->getLTOInfo();
9079 bool IgnoreEmptyThinLTOIndexFile) {
9084 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 AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val, bool &IsElementwise)
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
static bool hasImplicitComdat(size_t Val)
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream)
static Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
static void parseWholeProgramDevirtResolution(ArrayRef< uint64_t > Record, StringRef Strtab, size_t &Slot, TypeIdSummary &TypeId)
static void inferDSOLocal(GlobalValue *GV)
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V)
static Expected< BitstreamCursor > initStream(MemoryBufferRef Buffer)
static 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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase)
This file defines the DenseMap class.
Provides ErrorOr<T> smart pointer.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Module.h This file contains the declarations for the Module class.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
static bool isValidFailureOrdering(AtomicOrdering Ordering)
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
static bool isTypeAttrKind(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ 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 Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(StringRef)> IsPrevailing=nullptr, std::function< void(ValueInfo)> OnValueInfo=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
void push_back(Value *V, unsigned TypeID)
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
void shrinkTo(unsigned N)
unsigned getTypeID(unsigned ValNo) const
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
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)