24#include "llvm/Config/llvm-config.h"
54#include "llvm/IR/IntrinsicsAArch64.h"
55#include "llvm/IR/IntrinsicsARM.h"
87#include <system_error>
97 "Print the global id for each value when reading the module summary"));
102 "Expand constant expressions to instructions for testing purposes"));
107 SWITCH_INST_MAGIC = 0x4B5
120 "file too small to contain bitcode header");
121 for (
unsigned C : {
'B',
'C'})
125 "file doesn't start with bitcode header");
127 return Res.takeError();
128 for (
unsigned C : {0x0, 0xC, 0xE, 0xD})
132 "file doesn't start with bitcode header");
134 return Res.takeError();
139 const unsigned char *BufPtr = (
const unsigned char *)Buffer.
getBufferStart();
140 const unsigned char *BufEnd = BufPtr + Buffer.
getBufferSize();
143 return error(
"Invalid bitcode signature");
149 return error(
"Invalid bitcode wrapper header");
153 return std::move(Err);
155 return std::move(Stream);
159template <
typename StrTy>
172 if (
F.isMaterializable())
175 I.setMetadata(LLVMContext::MD_tbaa,
nullptr);
183 return std::move(Err);
188 std::string ProducerIdentification;
195 switch (Entry.Kind) {
198 return error(
"Malformed block");
200 return ProducerIdentification;
211 switch (MaybeBitCode.
get()) {
213 return error(
"Invalid value");
221 Twine(
"Incompatible epoch: Bitcode '") +
Twine(epoch) +
240 switch (Entry.Kind) {
243 return error(
"Malformed block");
251 return std::move(Err);
263 return std::move(Err);
274 switch (Entry.Kind) {
277 return error(
"Malformed block");
289 switch (MaybeRecord.
get()) {
295 return error(
"Invalid section name record");
300 Segment = Segment.trim();
301 Section = Section.trim();
303 if (Segment ==
"__DATA" && Section.starts_with(
"__objc_catlist"))
305 if (Segment ==
"__OBJC" && Section.starts_with(
"__category"))
307 if (Segment ==
"__TEXT" && Section.starts_with(
"__swift"))
325 switch (Entry.Kind) {
327 return error(
"Malformed block");
337 return std::move(Err);
350 return std::move(Err);
363 switch (Entry.Kind) {
366 return error(
"Malformed block");
378 switch (MaybeRecord.
get()) {
383 return error(
"Invalid triple record");
402 switch (Entry.Kind) {
404 return error(
"Malformed block");
414 return std::move(Err);
421 return Skipped.takeError();
428class BitcodeReaderBase {
430 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
431 : Stream(std::
move(Stream)), Strtab(Strtab) {
432 this->Stream.setBlockInfo(&BlockInfo);
435 BitstreamBlockInfo BlockInfo;
436 BitstreamCursor Stream;
441 bool UseStrtab =
false;
443 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
448 std::pair<StringRef, ArrayRef<uint64_t>>
449 readNameFromStrtab(ArrayRef<uint64_t> Record);
451 Error readBlockInfo();
454 std::string ProducerIdentification;
461Error BitcodeReaderBase::error(
const Twine &Message) {
462 std::string FullMsg = Message.
str();
463 if (!ProducerIdentification.empty())
464 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
465 LLVM_VERSION_STRING
"')";
466 return ::error(FullMsg);
470BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
472 return error(
"Invalid version record");
473 unsigned ModuleVersion =
Record[0];
474 if (ModuleVersion > 2)
475 return error(
"Invalid value");
476 UseStrtab = ModuleVersion >= 2;
477 return ModuleVersion;
480std::pair<StringRef, ArrayRef<uint64_t>>
481BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
485 if (Record[0] + Record[1] > Strtab.
size())
487 return {StringRef(Strtab.
data() + Record[0], Record[1]),
Record.slice(2)};
498class BitcodeConstant final :
public Value,
499 TrailingObjects<BitcodeConstant, unsigned> {
500 friend TrailingObjects;
503 static constexpr uint8_t SubclassID = 255;
511 static constexpr uint8_t ConstantStructOpcode = 255;
512 static constexpr uint8_t ConstantArrayOpcode = 254;
513 static constexpr uint8_t ConstantVectorOpcode = 253;
514 static constexpr uint8_t NoCFIOpcode = 252;
515 static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
516 static constexpr uint8_t BlockAddressOpcode = 250;
517 static constexpr uint8_t ConstantPtrAuthOpcode = 249;
518 static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
525 unsigned BlockAddressBB = 0;
526 Type *SrcElemTy =
nullptr;
527 std::optional<ConstantRange>
InRange;
529 ExtraInfo(uint8_t Opcode, uint8_t Flags = 0,
Type *SrcElemTy =
nullptr,
530 std::optional<ConstantRange>
InRange = std::nullopt)
531 : Opcode(Opcode),
Flags(
Flags), SrcElemTy(SrcElemTy),
534 ExtraInfo(uint8_t Opcode, uint8_t Flags,
unsigned BlockAddressBB)
535 : Opcode(Opcode),
Flags(
Flags), BlockAddressBB(BlockAddressBB) {}
540 unsigned NumOperands;
541 unsigned BlockAddressBB;
543 std::optional<ConstantRange>
InRange;
546 BitcodeConstant(
Type *Ty,
const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
548 NumOperands(OpIDs.
size()), BlockAddressBB(
Info.BlockAddressBB),
553 BitcodeConstant &operator=(
const BitcodeConstant &) =
delete;
557 const ExtraInfo &Info,
558 ArrayRef<unsigned> OpIDs) {
559 void *Mem =
A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.
size()),
560 alignof(BitcodeConstant));
561 return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
564 static bool classof(
const Value *V) {
return V->getValueID() == SubclassID; }
566 ArrayRef<unsigned> getOperandIDs()
const {
567 return ArrayRef(getTrailingObjects(), NumOperands);
570 std::optional<ConstantRange> getInRange()
const {
571 assert(Opcode == Instruction::GetElementPtr);
580class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
582 Module *TheModule =
nullptr;
584 uint64_t NextUnreadBit = 0;
586 uint64_t LastFunctionBlockBit = 0;
587 bool SeenValueSymbolTable =
false;
588 uint64_t VSTOffset = 0;
590 std::vector<std::string> SectionTable;
591 std::vector<std::string> GCTable;
593 std::vector<Type *> TypeList;
597 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
604 DenseMap<std::pair<Type *, unsigned>,
unsigned> VirtualTypeIDs;
605 DenseMap<Function *, unsigned> FunctionTypeIDs;
610 BitcodeReaderValueList ValueList;
611 std::optional<MetadataLoader> MDLoader;
612 std::vector<Comdat *> ComdatList;
613 DenseSet<GlobalObject *> ImplicitComdatObjects;
616 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
617 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
619 struct FunctionOperandInfo {
621 unsigned PersonalityFn;
625 std::vector<FunctionOperandInfo> FunctionOperands;
629 std::vector<AttributeList> MAttributes;
632 std::map<unsigned, AttributeList> MAttributeGroups;
636 std::vector<BasicBlock*> FunctionBBs;
640 std::vector<Function*> FunctionsWithBodies;
644 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
645 UpdatedIntrinsicMap UpgradedIntrinsics;
650 bool SeenFirstFunctionBody =
false;
654 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
659 std::vector<uint64_t> DeferredMetadataInfo;
664 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
665 std::deque<Function *> BasicBlockFwdRefQueue;
672 std::vector<Function *> BackwardRefFunctions;
680 bool UseRelativeIDs =
false;
684 bool WillMaterializeAllForwardRefs =
false;
688 bool SeenDebugIntrinsic =
false;
689 bool SeenDebugRecord =
false;
692 TBAAVerifier TBAAVerifyHelper;
694 std::vector<std::string> BundleTags;
697 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
700 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
701 StringRef ProducerIdentification, LLVMContext &
Context);
703 Error materializeForwardReferencedFunctions();
705 Error materialize(GlobalValue *GV)
override;
706 Error materializeModule()
override;
707 std::vector<StructType *> getIdentifiedStructTypes()
const override;
711 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
712 bool IsImporting, ParserCallbacks Callbacks = {});
714 static uint64_t decodeSignRotatedValue(uint64_t V);
717 Error materializeMetadata()
override;
719 void setStripDebugInfo()
override;
722 std::vector<StructType *> IdentifiedStructTypes;
723 StructType *createIdentifiedStructType(LLVMContext &
Context, StringRef Name);
724 StructType *createIdentifiedStructType(LLVMContext &
Context);
726 static constexpr unsigned InvalidTypeID = ~0
u;
728 Type *getTypeByID(
unsigned ID);
729 Type *getPtrElementTypeByID(
unsigned ID);
730 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
731 unsigned getVirtualTypeID(
Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
734 Expected<Value *> materializeValue(
unsigned ValID, BasicBlock *InsertBB);
735 Expected<Constant *> getValueForInitializer(
unsigned ID);
737 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
738 BasicBlock *ConstExprInsertBB) {
745 return MDLoader->getMetadataFwdRefOrLoad(
ID);
749 if (
ID >= FunctionBBs.size())
return nullptr;
750 return FunctionBBs[
ID];
754 if (i-1 < MAttributes.size())
755 return MAttributes[i-1];
756 return AttributeList();
762 bool getValueTypePair(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
763 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
764 BasicBlock *ConstExprInsertBB) {
765 if (Slot ==
Record.size())
return true;
766 unsigned ValNo = (unsigned)Record[Slot++];
769 ValNo = InstNum - ValNo;
770 if (ValNo < InstNum) {
774 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
776 "Incorrect type ID stored for value");
777 return ResVal ==
nullptr;
779 if (Slot ==
Record.size())
782 TypeID = (unsigned)Record[Slot++];
783 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
785 return ResVal ==
nullptr;
788 bool getValueOrMetadata(
const SmallVectorImpl<uint64_t> &Record,
789 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
790 BasicBlock *ConstExprInsertBB) {
791 if (Slot ==
Record.size())
796 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
799 if (Slot ==
Record.size())
801 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
809 bool popValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
810 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
811 BasicBlock *ConstExprInsertBB) {
812 if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
820 bool getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
821 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
822 BasicBlock *ConstExprInsertBB) {
823 ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
824 return ResVal ==
nullptr;
829 Value *getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
830 unsigned InstNum,
Type *Ty,
unsigned TyID,
831 BasicBlock *ConstExprInsertBB) {
832 if (Slot ==
Record.size())
return nullptr;
833 unsigned ValNo = (unsigned)Record[Slot];
836 ValNo = InstNum - ValNo;
837 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
841 Value *getValueSigned(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
842 unsigned InstNum,
Type *Ty,
unsigned TyID,
843 BasicBlock *ConstExprInsertBB) {
844 if (Slot ==
Record.size())
return nullptr;
845 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
848 ValNo = InstNum - ValNo;
849 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
852 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
855 if (
Record.size() - OpNum < 2)
856 return error(
"Too few records for range");
858 unsigned LowerActiveWords =
Record[OpNum];
859 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
860 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
861 return error(
"Too few records for range");
864 OpNum += LowerActiveWords;
867 OpNum += UpperActiveWords;
870 int64_t
Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
871 int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
872 return ConstantRange(APInt(
BitWidth, Start,
true),
877 Expected<ConstantRange>
878 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,
unsigned &OpNum) {
879 if (
Record.size() - OpNum < 1)
880 return error(
"Too few records for range");
882 return readConstantRange(Record, OpNum,
BitWidth);
888 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
893 Error parseAlignmentValue(uint64_t
Exponent, MaybeAlign &Alignment);
894 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
896 ParserCallbacks Callbacks = {});
898 Error parseComdatRecord(ArrayRef<uint64_t> Record);
899 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
900 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
901 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
902 ArrayRef<uint64_t> Record);
904 Error parseAttributeBlock();
905 Error parseAttributeGroupBlock();
906 Error parseTypeTable();
907 Error parseTypeTableBody();
908 Error parseOperandBundleTags();
909 Error parseSyncScopeNames();
911 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
912 unsigned NameIndex, Triple &TT);
913 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta, Function *
F,
914 ArrayRef<uint64_t> Record);
916 Error parseGlobalValueSymbolTable();
917 Error parseConstants();
918 Error rememberAndSkipFunctionBodies();
919 Error rememberAndSkipFunctionBody();
921 Error rememberAndSkipMetadata();
923 Error parseFunctionBody(Function *
F);
924 Error globalCleanup();
925 Error resolveGlobalAndIndirectSymbolInits();
926 Error parseUseLists();
927 Error findFunctionInStream(
929 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
936class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
938 ModuleSummaryIndex &TheIndex;
942 bool SeenGlobalValSummary =
false;
945 bool SeenValueSymbolTable =
false;
949 uint64_t VSTOffset = 0;
959 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
960 ValueIdToValueInfoMap;
966 DenseMap<uint64_t, StringRef> ModuleIdMap;
969 std::string SourceFileName;
973 StringRef ModulePath;
981 std::vector<uint64_t> StackIds;
985 std::vector<uint64_t> RadixArray;
990 std::vector<unsigned> StackIdToIndex;
993 ModuleSummaryIndexBitcodeReader(
994 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
995 StringRef ModulePath,
1001 void setValueGUID(uint64_t ValueID, StringRef
ValueName,
1003 StringRef SourceFileName);
1004 Error parseValueSymbolTable(
1006 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1009 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1010 bool HasProfile,
bool HasRelBF);
1011 Error parseEntireSummary(
unsigned ID);
1012 Error parseModuleStringTable();
1013 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1014 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1016 std::vector<FunctionSummary::ParamAccess>
1017 parseParamAccesses(ArrayRef<uint64_t> Record);
1018 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1022 static constexpr unsigned UninitializedStackIdIndex =
1023 std::numeric_limits<unsigned>::max();
1025 unsigned getStackIdIndex(
unsigned LocalIndex) {
1026 unsigned &
Index = StackIdToIndex[LocalIndex];
1029 if (Index == UninitializedStackIdIndex)
1034 template <
bool AllowNullValueInfo = false>
1035 std::pair<ValueInfo, GlobalValue::GUID>
1036 getValueInfoFromValueId(
unsigned ValueId);
1038 void addThisModule();
1054 return std::error_code();
1060 : BitcodeReaderBase(
std::
move(Stream), Strtab), Context(Context),
1061 ValueList(this->Stream.SizeInBytes(),
1063 return materializeValue(
ValID, InsertBB);
1065 this->ProducerIdentification = std::string(ProducerIdentification);
1068Error BitcodeReader::materializeForwardReferencedFunctions() {
1069 if (WillMaterializeAllForwardRefs)
1073 WillMaterializeAllForwardRefs =
true;
1075 while (!BasicBlockFwdRefQueue.empty()) {
1076 Function *
F = BasicBlockFwdRefQueue.front();
1077 BasicBlockFwdRefQueue.pop_front();
1078 assert(
F &&
"Expected valid function");
1079 if (!BasicBlockFwdRefs.
count(
F))
1087 if (!
F->isMaterializable())
1088 return error(
"Never resolved function from blockaddress");
1091 if (
Error Err = materialize(
F))
1094 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1096 for (Function *
F : BackwardRefFunctions)
1097 if (
Error Err = materialize(
F))
1099 BackwardRefFunctions.clear();
1102 WillMaterializeAllForwardRefs =
false;
1167 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1168 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1169 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1170 Flags.NoInline = (RawFlags >> 4) & 0x1;
1171 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1172 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1173 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1174 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1175 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1191 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1);
1192 RawFlags = RawFlags >> 4;
1193 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1197 bool Live = (RawFlags & 0x2) || Version < 3;
1198 bool Local = (RawFlags & 0x4);
1199 bool AutoHide = (RawFlags & 0x8);
1202 Live,
Local, AutoHide, IK,
1203 NoRenameOnPromotion);
1209 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1210 (RawFlags & 0x4) ?
true :
false,
1214static std::pair<CalleeInfo::HotnessType, bool>
1218 bool HasTailCall = (RawFlags & 0x8);
1219 return {Hotness, HasTailCall};
1224 bool &HasTailCall) {
1225 static constexpr unsigned RelBlockFreqBits = 28;
1226 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1227 RelBF = RawFlags & RelBlockFreqMask;
1228 HasTailCall = (RawFlags & (1 << RelBlockFreqBits));
1253 case 0:
return false;
1254 case 1:
return true;
1316 bool IsFP = Ty->isFPOrFPVectorTy();
1318 if (!IsFP && !Ty->isIntOrIntVectorTy())
1325 return IsFP ? Instruction::FNeg : -1;
1330 bool IsFP = Ty->isFPOrFPVectorTy();
1332 if (!IsFP && !Ty->isIntOrIntVectorTy())
1339 return IsFP ? Instruction::FAdd : Instruction::Add;
1341 return IsFP ? Instruction::FSub : Instruction::Sub;
1343 return IsFP ? Instruction::FMul : Instruction::Mul;
1345 return IsFP ? -1 : Instruction::UDiv;
1347 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1349 return IsFP ? -1 : Instruction::URem;
1351 return IsFP ? Instruction::FRem : Instruction::SRem;
1353 return IsFP ? -1 : Instruction::Shl;
1355 return IsFP ? -1 : Instruction::LShr;
1357 return IsFP ? -1 : Instruction::AShr;
1359 return IsFP ? -1 : Instruction::And;
1361 return IsFP ? -1 : Instruction::Or;
1363 return IsFP ? -1 : Instruction::Xor;
1464Type *BitcodeReader::getTypeByID(
unsigned ID) {
1466 if (
ID >= TypeList.size())
1469 if (
Type *Ty = TypeList[
ID])
1474 return TypeList[
ID] = createIdentifiedStructType(
Context);
1477unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1478 auto It = ContainedTypeIDs.
find(
ID);
1479 if (It == ContainedTypeIDs.
end())
1480 return InvalidTypeID;
1482 if (Idx >= It->second.size())
1483 return InvalidTypeID;
1485 return It->second[Idx];
1488Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1489 if (
ID >= TypeList.size())
1496 return getTypeByID(getContainedTypeID(
ID, 0));
1499unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1500 ArrayRef<unsigned> ChildTypeIDs) {
1501 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1502 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1503 auto It = VirtualTypeIDs.
find(CacheKey);
1504 if (It != VirtualTypeIDs.
end()) {
1510 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1511 "Incorrect cached contained type IDs");
1515 unsigned TypeID = TypeList.size();
1516 TypeList.push_back(Ty);
1517 if (!ChildTypeIDs.
empty())
1538 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1552 if (Opcode == Instruction::GetElementPtr)
1556 case Instruction::FNeg:
1557 case Instruction::Select:
1558 case Instruction::ICmp:
1559 case Instruction::FCmp:
1566Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1567 BasicBlock *InsertBB) {
1569 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1571 return ValueList[StartValID];
1573 SmallDenseMap<unsigned, Value *> MaterializedValues;
1574 SmallVector<unsigned> Worklist;
1576 while (!Worklist.
empty()) {
1577 unsigned ValID = Worklist.
back();
1578 if (MaterializedValues.
count(ValID)) {
1584 if (ValID >= ValueList.
size() || !ValueList[ValID])
1585 return error(
"Invalid value ID");
1587 Value *
V = ValueList[ValID];
1590 MaterializedValues.
insert({ValID,
V});
1598 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1599 auto It = MaterializedValues.
find(OpID);
1600 if (It != MaterializedValues.
end())
1601 Ops.push_back(It->second);
1608 if (
Ops.size() != BC->getOperandIDs().size())
1610 std::reverse(
Ops.begin(),
Ops.end());
1627 switch (BC->Opcode) {
1628 case BitcodeConstant::ConstantPtrAuthOpcode: {
1631 return error(
"ptrauth key operand must be ConstantInt");
1635 return error(
"ptrauth disc operand must be ConstantInt");
1638 ConstOps.
size() > 4 ? ConstOps[4]
1643 "ptrauth deactivation symbol operand must be a pointer");
1646 DeactivationSymbol);
1649 case BitcodeConstant::NoCFIOpcode: {
1652 return error(
"no_cfi operand must be GlobalValue");
1656 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1659 return error(
"dso_local operand must be GlobalValue");
1663 case BitcodeConstant::BlockAddressOpcode: {
1666 return error(
"blockaddress operand must be a function");
1671 unsigned BBID = BC->BlockAddressBB;
1674 return error(
"Invalid ID");
1677 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1679 return error(
"Invalid ID");
1686 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1688 BasicBlockFwdRefQueue.push_back(Fn);
1689 if (FwdBBs.size() < BBID + 1)
1690 FwdBBs.resize(BBID + 1);
1698 case BitcodeConstant::ConstantStructOpcode: {
1700 if (
ST->getNumElements() != ConstOps.
size())
1701 return error(
"Invalid number of elements in struct initializer");
1703 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1704 if (
Op->getType() != Ty)
1705 return error(
"Incorrect type in struct initializer");
1710 case BitcodeConstant::ConstantArrayOpcode: {
1712 if (AT->getNumElements() != ConstOps.
size())
1713 return error(
"Invalid number of elements in array initializer");
1715 for (Constant *
Op : ConstOps)
1716 if (
Op->getType() != AT->getElementType())
1717 return error(
"Incorrect type in array initializer");
1722 case BitcodeConstant::ConstantVectorOpcode: {
1724 if (VT->getNumElements() != ConstOps.size())
1725 return error(
"Invalid number of elements in vector initializer");
1727 for (Constant *
Op : ConstOps)
1728 if (
Op->getType() != VT->getElementType())
1729 return error(
"Incorrect type in vector initializer");
1734 case Instruction::GetElementPtr:
1736 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1739 case Instruction::ExtractElement:
1742 case Instruction::InsertElement:
1746 case Instruction::ShuffleVector: {
1747 SmallVector<int, 16>
Mask;
1759 MaterializedValues.
insert({ValID,
C});
1765 return error(Twine(
"Value referenced by initializer is an unsupported "
1766 "constant expression of type ") +
1767 BC->getOpcodeName());
1773 BC->getType(),
"constexpr", InsertBB);
1776 "constexpr", InsertBB);
1779 Ops[1],
"constexpr", InsertBB);
1782 I->setHasNoSignedWrap();
1784 I->setHasNoUnsignedWrap();
1790 switch (BC->Opcode) {
1791 case BitcodeConstant::ConstantVectorOpcode: {
1792 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1795 Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1802 case BitcodeConstant::ConstantStructOpcode:
1803 case BitcodeConstant::ConstantArrayOpcode: {
1807 "constexpr.ins", InsertBB);
1811 case Instruction::ICmp:
1812 case Instruction::FCmp:
1815 "constexpr", InsertBB);
1817 case Instruction::GetElementPtr:
1823 case Instruction::Select:
1826 case Instruction::ExtractElement:
1829 case Instruction::InsertElement:
1833 case Instruction::ShuffleVector:
1834 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1842 MaterializedValues.
insert({ValID,
I});
1846 return MaterializedValues[StartValID];
1849Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1850 Expected<Value *> MaybeV = materializeValue(
ID,
nullptr);
1858StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1861 IdentifiedStructTypes.push_back(Ret);
1865StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1867 IdentifiedStructTypes.push_back(Ret);
1883 case Attribute::ZExt:
return 1 << 0;
1884 case Attribute::SExt:
return 1 << 1;
1885 case Attribute::NoReturn:
return 1 << 2;
1886 case Attribute::InReg:
return 1 << 3;
1887 case Attribute::StructRet:
return 1 << 4;
1888 case Attribute::NoUnwind:
return 1 << 5;
1889 case Attribute::NoAlias:
return 1 << 6;
1890 case Attribute::ByVal:
return 1 << 7;
1891 case Attribute::Nest:
return 1 << 8;
1892 case Attribute::ReadNone:
return 1 << 9;
1893 case Attribute::ReadOnly:
return 1 << 10;
1894 case Attribute::NoInline:
return 1 << 11;
1895 case Attribute::AlwaysInline:
return 1 << 12;
1896 case Attribute::OptimizeForSize:
return 1 << 13;
1897 case Attribute::StackProtect:
return 1 << 14;
1898 case Attribute::StackProtectReq:
return 1 << 15;
1899 case Attribute::Alignment:
return 31 << 16;
1901 case Attribute::NoRedZone:
return 1 << 22;
1902 case Attribute::NoImplicitFloat:
return 1 << 23;
1903 case Attribute::Naked:
return 1 << 24;
1904 case Attribute::InlineHint:
return 1 << 25;
1905 case Attribute::StackAlignment:
return 7 << 26;
1906 case Attribute::ReturnsTwice:
return 1 << 29;
1907 case Attribute::UWTable:
return 1 << 30;
1908 case Attribute::NonLazyBind:
return 1U << 31;
1909 case Attribute::SanitizeAddress:
return 1ULL << 32;
1910 case Attribute::MinSize:
return 1ULL << 33;
1911 case Attribute::NoDuplicate:
return 1ULL << 34;
1912 case Attribute::StackProtectStrong:
return 1ULL << 35;
1913 case Attribute::SanitizeThread:
return 1ULL << 36;
1914 case Attribute::SanitizeMemory:
return 1ULL << 37;
1915 case Attribute::NoBuiltin:
return 1ULL << 38;
1916 case Attribute::Returned:
return 1ULL << 39;
1917 case Attribute::Cold:
return 1ULL << 40;
1918 case Attribute::Builtin:
return 1ULL << 41;
1919 case Attribute::OptimizeNone:
return 1ULL << 42;
1920 case Attribute::InAlloca:
return 1ULL << 43;
1921 case Attribute::NonNull:
return 1ULL << 44;
1922 case Attribute::JumpTable:
return 1ULL << 45;
1923 case Attribute::Convergent:
return 1ULL << 46;
1924 case Attribute::SafeStack:
return 1ULL << 47;
1925 case Attribute::NoRecurse:
return 1ULL << 48;
1928 case Attribute::SwiftSelf:
return 1ULL << 51;
1929 case Attribute::SwiftError:
return 1ULL << 52;
1930 case Attribute::WriteOnly:
return 1ULL << 53;
1931 case Attribute::Speculatable:
return 1ULL << 54;
1932 case Attribute::StrictFP:
return 1ULL << 55;
1933 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1934 case Attribute::NoCfCheck:
return 1ULL << 57;
1935 case Attribute::OptForFuzzing:
return 1ULL << 58;
1936 case Attribute::ShadowCallStack:
return 1ULL << 59;
1937 case Attribute::SpeculativeLoadHardening:
1939 case Attribute::ImmArg:
1941 case Attribute::WillReturn:
1943 case Attribute::NoFree:
1959 if (
I == Attribute::Alignment)
1960 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
1961 else if (
I == Attribute::StackAlignment)
1962 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
1964 B.addTypeAttr(
I,
nullptr);
1978 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1980 "Alignment must be a power of two.");
1983 B.addAlignmentAttr(Alignment);
1985 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1986 (EncodedAttrs & 0xffff);
1988 if (AttrIdx == AttributeList::FunctionIndex) {
1991 if (Attrs & (1ULL << 9)) {
1993 Attrs &= ~(1ULL << 9);
1996 if (Attrs & (1ULL << 10)) {
1998 Attrs &= ~(1ULL << 10);
2001 if (Attrs & (1ULL << 49)) {
2003 Attrs &= ~(1ULL << 49);
2006 if (Attrs & (1ULL << 50)) {
2008 Attrs &= ~(1ULL << 50);
2011 if (Attrs & (1ULL << 53)) {
2013 Attrs &= ~(1ULL << 53);
2017 B.addMemoryAttr(ME);
2021 if (Attrs & (1ULL << 21)) {
2022 Attrs &= ~(1ULL << 21);
2029Error BitcodeReader::parseAttributeBlock() {
2033 if (!MAttributes.empty())
2034 return error(
"Invalid multiple blocks");
2036 SmallVector<uint64_t, 64>
Record;
2045 BitstreamEntry
Entry = MaybeEntry.
get();
2047 switch (
Entry.Kind) {
2050 return error(
"Malformed block");
2063 switch (MaybeRecord.
get()) {
2069 return error(
"Invalid parameter attribute record");
2071 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2077 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2081 for (uint64_t Val : Record)
2082 Attrs.push_back(MAttributeGroups[Val]);
2084 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2097 return Attribute::Alignment;
2099 return Attribute::AlwaysInline;
2101 return Attribute::Builtin;
2103 return Attribute::ByVal;
2105 return Attribute::InAlloca;
2107 return Attribute::Cold;
2109 return Attribute::Convergent;
2111 return Attribute::DisableSanitizerInstrumentation;
2113 return Attribute::ElementType;
2115 return Attribute::FnRetThunkExtern;
2117 return Attribute::Flatten;
2119 return Attribute::InlineHint;
2121 return Attribute::InReg;
2123 return Attribute::JumpTable;
2125 return Attribute::Memory;
2127 return Attribute::NoFPClass;
2129 return Attribute::MinSize;
2131 return Attribute::Naked;
2133 return Attribute::Nest;
2135 return Attribute::NoAlias;
2137 return Attribute::NoBuiltin;
2139 return Attribute::NoCallback;
2141 return Attribute::NoDivergenceSource;
2143 return Attribute::NoDuplicate;
2145 return Attribute::NoFree;
2147 return Attribute::NoImplicitFloat;
2149 return Attribute::NoInline;
2151 return Attribute::NoRecurse;
2153 return Attribute::NoMerge;
2155 return Attribute::NonLazyBind;
2157 return Attribute::NonNull;
2159 return Attribute::Dereferenceable;
2161 return Attribute::DereferenceableOrNull;
2163 return Attribute::AllocAlign;
2165 return Attribute::AllocKind;
2167 return Attribute::AllocSize;
2169 return Attribute::AllocatedPointer;
2171 return Attribute::NoRedZone;
2173 return Attribute::NoReturn;
2175 return Attribute::NoSync;
2177 return Attribute::NoCfCheck;
2179 return Attribute::NoProfile;
2181 return Attribute::SkipProfile;
2183 return Attribute::NoUnwind;
2185 return Attribute::NoSanitizeBounds;
2187 return Attribute::NoSanitizeCoverage;
2189 return Attribute::NullPointerIsValid;
2191 return Attribute::OptimizeForDebugging;
2193 return Attribute::OptForFuzzing;
2195 return Attribute::OptimizeForSize;
2197 return Attribute::OptimizeNone;
2199 return Attribute::ReadNone;
2201 return Attribute::ReadOnly;
2203 return Attribute::Returned;
2205 return Attribute::ReturnsTwice;
2207 return Attribute::SExt;
2209 return Attribute::Speculatable;
2211 return Attribute::StackAlignment;
2213 return Attribute::StackProtect;
2215 return Attribute::StackProtectReq;
2217 return Attribute::StackProtectStrong;
2219 return Attribute::SafeStack;
2221 return Attribute::ShadowCallStack;
2223 return Attribute::StrictFP;
2225 return Attribute::StructRet;
2227 return Attribute::SanitizeAddress;
2229 return Attribute::SanitizeHWAddress;
2231 return Attribute::SanitizeThread;
2233 return Attribute::SanitizeType;
2235 return Attribute::SanitizeMemory;
2237 return Attribute::SanitizeNumericalStability;
2239 return Attribute::SanitizeRealtime;
2241 return Attribute::SanitizeRealtimeBlocking;
2243 return Attribute::SanitizeAllocToken;
2245 return Attribute::SpeculativeLoadHardening;
2247 return Attribute::SwiftError;
2249 return Attribute::SwiftSelf;
2251 return Attribute::SwiftAsync;
2253 return Attribute::UWTable;
2255 return Attribute::VScaleRange;
2257 return Attribute::WillReturn;
2259 return Attribute::WriteOnly;
2261 return Attribute::ZExt;
2263 return Attribute::ImmArg;
2265 return Attribute::SanitizeMemTag;
2267 return Attribute::Preallocated;
2269 return Attribute::NoUndef;
2271 return Attribute::ByRef;
2273 return Attribute::MustProgress;
2275 return Attribute::Hot;
2277 return Attribute::PresplitCoroutine;
2279 return Attribute::Writable;
2281 return Attribute::CoroDestroyOnlyWhenComplete;
2283 return Attribute::DeadOnUnwind;
2285 return Attribute::Range;
2287 return Attribute::Initializes;
2289 return Attribute::CoroElideSafe;
2291 return Attribute::NoExt;
2293 return Attribute::Captures;
2295 return Attribute::DeadOnReturn;
2297 return Attribute::NoCreateUndefOrPoison;
2299 return Attribute::DenormalFPEnv;
2301 return Attribute::NoOutline;
2306 MaybeAlign &Alignment) {
2309 if (
Exponent > Value::MaxAlignmentExponent + 1)
2310 return error(
"Invalid alignment value");
2315Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2317 if (*Kind == Attribute::None)
2318 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2323 switch (EncodedKind) {
2347Error BitcodeReader::parseAttributeGroupBlock() {
2351 if (!MAttributeGroups.empty())
2352 return error(
"Invalid multiple blocks");
2354 SmallVector<uint64_t, 64>
Record;
2361 BitstreamEntry
Entry = MaybeEntry.
get();
2363 switch (
Entry.Kind) {
2366 return error(
"Malformed block");
2379 switch (MaybeRecord.
get()) {
2384 return error(
"Invalid grp record");
2386 uint64_t GrpID =
Record[0];
2387 uint64_t Idx =
Record[1];
2391 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2392 if (Record[i] == 0) {
2393 Attribute::AttrKind
Kind;
2394 uint64_t EncodedKind =
Record[++i];
2395 if (Idx == AttributeList::FunctionIndex &&
2404 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2410 if (Kind == Attribute::ByVal)
2411 B.addByValAttr(
nullptr);
2412 else if (Kind == Attribute::StructRet)
2413 B.addStructRetAttr(
nullptr);
2414 else if (Kind == Attribute::InAlloca)
2415 B.addInAllocaAttr(
nullptr);
2416 else if (Kind == Attribute::UWTable)
2417 B.addUWTableAttr(UWTableKind::Default);
2418 else if (Kind == Attribute::DeadOnReturn)
2419 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2420 else if (Attribute::isEnumAttrKind(Kind))
2421 B.addAttribute(Kind);
2423 return error(
"Not an enum attribute");
2424 }
else if (Record[i] == 1) {
2425 Attribute::AttrKind
Kind;
2426 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2428 if (!Attribute::isIntAttrKind(Kind))
2429 return error(
"Not an int attribute");
2430 if (Kind == Attribute::Alignment)
2431 B.addAlignmentAttr(Record[++i]);
2432 else if (Kind == Attribute::StackAlignment)
2433 B.addStackAlignmentAttr(Record[++i]);
2434 else if (Kind == Attribute::Dereferenceable)
2435 B.addDereferenceableAttr(Record[++i]);
2436 else if (Kind == Attribute::DereferenceableOrNull)
2437 B.addDereferenceableOrNullAttr(Record[++i]);
2438 else if (Kind == Attribute::DeadOnReturn)
2439 B.addDeadOnReturnAttr(
2441 else if (Kind == Attribute::AllocSize)
2442 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2443 else if (Kind == Attribute::VScaleRange)
2444 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2445 else if (Kind == Attribute::UWTable)
2447 else if (Kind == Attribute::AllocKind)
2448 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2449 else if (Kind == Attribute::Memory) {
2450 uint64_t EncodedME =
Record[++i];
2451 const uint8_t
Version = (EncodedME >> 56);
2463 B.addMemoryAttr(ME);
2468 EncodedME & 0x00FFFFFFFFFFFFFFULL));
2470 }
else if (Kind == Attribute::Captures)
2472 else if (Kind == Attribute::NoFPClass)
2475 else if (Kind == Attribute::DenormalFPEnv) {
2476 B.addDenormalFPEnvAttr(
2479 }
else if (Record[i] == 3 || Record[i] == 4) {
2481 SmallString<64> KindStr;
2482 SmallString<64> ValStr;
2484 while (Record[i] != 0 && i != e)
2486 assert(Record[i] == 0 &&
"Kind string not null terminated");
2491 while (Record[i] != 0 && i != e)
2493 assert(Record[i] == 0 &&
"Value string not null terminated");
2496 B.addAttribute(KindStr.
str(), ValStr.
str());
2497 }
else if (Record[i] == 5 || Record[i] == 6) {
2498 bool HasType =
Record[i] == 6;
2499 Attribute::AttrKind
Kind;
2500 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2502 if (!Attribute::isTypeAttrKind(Kind))
2503 return error(
"Not a type attribute");
2505 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2506 }
else if (Record[i] == 7) {
2507 Attribute::AttrKind
Kind;
2510 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2512 if (!Attribute::isConstantRangeAttrKind(Kind))
2513 return error(
"Not a ConstantRange attribute");
2515 Expected<ConstantRange> MaybeCR =
2516 readBitWidthAndConstantRange(Record, i);
2521 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2522 }
else if (Record[i] == 8) {
2523 Attribute::AttrKind
Kind;
2526 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2528 if (!Attribute::isConstantRangeListAttrKind(Kind))
2529 return error(
"Not a constant range list attribute");
2533 return error(
"Too few records for constant range list");
2534 unsigned RangeSize =
Record[i++];
2536 for (
unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2537 Expected<ConstantRange> MaybeCR =
2538 readConstantRange(Record, i,
BitWidth);
2546 return error(
"Invalid (unordered or overlapping) range list");
2547 B.addConstantRangeListAttr(Kind, Val);
2549 return error(
"Invalid attribute group entry");
2554 B.addMemoryAttr(ME);
2557 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2564Error BitcodeReader::parseTypeTable() {
2568 return parseTypeTableBody();
2571Error BitcodeReader::parseTypeTableBody() {
2572 if (!TypeList.empty())
2573 return error(
"Invalid multiple blocks");
2575 SmallVector<uint64_t, 64>
Record;
2576 unsigned NumRecords = 0;
2585 BitstreamEntry
Entry = MaybeEntry.
get();
2587 switch (
Entry.Kind) {
2590 return error(
"Malformed block");
2592 if (NumRecords != TypeList.size())
2593 return error(
"Malformed block");
2602 Type *ResultTy =
nullptr;
2603 SmallVector<unsigned> ContainedIDs;
2607 switch (MaybeRecord.
get()) {
2609 return error(
"Invalid value");
2614 return error(
"Invalid numentry record");
2615 TypeList.resize(Record[0]);
2618 ResultTy = Type::getVoidTy(
Context);
2621 ResultTy = Type::getHalfTy(
Context);
2624 ResultTy = Type::getBFloatTy(
Context);
2627 ResultTy = Type::getFloatTy(
Context);
2630 ResultTy = Type::getDoubleTy(
Context);
2633 ResultTy = Type::getX86_FP80Ty(
Context);
2636 ResultTy = Type::getFP128Ty(
Context);
2639 ResultTy = Type::getPPC_FP128Ty(
Context);
2642 ResultTy = Type::getLabelTy(
Context);
2645 ResultTy = Type::getMetadataTy(
Context);
2653 ResultTy = Type::getX86_AMXTy(
Context);
2656 ResultTy = Type::getTokenTy(
Context);
2660 return error(
"Invalid record");
2662 uint64_t NumBits =
Record[0];
2665 return error(
"Bitwidth for byte type out of range");
2671 return error(
"Invalid integer record");
2673 uint64_t NumBits =
Record[0];
2676 return error(
"Bitwidth for integer type out of range");
2683 return error(
"Invalid pointer record");
2687 ResultTy = getTypeByID(Record[0]);
2689 !PointerType::isValidElementType(ResultTy))
2690 return error(
"Invalid type");
2697 return error(
"Invalid opaque pointer record");
2706 return error(
"Invalid function record");
2708 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2709 if (
Type *
T = getTypeByID(Record[i]))
2715 ResultTy = getTypeByID(Record[2]);
2716 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2717 return error(
"Invalid type");
2720 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2726 return error(
"Invalid function record");
2728 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2729 if (
Type *
T = getTypeByID(Record[i])) {
2730 if (!FunctionType::isValidArgumentType(
T))
2731 return error(
"Invalid function argument type");
2738 ResultTy = getTypeByID(Record[1]);
2739 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2740 return error(
"Invalid type");
2743 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2748 return error(
"Invalid anon struct record");
2750 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2751 if (
Type *
T = getTypeByID(Record[i]))
2757 return error(
"Invalid type");
2764 return error(
"Invalid struct name record");
2769 return error(
"Invalid named struct record");
2771 if (NumRecords >= TypeList.size())
2772 return error(
"Invalid TYPE table");
2778 TypeList[NumRecords] =
nullptr;
2780 Res = createIdentifiedStructType(
Context, TypeName);
2784 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2785 if (
Type *
T = getTypeByID(Record[i]))
2791 return error(
"Invalid named struct record");
2800 return error(
"Invalid opaque type record");
2802 if (NumRecords >= TypeList.size())
2803 return error(
"Invalid TYPE table");
2809 TypeList[NumRecords] =
nullptr;
2811 Res = createIdentifiedStructType(
Context, TypeName);
2818 return error(
"Invalid target extension type record");
2820 if (NumRecords >= TypeList.size())
2821 return error(
"Invalid TYPE table");
2823 if (Record[0] >=
Record.size())
2824 return error(
"Too many type parameters");
2826 unsigned NumTys =
Record[0];
2828 SmallVector<unsigned, 8> IntParams;
2829 for (
unsigned i = 0; i < NumTys; i++) {
2830 if (
Type *
T = getTypeByID(Record[i + 1]))
2833 return error(
"Invalid type");
2836 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2837 if (Record[i] > UINT_MAX)
2838 return error(
"Integer parameter too large");
2843 if (
auto E = TTy.takeError())
2851 return error(
"Invalid array type record");
2852 ResultTy = getTypeByID(Record[1]);
2853 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2854 return error(
"Invalid type");
2856 ResultTy = ArrayType::get(ResultTy, Record[0]);
2861 return error(
"Invalid vector type record");
2863 return error(
"Invalid vector length");
2864 ResultTy = getTypeByID(Record[1]);
2865 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2866 return error(
"Invalid type");
2869 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2873 if (NumRecords >= TypeList.size())
2874 return error(
"Invalid TYPE table");
2875 if (TypeList[NumRecords])
2877 "Invalid TYPE table: Only named structs can be forward referenced");
2878 assert(ResultTy &&
"Didn't read a type?");
2879 TypeList[NumRecords] = ResultTy;
2880 if (!ContainedIDs.
empty())
2881 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2886Error BitcodeReader::parseOperandBundleTags() {
2890 if (!BundleTags.empty())
2891 return error(
"Invalid multiple blocks");
2893 SmallVector<uint64_t, 64>
Record;
2899 BitstreamEntry
Entry = MaybeEntry.
get();
2901 switch (
Entry.Kind) {
2904 return error(
"Malformed block");
2918 return error(
"Invalid operand bundle record");
2921 BundleTags.emplace_back();
2923 return error(
"Invalid operand bundle record");
2928Error BitcodeReader::parseSyncScopeNames() {
2933 return error(
"Invalid multiple synchronization scope names blocks");
2935 SmallVector<uint64_t, 64>
Record;
2940 BitstreamEntry
Entry = MaybeEntry.
get();
2942 switch (
Entry.Kind) {
2945 return error(
"Malformed block");
2948 return error(
"Invalid empty synchronization scope names block");
2962 return error(
"Invalid sync scope record");
2964 SmallString<16> SSN;
2966 return error(
"Invalid sync scope record");
2974Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2975 unsigned NameIndex, Triple &TT) {
2978 return error(
"Invalid record");
2979 unsigned ValueID =
Record[0];
2980 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
2981 return error(
"Invalid record");
2982 Value *
V = ValueList[ValueID];
2985 if (NameStr.contains(0))
2986 return error(
"Invalid value name");
2987 V->setName(NameStr);
2989 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
3002 return std::move(JumpFailed);
3008 return error(
"Expected value symbol table subblock");
3012void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
3014 ArrayRef<uint64_t> Record) {
3018 uint64_t FuncWordOffset =
Record[1] - 1;
3019 uint64_t FuncBitOffset = FuncWordOffset * 32;
3020 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3024 if (FuncBitOffset > LastFunctionBlockBit)
3025 LastFunctionBlockBit = FuncBitOffset;
3029Error BitcodeReader::parseGlobalValueSymbolTable() {
3030 unsigned FuncBitcodeOffsetDelta =
3036 SmallVector<uint64_t, 64>
Record;
3041 BitstreamEntry
Entry = MaybeEntry.
get();
3043 switch (
Entry.Kind) {
3046 return error(
"Malformed block");
3057 switch (MaybeRecord.
get()) {
3059 unsigned ValueID =
Record[0];
3060 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3061 return error(
"Invalid value reference in symbol table");
3062 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3072Error BitcodeReader::parseValueSymbolTable(uint64_t
Offset) {
3073 uint64_t CurrentBit;
3079 if (!MaybeCurrentBit)
3081 CurrentBit = MaybeCurrentBit.
get();
3084 if (
Error Err = parseGlobalValueSymbolTable())
3105 unsigned FuncBitcodeOffsetDelta =
3111 SmallVector<uint64_t, 64>
Record;
3122 BitstreamEntry
Entry = MaybeEntry.
get();
3124 switch (
Entry.Kind) {
3127 return error(
"Malformed block");
3143 switch (MaybeRecord.
get()) {
3147 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3155 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3163 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3168 return error(
"Invalid bbentry record");
3171 return error(
"Invalid bbentry record");
3183uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3193Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3194 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3195 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3196 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3198 GlobalInitWorklist.swap(GlobalInits);
3199 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3200 FunctionOperandWorklist.swap(FunctionOperands);
3202 while (!GlobalInitWorklist.empty()) {
3203 unsigned ValID = GlobalInitWorklist.back().second;
3204 if (ValID >= ValueList.
size()) {
3206 GlobalInits.push_back(GlobalInitWorklist.back());
3208 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3211 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3213 GlobalInitWorklist.pop_back();
3216 while (!IndirectSymbolInitWorklist.empty()) {
3217 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3218 if (ValID >= ValueList.
size()) {
3219 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3221 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3225 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3228 return error(
"Alias and aliasee types don't match");
3233 return error(
"Expected an alias or an ifunc");
3236 IndirectSymbolInitWorklist.pop_back();
3239 while (!FunctionOperandWorklist.empty()) {
3240 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3241 if (
Info.PersonalityFn) {
3242 unsigned ValID =
Info.PersonalityFn - 1;
3243 if (ValID < ValueList.
size()) {
3244 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3247 Info.F->setPersonalityFn(MaybeC.
get());
3248 Info.PersonalityFn = 0;
3252 unsigned ValID =
Info.Prefix - 1;
3253 if (ValID < ValueList.
size()) {
3254 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3257 Info.F->setPrefixData(MaybeC.
get());
3261 if (
Info.Prologue) {
3262 unsigned ValID =
Info.Prologue - 1;
3263 if (ValID < ValueList.
size()) {
3264 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3267 Info.F->setPrologueData(MaybeC.
get());
3271 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3272 FunctionOperands.push_back(Info);
3273 FunctionOperandWorklist.pop_back();
3282 BitcodeReader::decodeSignRotatedValue);
3284 return APInt(TypeBits, Words);
3287Error BitcodeReader::parseConstants() {
3295 unsigned Int32TyID = getVirtualTypeID(CurTy);
3296 unsigned CurTyID = Int32TyID;
3297 Type *CurElemTy =
nullptr;
3298 unsigned NextCstNo = ValueList.
size();
3306 switch (Entry.Kind) {
3309 return error(
"Malformed block");
3311 if (NextCstNo != ValueList.
size())
3312 return error(
"Invalid constant reference");
3323 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
3326 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3336 return error(
"Invalid settype record");
3337 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3338 return error(
"Invalid settype record");
3339 if (TypeList[Record[0]] == VoidType)
3340 return error(
"Invalid constant type");
3342 CurTy = TypeList[CurTyID];
3343 CurElemTy = getPtrElementTypeByID(CurTyID);
3347 return error(
"Invalid type for a constant null value");
3350 return error(
"Invalid type for a constant null value");
3355 return error(
"Invalid integer const record");
3360 return error(
"Invalid wide integer const record");
3363 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3364 V = ConstantInt::get(CurTy, VInt);
3369 return error(
"Invalid byte const record");
3370 V = ConstantByte::get(CurTy, decodeSignRotatedValue(Record[0]));
3374 return error(
"Invalid wide byte const record");
3377 APInt VByte =
readWideAPInt(Record, ScalarTy->getBitWidth());
3378 V = ConstantByte::get(CurTy, VByte);
3383 return error(
"Invalid float const record");
3386 if (ScalarTy->isHalfTy())
3387 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3388 APInt(16, (uint16_t)Record[0])));
3389 else if (ScalarTy->isBFloatTy())
3390 V = ConstantFP::get(
3391 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3392 else if (ScalarTy->isFloatTy())
3393 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3394 APInt(32, (uint32_t)Record[0])));
3395 else if (ScalarTy->isDoubleTy())
3396 V = ConstantFP::get(
3397 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3398 else if (ScalarTy->isX86_FP80Ty()) {
3400 uint64_t Rearrange[2];
3401 Rearrange[0] = (
Record[1] & 0xffffLL) | (Record[0] << 16);
3402 Rearrange[1] =
Record[0] >> 48;
3403 V = ConstantFP::get(
3404 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3405 }
else if (ScalarTy->isFP128Ty())
3406 V = ConstantFP::get(CurTy,
3407 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3408 else if (ScalarTy->isPPC_FP128Ty())
3409 V = ConstantFP::get(
3410 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3418 return error(
"Invalid aggregate record");
3420 SmallVector<unsigned, 16> Elts;
3424 V = BitcodeConstant::create(
3425 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3427 V = BitcodeConstant::create(
Alloc, CurTy,
3428 BitcodeConstant::ConstantArrayOpcode, Elts);
3430 V = BitcodeConstant::create(
3431 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3440 return error(
"Invalid string record");
3450 return error(
"Invalid data record");
3454 EltTy =
Array->getElementType();
3464 SmallVector<uint16_t, 16> Elts(
Record.begin(),
Record.end());
3470 SmallVector<uint32_t, 16> Elts(
Record.begin(),
Record.end());
3476 SmallVector<uint64_t, 16> Elts(
Record.begin(),
Record.end());
3488 SmallVector<uint16_t, 16> Elts(
Record.begin(),
Record.end());
3494 SmallVector<uint32_t, 16> Elts(
Record.begin(),
Record.end());
3500 SmallVector<uint64_t, 16> Elts(
Record.begin(),
Record.end());
3506 SmallVector<uint16_t, 16> Elts(
Record.begin(),
Record.end());
3512 SmallVector<uint16_t, 16> Elts(
Record.begin(),
Record.end());
3518 SmallVector<uint32_t, 16> Elts(
Record.begin(),
Record.end());
3524 SmallVector<uint64_t, 16> Elts(
Record.begin(),
Record.end());
3530 return error(
"Invalid type for value");
3536 return error(
"Invalid unary op constexpr record");
3541 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3547 return error(
"Invalid binary op constexpr record");
3553 if (
Record.size() >= 4) {
3554 if (
Opc == Instruction::Add ||
3555 Opc == Instruction::Sub ||
3556 Opc == Instruction::Mul ||
3557 Opc == Instruction::Shl) {
3562 }
else if (
Opc == Instruction::SDiv ||
3563 Opc == Instruction::UDiv ||
3564 Opc == Instruction::LShr ||
3565 Opc == Instruction::AShr) {
3570 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3571 {(unsigned)Record[1], (
unsigned)
Record[2]});
3577 return error(
"Invalid cast constexpr record");
3582 unsigned OpTyID =
Record[1];
3583 Type *OpTy = getTypeByID(OpTyID);
3585 return error(
"Invalid cast constexpr record");
3586 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3598 return error(
"Constant GEP record must have at least two elements");
3600 Type *PointeeType =
nullptr;
3604 PointeeType = getTypeByID(Record[OpNum++]);
3607 std::optional<ConstantRange>
InRange;
3611 unsigned InRangeIndex =
Op >> 1;
3617 Expected<ConstantRange> MaybeInRange =
3618 readBitWidthAndConstantRange(Record, OpNum);
3627 SmallVector<unsigned, 16> Elts;
3628 unsigned BaseTypeID =
Record[OpNum];
3629 while (OpNum !=
Record.size()) {
3630 unsigned ElTyID =
Record[OpNum++];
3631 Type *ElTy = getTypeByID(ElTyID);
3633 return error(
"Invalid getelementptr constexpr record");
3637 if (Elts.
size() < 1)
3638 return error(
"Invalid gep with no operands");
3642 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3643 BaseType = getTypeByID(BaseTypeID);
3648 return error(
"GEP base operand must be pointer or vector of pointer");
3651 PointeeType = getPtrElementTypeByID(BaseTypeID);
3653 return error(
"Missing element type for old-style constant GEP");
3656 V = BitcodeConstant::create(
3658 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3664 return error(
"Invalid select constexpr record");
3666 V = BitcodeConstant::create(
3667 Alloc, CurTy, Instruction::Select,
3668 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3674 return error(
"Invalid extractelement constexpr record");
3675 unsigned OpTyID =
Record[0];
3679 return error(
"Invalid extractelement constexpr record");
3681 if (
Record.size() == 4) {
3682 unsigned IdxTyID =
Record[2];
3683 Type *IdxTy = getTypeByID(IdxTyID);
3685 return error(
"Invalid extractelement constexpr record");
3691 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3692 {(unsigned)Record[1], IdxRecord});
3698 if (
Record.size() < 3 || !OpTy)
3699 return error(
"Invalid insertelement constexpr record");
3701 if (
Record.size() == 4) {
3702 unsigned IdxTyID =
Record[2];
3703 Type *IdxTy = getTypeByID(IdxTyID);
3705 return error(
"Invalid insertelement constexpr record");
3711 V = BitcodeConstant::create(
3712 Alloc, CurTy, Instruction::InsertElement,
3713 {(unsigned)Record[0], (
unsigned)
Record[1], IdxRecord});
3718 if (
Record.size() < 3 || !OpTy)
3719 return error(
"Invalid shufflevector constexpr record");
3720 V = BitcodeConstant::create(
3721 Alloc, CurTy, Instruction::ShuffleVector,
3722 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3729 if (
Record.size() < 4 || !RTy || !OpTy)
3730 return error(
"Invalid shufflevector constexpr record");
3731 V = BitcodeConstant::create(
3732 Alloc, CurTy, Instruction::ShuffleVector,
3733 {(unsigned)Record[1], (
unsigned)
Record[2], (unsigned)Record[3]});
3738 return error(
"Invalid cmp constexpt record");
3739 unsigned OpTyID =
Record[0];
3740 Type *OpTy = getTypeByID(OpTyID);
3742 return error(
"Invalid cmp constexpr record");
3743 V = BitcodeConstant::create(
3746 : Instruction::ICmp),
3747 (uint8_t)Record[3]},
3748 {(unsigned)Record[1], (
unsigned)
Record[2]});
3755 return error(
"Invalid inlineasm record");
3756 std::string AsmStr, ConstrStr;
3757 bool HasSideEffects =
Record[0] & 1;
3758 bool IsAlignStack =
Record[0] >> 1;
3759 unsigned AsmStrSize =
Record[1];
3760 if (2+AsmStrSize >=
Record.size())
3761 return error(
"Invalid inlineasm record");
3762 unsigned ConstStrSize =
Record[2+AsmStrSize];
3763 if (3+AsmStrSize+ConstStrSize >
Record.size())
3764 return error(
"Invalid inlineasm record");
3766 for (
unsigned i = 0; i != AsmStrSize; ++i)
3767 AsmStr += (
char)
Record[2+i];
3768 for (
unsigned i = 0; i != ConstStrSize; ++i)
3769 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3772 return error(
"Missing element type for old-style inlineasm");
3774 HasSideEffects, IsAlignStack);
3781 return error(
"Invalid inlineasm record");
3782 std::string AsmStr, ConstrStr;
3783 bool HasSideEffects =
Record[0] & 1;
3784 bool IsAlignStack = (
Record[0] >> 1) & 1;
3785 unsigned AsmDialect =
Record[0] >> 2;
3786 unsigned AsmStrSize =
Record[1];
3787 if (2+AsmStrSize >=
Record.size())
3788 return error(
"Invalid inlineasm record");
3789 unsigned ConstStrSize =
Record[2+AsmStrSize];
3790 if (3+AsmStrSize+ConstStrSize >
Record.size())
3791 return error(
"Invalid inlineasm record");
3793 for (
unsigned i = 0; i != AsmStrSize; ++i)
3794 AsmStr += (
char)
Record[2+i];
3795 for (
unsigned i = 0; i != ConstStrSize; ++i)
3796 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3799 return error(
"Missing element type for old-style inlineasm");
3801 HasSideEffects, IsAlignStack,
3808 return error(
"Invalid inlineasm record");
3810 std::string AsmStr, ConstrStr;
3811 bool HasSideEffects =
Record[OpNum] & 1;
3812 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3813 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3814 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3816 unsigned AsmStrSize =
Record[OpNum];
3818 if (OpNum + AsmStrSize >=
Record.size())
3819 return error(
"Invalid inlineasm record");
3820 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3821 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3822 return error(
"Invalid inlineasm record");
3824 for (
unsigned i = 0; i != AsmStrSize; ++i)
3825 AsmStr += (
char)
Record[OpNum + i];
3827 for (
unsigned i = 0; i != ConstStrSize; ++i)
3828 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3831 return error(
"Missing element type for old-style inlineasm");
3833 HasSideEffects, IsAlignStack,
3840 return error(
"Invalid inlineasm record");
3845 return error(
"Invalid inlineasm record");
3846 std::string AsmStr, ConstrStr;
3847 bool HasSideEffects =
Record[OpNum] & 1;
3848 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3849 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3850 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3852 unsigned AsmStrSize =
Record[OpNum];
3854 if (OpNum + AsmStrSize >=
Record.size())
3855 return error(
"Invalid inlineasm record");
3856 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3857 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3858 return error(
"Invalid inlineasm record");
3860 for (
unsigned i = 0; i != AsmStrSize; ++i)
3861 AsmStr += (
char)
Record[OpNum + i];
3863 for (
unsigned i = 0; i != ConstStrSize; ++i)
3864 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3866 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3872 return error(
"Invalid blockaddress record");
3873 unsigned FnTyID =
Record[0];
3874 Type *FnTy = getTypeByID(FnTyID);
3876 return error(
"Invalid blockaddress record");
3877 V = BitcodeConstant::create(
3879 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3885 return error(
"Invalid dso_local record");
3886 unsigned GVTyID =
Record[0];
3887 Type *GVTy = getTypeByID(GVTyID);
3889 return error(
"Invalid dso_local record");
3890 V = BitcodeConstant::create(
3891 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3896 return error(
"Invalid no_cfi record");
3897 unsigned GVTyID =
Record[0];
3898 Type *GVTy = getTypeByID(GVTyID);
3900 return error(
"Invalid no_cfi record");
3901 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3907 return error(
"Invalid ptrauth record");
3909 V = BitcodeConstant::create(
Alloc, CurTy,
3910 BitcodeConstant::ConstantPtrAuthOpcode,
3911 {(unsigned)Record[0], (
unsigned)
Record[1],
3912 (unsigned)Record[2], (
unsigned)
Record[3]});
3917 return error(
"Invalid ptrauth record");
3919 V = BitcodeConstant::create(
3920 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3921 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2],
3922 (
unsigned)
Record[3], (unsigned)Record[4]});
3927 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3934Error BitcodeReader::parseUseLists() {
3939 SmallVector<uint64_t, 64>
Record;
3945 BitstreamEntry
Entry = MaybeEntry.
get();
3947 switch (
Entry.Kind) {
3950 return error(
"Malformed block");
3964 switch (MaybeRecord.
get()) {
3972 if (RecordLength < 3)
3974 return error(
"Invalid uselist record");
3975 unsigned ID =
Record.pop_back_val();
3979 assert(
ID < FunctionBBs.size() &&
"Basic block not found");
3980 V = FunctionBBs[
ID];
3984 if (!
V->hasUseList())
3987 unsigned NumUses = 0;
3988 SmallDenseMap<const Use *, unsigned, 16> Order;
3989 for (
const Use &U :
V->materialized_uses()) {
3990 if (++NumUses >
Record.size())
3992 Order[&
U] =
Record[NumUses - 1];
3999 V->sortUseList([&](
const Use &L,
const Use &R) {
4010Error BitcodeReader::rememberAndSkipMetadata() {
4013 DeferredMetadataInfo.push_back(CurBit);
4021Error BitcodeReader::materializeMetadata() {
4022 for (uint64_t BitPos : DeferredMetadataInfo) {
4026 if (
Error Err = MDLoader->parseModuleMetadata())
4035 NamedMDNode *LinkerOpts =
4037 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
4042 DeferredMetadataInfo.clear();
4046void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
4050Error BitcodeReader::rememberAndSkipFunctionBody() {
4052 if (FunctionsWithBodies.empty())
4053 return error(
"Insufficient function protos");
4055 Function *Fn = FunctionsWithBodies.back();
4056 FunctionsWithBodies.pop_back();
4061 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4062 "Mismatch between VST and scanned function offsets");
4063 DeferredFunctionInfo[Fn] = CurBit;
4071Error BitcodeReader::globalCleanup() {
4073 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4075 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4076 return error(
"Malformed global initializer set");
4080 for (Function &
F : *TheModule) {
4081 MDLoader->upgradeDebugIntrinsics(
F);
4084 UpgradedIntrinsics[&
F] = NewFn;
4090 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4091 for (GlobalVariable &GV : TheModule->globals())
4093 UpgradedVariables.emplace_back(&GV, Upgraded);
4094 for (
auto &Pair : UpgradedVariables) {
4095 Pair.first->eraseFromParent();
4096 TheModule->insertGlobalVariable(Pair.second);
4101 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
4102 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4110Error BitcodeReader::rememberAndSkipFunctionBodies() {
4115 return error(
"Could not find function in stream");
4117 if (!SeenFirstFunctionBody)
4118 return error(
"Trying to materialize functions before seeing function blocks");
4122 assert(SeenValueSymbolTable);
4125 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4128 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4130 switch (
Entry.Kind) {
4132 return error(
"Expect SubBlock");
4136 return error(
"Expect function block");
4138 if (
Error Err = rememberAndSkipFunctionBody())
4147Error BitcodeReaderBase::readBlockInfo() {
4148 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4150 if (!MaybeNewBlockInfo)
4152 std::optional<BitstreamBlockInfo> NewBlockInfo =
4153 std::move(MaybeNewBlockInfo.
get());
4155 return error(
"Malformed block");
4156 BlockInfo = std::move(*NewBlockInfo);
4160Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4164 std::tie(Name, Record) = readNameFromStrtab(Record);
4167 return error(
"Invalid comdat record");
4169 std::string OldFormatName;
4172 return error(
"Invalid comdat record");
4173 unsigned ComdatNameSize =
Record[1];
4174 if (ComdatNameSize >
Record.size() - 2)
4175 return error(
"Comdat name size too large");
4176 OldFormatName.reserve(ComdatNameSize);
4177 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4178 OldFormatName += (
char)
Record[2 + i];
4179 Name = OldFormatName;
4181 Comdat *
C = TheModule->getOrInsertComdat(Name);
4182 C->setSelectionKind(SK);
4183 ComdatList.push_back(
C);
4197 Meta.NoAddress =
true;
4199 Meta.NoHWAddress =
true;
4203 Meta.IsDynInit =
true;
4207Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4215 std::tie(Name, Record) = readNameFromStrtab(Record);
4218 return error(
"Invalid global variable record");
4219 unsigned TyID =
Record[0];
4220 Type *Ty = getTypeByID(TyID);
4222 return error(
"Invalid global variable record");
4224 bool explicitType =
Record[1] & 2;
4230 return error(
"Invalid type for value");
4232 TyID = getContainedTypeID(TyID);
4233 Ty = getTypeByID(TyID);
4235 return error(
"Missing element type for old-style global");
4238 uint64_t RawLinkage =
Record[3];
4240 MaybeAlign Alignment;
4241 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4245 if (Record[5] - 1 >= SectionTable.size())
4246 return error(
"Invalid ID");
4255 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4263 bool ExternallyInitialized =
false;
4265 ExternallyInitialized =
Record[9];
4267 GlobalVariable *NewGV =
4277 if (
Record.size() > 10) {
4289 if (
unsigned InitID = Record[2])
4290 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4292 if (
Record.size() > 11) {
4293 if (
unsigned ComdatID = Record[11]) {
4294 if (ComdatID > ComdatList.size())
4295 return error(
"Invalid global variable comdat ID");
4296 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4299 ImplicitComdatObjects.
insert(NewGV);
4302 if (
Record.size() > 12) {
4307 if (
Record.size() > 13) {
4316 if (
Record.size() > 16 && Record[16]) {
4317 llvm::GlobalValue::SanitizerMetadata
Meta =
4322 if (
Record.size() > 17 && Record[17]) {
4326 return error(
"Invalid global variable code model");
4332void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4333 if (ValueTypeCallback) {
4334 (*ValueTypeCallback)(
4335 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4336 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4340Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4346 std::tie(Name, Record) = readNameFromStrtab(Record);
4349 return error(
"Invalid function record");
4350 unsigned FTyID =
Record[0];
4351 Type *FTy = getTypeByID(FTyID);
4353 return error(
"Invalid function record");
4355 FTyID = getContainedTypeID(FTyID, 0);
4356 FTy = getTypeByID(FTyID);
4358 return error(
"Missing element type for old-style function");
4362 return error(
"Invalid type for value");
4363 auto CC =
static_cast<CallingConv::ID
>(
Record[1]);
4364 if (CC & ~CallingConv::MaxID)
4365 return error(
"Invalid calling convention ID");
4367 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4373 AddrSpace, Name, TheModule);
4376 "Incorrect fully specified type provided for function");
4377 FunctionTypeIDs[
Func] = FTyID;
4379 Func->setCallingConv(CC);
4380 bool isProto =
Record[2];
4381 uint64_t RawLinkage =
Record[3];
4384 callValueTypeCallback(Func, FTyID);
4389 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4390 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4391 Attribute::InAlloca}) {
4392 if (!
Func->hasParamAttribute(i, Kind))
4395 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4398 Func->removeParamAttr(i, Kind);
4400 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4401 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4403 return error(
"Missing param element type for attribute upgrade");
4407 case Attribute::ByVal:
4408 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4410 case Attribute::StructRet:
4411 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4413 case Attribute::InAlloca:
4414 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4420 Func->addParamAttr(i, NewAttr);
4424 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4425 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4426 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4427 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4429 return error(
"Missing param element type for x86_intrcc upgrade");
4431 Func->addParamAttr(0, NewAttr);
4434 MaybeAlign Alignment;
4435 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4438 Func->setAlignment(*Alignment);
4440 if (Record[6] - 1 >= SectionTable.size())
4441 return error(
"Invalid ID");
4442 Func->setSection(SectionTable[Record[6] - 1]);
4446 if (!
Func->hasLocalLinkage())
4448 if (
Record.size() > 8 && Record[8]) {
4449 if (Record[8] - 1 >= GCTable.size())
4450 return error(
"Invalid ID");
4451 Func->setGC(GCTable[Record[8] - 1]);
4456 Func->setUnnamedAddr(UnnamedAddr);
4458 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4460 OperandInfo.Prologue =
Record[10];
4462 if (
Record.size() > 11) {
4464 if (!
Func->hasLocalLinkage()) {
4471 if (
Record.size() > 12) {
4472 if (
unsigned ComdatID = Record[12]) {
4473 if (ComdatID > ComdatList.size())
4474 return error(
"Invalid function comdat ID");
4475 Func->setComdat(ComdatList[ComdatID - 1]);
4478 ImplicitComdatObjects.
insert(Func);
4482 OperandInfo.Prefix =
Record[13];
4485 OperandInfo.PersonalityFn =
Record[14];
4487 if (
Record.size() > 15) {
4497 Record[17] + Record[18] <= Strtab.
size()) {
4498 Func->setPartition(StringRef(Strtab.
data() + Record[17], Record[18]));
4501 if (
Record.size() > 19) {
4502 MaybeAlign PrefAlignment;
4503 if (
Error Err = parseAlignmentValue(Record[19], PrefAlignment))
4505 Func->setPreferredAlignment(PrefAlignment);
4508 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4510 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4511 FunctionOperands.push_back(OperandInfo);
4516 Func->setIsMaterializable(
true);
4517 FunctionsWithBodies.push_back(Func);
4518 DeferredFunctionInfo[
Func] = 0;
4523Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4524 unsigned BitCode, ArrayRef<uint64_t> Record) {
4534 std::tie(Name, Record) = readNameFromStrtab(Record);
4537 if (
Record.size() < (3 + (
unsigned)NewRecord))
4538 return error(
"Invalid global indirect symbol record");
4543 return error(
"Invalid global indirect symbol record");
4549 return error(
"Invalid type for value");
4550 AddrSpace = PTy->getAddressSpace();
4552 Ty = getTypeByID(
TypeID);
4554 return error(
"Missing element type for old-style indirect symbol");
4556 AddrSpace =
Record[OpNum++];
4559 auto Val =
Record[OpNum++];
4568 nullptr, TheModule);
4572 if (OpNum !=
Record.size()) {
4573 auto VisInd = OpNum++;
4579 if (OpNum !=
Record.size()) {
4580 auto S =
Record[OpNum++];
4587 if (OpNum !=
Record.size())
4589 if (OpNum !=
Record.size())
4592 if (OpNum !=
Record.size())
4597 if (OpNum + 1 <
Record.size()) {
4599 if (Record[OpNum] + Record[OpNum + 1] > Strtab.
size())
4600 return error(
"Malformed partition, too large.");
4602 StringRef(Strtab.
data() + Record[OpNum], Record[OpNum + 1]));
4606 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4610Error BitcodeReader::parseModule(uint64_t ResumeBit,
4611 bool ShouldLazyLoadMetadata,
4612 ParserCallbacks Callbacks) {
4613 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4620 SmallVector<uint64_t, 64>
Record;
4624 bool ResolvedDataLayout =
false;
4629 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4631 auto ResolveDataLayout = [&]() ->
Error {
4632 if (ResolvedDataLayout)
4636 ResolvedDataLayout =
true;
4640 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4644 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4645 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4646 TentativeDataLayoutStr = *LayoutOverride;
4654 TheModule->setDataLayout(MaybeDL.
get());
4660 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4663 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4665 switch (
Entry.Kind) {
4667 return error(
"Malformed block");
4669 if (
Error Err = ResolveDataLayout())
4671 return globalCleanup();
4680 if (
Error Err = readBlockInfo())
4684 if (
Error Err = parseAttributeBlock())
4688 if (
Error Err = parseAttributeGroupBlock())
4692 if (
Error Err = parseTypeTable())
4696 if (!SeenValueSymbolTable) {
4702 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4703 if (
Error Err = parseValueSymbolTable())
4705 SeenValueSymbolTable =
true;
4715 if (
Error Err = parseConstants())
4717 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4721 if (ShouldLazyLoadMetadata) {
4722 if (
Error Err = rememberAndSkipMetadata())
4726 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4727 if (
Error Err = MDLoader->parseModuleMetadata())
4731 if (
Error Err = MDLoader->parseMetadataKinds())
4735 if (
Error Err = ResolveDataLayout())
4740 if (!SeenFirstFunctionBody) {
4741 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4742 if (
Error Err = globalCleanup())
4744 SeenFirstFunctionBody =
true;
4747 if (VSTOffset > 0) {
4751 if (!SeenValueSymbolTable) {
4752 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4754 SeenValueSymbolTable =
true;
4776 if (
Error Err = rememberAndSkipFunctionBody())
4783 if (SeenValueSymbolTable) {
4787 return globalCleanup();
4791 if (
Error Err = parseUseLists())
4795 if (
Error Err = parseOperandBundleTags())
4799 if (
Error Err = parseSyncScopeNames())
4811 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
4814 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4817 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4820 UseRelativeIDs = *VersionOrErr >= 1;
4824 if (ResolvedDataLayout)
4825 return error(
"target triple too late in module");
4828 return error(
"Invalid triple record");
4829 TheModule->setTargetTriple(Triple(std::move(S)));
4833 if (ResolvedDataLayout)
4834 return error(
"datalayout too late in module");
4836 return error(
"Invalid data layout record");
4842 return error(
"Invalid asm record");
4843 TheModule->setModuleInlineAsm(S);
4850 return error(
"Invalid deplib record");
4857 return error(
"Invalid section name record");
4858 SectionTable.push_back(S);
4864 return error(
"Invalid gcname record");
4865 GCTable.push_back(S);
4869 if (
Error Err = parseComdatRecord(Record))
4878 if (
Error Err = parseGlobalVarRecord(Record))
4882 if (
Error Err = ResolveDataLayout())
4884 if (
Error Err = parseFunctionRecord(Record))
4890 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4896 return error(
"Invalid vstoffset record");
4900 VSTOffset =
Record[0] - 1;
4906 return error(
"Invalid source filename record");
4907 TheModule->setSourceFileName(
ValueName);
4912 this->ValueTypeCallback = std::nullopt;
4916Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4918 ParserCallbacks Callbacks) {
4920 MetadataLoaderCallbacks MDCallbacks;
4921 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(
ID); };
4923 return getContainedTypeID(
I, J);
4926 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4927 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4930Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4932 return error(
"Load/Store operand is not a pointer type");
4933 if (!PointerType::isLoadableOrStorableType(ValType))
4934 return error(
"Cannot load/store from pointer");
4938Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4939 ArrayRef<unsigned> ArgTyIDs) {
4941 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4942 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4943 Attribute::InAlloca}) {
4944 if (!
Attrs.hasParamAttr(i, Kind) ||
4945 Attrs.getParamAttr(i, Kind).getValueAsType())
4948 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4950 return error(
"Missing element type for typed attribute upgrade");
4954 case Attribute::ByVal:
4955 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4957 case Attribute::StructRet:
4958 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4960 case Attribute::InAlloca:
4961 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4974 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
4978 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
4979 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4981 return error(
"Missing element type for inline asm upgrade");
4984 Attribute::get(
Context, Attribute::ElementType, ElemTy));
4992 case Intrinsic::preserve_array_access_index:
4993 case Intrinsic::preserve_struct_access_index:
4994 case Intrinsic::aarch64_ldaxr:
4995 case Intrinsic::aarch64_ldxr:
4996 case Intrinsic::aarch64_stlxr:
4997 case Intrinsic::aarch64_stxr:
4998 case Intrinsic::arm_ldaex:
4999 case Intrinsic::arm_ldrex:
5000 case Intrinsic::arm_stlex:
5001 case Intrinsic::arm_strex: {
5004 case Intrinsic::aarch64_stlxr:
5005 case Intrinsic::aarch64_stxr:
5006 case Intrinsic::arm_stlex:
5007 case Intrinsic::arm_strex:
5014 if (!
Attrs.getParamElementType(ArgNo)) {
5015 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5017 return error(
"Missing element type for elementtype upgrade");
5032Error BitcodeReader::parseFunctionBody(Function *
F) {
5037 if (MDLoader->hasFwdRefs())
5038 return error(
"Invalid function metadata: incoming forward references");
5040 InstructionList.
clear();
5041 unsigned ModuleValueListSize = ValueList.
size();
5042 unsigned ModuleMDLoaderSize = MDLoader->size();
5046 unsigned FTyID = FunctionTypeIDs[
F];
5047 for (Argument &
I :
F->args()) {
5048 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
5049 assert(
I.getType() == getTypeByID(ArgTyID) &&
5050 "Incorrect fully specified type for Function Argument");
5054 unsigned NextValueNo = ValueList.
size();
5056 unsigned CurBBNo = 0;
5061 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
5065 auto getLastInstruction = [&]() -> Instruction * {
5066 if (CurBB && !CurBB->
empty())
5067 return &CurBB->
back();
5068 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5069 !FunctionBBs[CurBBNo - 1]->
empty())
5070 return &FunctionBBs[CurBBNo - 1]->back();
5074 std::vector<OperandBundleDef> OperandBundles;
5077 SmallVector<uint64_t, 64>
Record;
5080 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
5083 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
5085 switch (
Entry.Kind) {
5087 return error(
"Malformed block");
5089 goto OutOfRecordLoop;
5098 if (
Error Err = parseConstants())
5100 NextValueNo = ValueList.
size();
5103 if (
Error Err = parseValueSymbolTable())
5107 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
5111 assert(DeferredMetadataInfo.empty() &&
5112 "Must read all module-level metadata before function-level");
5113 if (
Error Err = MDLoader->parseFunctionMetadata())
5117 if (
Error Err = parseUseLists())
5131 unsigned ResTypeID = InvalidTypeID;
5132 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
5135 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5137 return error(
"Invalid value");
5139 if (
Record.empty() || Record[0] == 0)
5140 return error(
"Invalid declareblocks record");
5142 FunctionBBs.resize(Record[0]);
5145 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5146 if (BBFRI == BasicBlockFwdRefs.
end()) {
5147 for (BasicBlock *&BB : FunctionBBs)
5150 auto &BBRefs = BBFRI->second;
5152 if (BBRefs.size() > FunctionBBs.size())
5153 return error(
"Invalid ID");
5154 assert(!BBRefs.empty() &&
"Unexpected empty array");
5155 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5156 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5158 if (
I < RE && BBRefs[
I]) {
5159 BBRefs[
I]->insertInto(
F);
5160 FunctionBBs[
I] = BBRefs[
I];
5166 BasicBlockFwdRefs.
erase(BBFRI);
5169 CurBB = FunctionBBs[0];
5176 return error(
"Invalid blockaddr users record");
5190 for (uint64_t ValID : Record)
5192 BackwardRefFunctions.push_back(
F);
5194 return error(
"Invalid blockaddr users record");
5201 I = getLastInstruction();
5204 return error(
"Invalid debug_loc_again record");
5205 I->setDebugLoc(LastLoc);
5210 I = getLastInstruction();
5212 return error(
"Invalid debug loc record");
5217 uint64_t AtomGroup =
Record.size() == 7 ?
Record[5] : 0;
5220 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5223 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5225 return error(
"Invalid debug loc record");
5229 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5231 return error(
"Invalid debug loc record");
5234 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5235 isImplicitCode, AtomGroup, AtomRank);
5236 I->setDebugLoc(LastLoc);
5244 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5246 return error(
"Invalid unary operator record");
5250 return error(
"Invalid unary operator record");
5254 if (OpNum <
Record.size()) {
5258 I->setFastMathFlags(FMF);
5267 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5271 return error(
"Invalid binary operator record");
5275 return error(
"Invalid binary operator record");
5279 if (OpNum <
Record.size()) {
5280 if (
Opc == Instruction::Add ||
5281 Opc == Instruction::Sub ||
5282 Opc == Instruction::Mul ||
5283 Opc == Instruction::Shl) {
5288 }
else if (
Opc == Instruction::SDiv ||
5289 Opc == Instruction::UDiv ||
5290 Opc == Instruction::LShr ||
5291 Opc == Instruction::AShr) {
5294 }
else if (
Opc == Instruction::Or) {
5300 I->setFastMathFlags(FMF);
5309 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5310 OpNum + 1 >
Record.size())
5311 return error(
"Invalid cast record");
5313 ResTypeID =
Record[OpNum++];
5314 Type *ResTy = getTypeByID(ResTypeID);
5317 if (
Opc == -1 || !ResTy)
5318 return error(
"Invalid cast record");
5323 assert(CurBB &&
"No current BB?");
5329 return error(
"Invalid cast");
5333 if (OpNum <
Record.size()) {
5334 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5337 }
else if (
Opc == Instruction::Trunc) {
5346 I->setFastMathFlags(FMF);
5365 Ty = getTypeByID(TyID);
5369 TyID = InvalidTypeID;
5374 unsigned BasePtrTypeID;
5375 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5377 return error(
"Invalid gep record");
5380 TyID = getContainedTypeID(BasePtrTypeID);
5381 if (
BasePtr->getType()->isVectorTy())
5382 TyID = getContainedTypeID(TyID);
5383 Ty = getTypeByID(TyID);
5386 SmallVector<Value*, 16> GEPIdx;
5387 while (OpNum !=
Record.size()) {
5390 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5391 return error(
"Invalid gep record");
5402 unsigned SubType = 0;
5403 if (GTI.isStruct()) {
5405 Idx->getType()->isVectorTy()
5407 :
cast<ConstantInt>(Idx);
5410 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5417 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5418 if (
I->getType()->isVectorTy())
5419 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5422 GEP->setNoWrapFlags(NW);
5431 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5432 return error(
"Invalid extractvalue record");
5435 unsigned RecSize =
Record.size();
5436 if (OpNum == RecSize)
5437 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5439 SmallVector<unsigned, 4> EXTRACTVALIdx;
5440 ResTypeID = AggTypeID;
5441 for (; OpNum != RecSize; ++OpNum) {
5446 if (!IsStruct && !IsArray)
5447 return error(
"EXTRACTVAL: Invalid type");
5448 if ((
unsigned)Index != Index)
5449 return error(
"Invalid value");
5451 return error(
"EXTRACTVAL: Invalid struct index");
5453 return error(
"EXTRACTVAL: Invalid array index");
5454 EXTRACTVALIdx.
push_back((
unsigned)Index);
5458 ResTypeID = getContainedTypeID(ResTypeID, Index);
5461 ResTypeID = getContainedTypeID(ResTypeID);
5475 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5476 return error(
"Invalid insertvalue record");
5479 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5480 return error(
"Invalid insertvalue record");
5482 unsigned RecSize =
Record.size();
5483 if (OpNum == RecSize)
5484 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5486 SmallVector<unsigned, 4> INSERTVALIdx;
5488 for (; OpNum != RecSize; ++OpNum) {
5493 if (!IsStruct && !IsArray)
5494 return error(
"INSERTVAL: Invalid type");
5495 if ((
unsigned)Index != Index)
5496 return error(
"Invalid value");
5498 return error(
"INSERTVAL: Invalid struct index");
5500 return error(
"INSERTVAL: Invalid array index");
5502 INSERTVALIdx.
push_back((
unsigned)Index);
5510 return error(
"Inserted value type doesn't match aggregate type");
5513 ResTypeID = AggTypeID;
5525 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5527 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5529 popValue(Record, OpNum, NextValueNo, CondType,
5530 getVirtualTypeID(CondType),
Cond, CurBB))
5531 return error(
"Invalid select record");
5544 unsigned ValTypeID, CondTypeID;
5545 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5547 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5549 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5550 return error(
"Invalid vector select record");
5553 if (VectorType* vector_type =
5556 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5557 return error(
"Invalid type for value");
5561 return error(
"Invalid type for value");
5565 ResTypeID = ValTypeID;
5570 I->setFastMathFlags(FMF);
5578 unsigned VecTypeID, IdxTypeID;
5579 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5580 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5581 return error(
"Invalid extractelement record");
5583 return error(
"Invalid type for value");
5585 ResTypeID = getContainedTypeID(VecTypeID);
5592 Value *Vec, *Elt, *Idx;
5593 unsigned VecTypeID, IdxTypeID;
5594 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5595 return error(
"Invalid insertelement record");
5597 return error(
"Invalid type for value");
5598 if (popValue(Record, OpNum, NextValueNo,
5600 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5601 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5602 return error(
"Invalid insert element record");
5604 ResTypeID = VecTypeID;
5612 unsigned Vec1TypeID;
5613 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5615 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5617 return error(
"Invalid shufflevector record");
5619 unsigned MaskTypeID;
5620 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5621 return error(
"Invalid shufflevector record");
5623 return error(
"Invalid type for value");
5625 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5627 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5642 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5643 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5645 return error(
"Invalid comparison record");
5647 if (OpNum >=
Record.size())
5649 "Invalid record: operand number exceeded available operands");
5654 if (IsFP &&
Record.size() > OpNum+1)
5659 return error(
"Invalid fcmp predicate");
5660 I =
new FCmpInst(PredVal,
LHS,
RHS);
5663 return error(
"Invalid icmp predicate");
5664 I =
new ICmpInst(PredVal,
LHS,
RHS);
5665 if (
Record.size() > OpNum + 1 &&
5670 if (OpNum + 1 !=
Record.size())
5671 return error(
"Invalid comparison record");
5673 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5675 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5678 I->setFastMathFlags(FMF);
5695 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5696 return error(
"Invalid ret record");
5697 if (OpNum !=
Record.size())
5698 return error(
"Invalid ret record");
5706 return error(
"Invalid br record");
5707 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5709 return error(
"Invalid br record");
5711 if (
Record.size() == 1) {
5716 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5718 Value *
Cond = getValue(Record, 2, NextValueNo, CondType,
5719 getVirtualTypeID(CondType), CurBB);
5720 if (!FalseDest || !
Cond)
5721 return error(
"Invalid br record");
5729 return error(
"Invalid cleanupret record");
5732 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5733 getVirtualTypeID(TokenTy), CurBB);
5735 return error(
"Invalid cleanupret record");
5737 if (
Record.size() == 2) {
5738 UnwindDest = getBasicBlock(Record[Idx++]);
5740 return error(
"Invalid cleanupret record");
5749 return error(
"Invalid catchret record");
5752 Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5753 getVirtualTypeID(TokenTy), CurBB);
5755 return error(
"Invalid catchret record");
5756 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5758 return error(
"Invalid catchret record");
5767 return error(
"Invalid catchswitch record");
5772 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5773 getVirtualTypeID(TokenTy), CurBB);
5775 return error(
"Invalid catchswitch record");
5777 unsigned NumHandlers =
Record[Idx++];
5780 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5781 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5783 return error(
"Invalid catchswitch record");
5788 if (Idx + 1 ==
Record.size()) {
5789 UnwindDest = getBasicBlock(Record[Idx++]);
5791 return error(
"Invalid catchswitch record");
5794 if (
Record.size() != Idx)
5795 return error(
"Invalid catchswitch record");
5799 for (BasicBlock *Handler : Handlers)
5800 CatchSwitch->addHandler(Handler);
5802 ResTypeID = getVirtualTypeID(
I->getType());
5810 return error(
"Invalid catchpad/cleanuppad record");
5815 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5816 getVirtualTypeID(TokenTy), CurBB);
5818 return error(
"Invalid catchpad/cleanuppad record");
5820 unsigned NumArgOperands =
Record[Idx++];
5822 SmallVector<Value *, 2>
Args;
5823 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5826 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5827 return error(
"Invalid catchpad/cleanuppad record");
5828 Args.push_back(Val);
5831 if (
Record.size() != Idx)
5832 return error(
"Invalid catchpad/cleanuppad record");
5838 ResTypeID = getVirtualTypeID(
I->getType());
5844 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5850 unsigned OpTyID =
Record[1];
5851 Type *OpTy = getTypeByID(OpTyID);
5854 Value *
Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
5857 return error(
"Invalid switch record");
5859 unsigned NumCases =
Record[4];
5864 unsigned CurIdx = 5;
5865 for (
unsigned i = 0; i != NumCases; ++i) {
5867 unsigned NumItems =
Record[CurIdx++];
5868 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5869 bool isSingleNumber =
Record[CurIdx++];
5872 unsigned ActiveWords = 1;
5873 if (ValueBitWidth > 64)
5874 ActiveWords =
Record[CurIdx++];
5877 CurIdx += ActiveWords;
5879 if (!isSingleNumber) {
5881 if (ValueBitWidth > 64)
5882 ActiveWords =
Record[CurIdx++];
5885 CurIdx += ActiveWords;
5896 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5897 for (ConstantInt *Cst : CaseVals)
5898 SI->addCase(Cst, DestBB);
5907 return error(
"Invalid switch record");
5908 unsigned OpTyID =
Record[0];
5909 Type *OpTy = getTypeByID(OpTyID);
5910 Value *
Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5913 return error(
"Invalid switch record");
5914 unsigned NumCases = (
Record.size()-3)/2;
5917 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
5919 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
5920 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5921 if (!CaseVal || !DestBB) {
5923 return error(
"Invalid switch record");
5925 SI->addCase(CaseVal, DestBB);
5932 return error(
"Invalid indirectbr record");
5933 unsigned OpTyID =
Record[0];
5934 Type *OpTy = getTypeByID(OpTyID);
5935 Value *
Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5937 return error(
"Invalid indirectbr record");
5938 unsigned NumDests =
Record.size()-2;
5941 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
5942 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5946 return error(
"Invalid indirectbr record");
5956 return error(
"Invalid invoke record");
5959 unsigned CCInfo =
Record[OpNum++];
5960 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5961 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5963 unsigned FTyID = InvalidTypeID;
5964 FunctionType *FTy =
nullptr;
5965 if ((CCInfo >> 13) & 1) {
5969 return error(
"Explicit invoke type is not a function type");
5973 unsigned CalleeTypeID;
5974 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5976 return error(
"Invalid invoke record");
5980 return error(
"Callee is not a pointer");
5982 FTyID = getContainedTypeID(CalleeTypeID);
5985 return error(
"Callee is not of pointer to function type");
5987 if (
Record.size() < FTy->getNumParams() + OpNum)
5988 return error(
"Insufficient operands to call");
5990 SmallVector<Value*, 16>
Ops;
5991 SmallVector<unsigned, 16> ArgTyIDs;
5992 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5993 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5994 Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5998 return error(
"Invalid invoke record");
6001 if (!FTy->isVarArg()) {
6002 if (
Record.size() != OpNum)
6003 return error(
"Invalid invoke record");
6006 while (OpNum !=
Record.size()) {
6009 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6010 return error(
"Invalid invoke record");
6017 if (!OperandBundles.empty())
6022 ResTypeID = getContainedTypeID(FTyID);
6023 OperandBundles.clear();
6026 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
6037 Value *Val =
nullptr;
6039 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
6040 return error(
"Invalid resume record");
6049 unsigned CCInfo =
Record[OpNum++];
6051 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
6052 unsigned NumIndirectDests =
Record[OpNum++];
6053 SmallVector<BasicBlock *, 16> IndirectDests;
6054 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
6055 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
6057 unsigned FTyID = InvalidTypeID;
6058 FunctionType *FTy =
nullptr;
6063 return error(
"Explicit call type is not a function type");
6067 unsigned CalleeTypeID;
6068 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6070 return error(
"Invalid callbr record");
6074 return error(
"Callee is not a pointer type");
6076 FTyID = getContainedTypeID(CalleeTypeID);
6079 return error(
"Callee is not of pointer to function type");
6081 if (
Record.size() < FTy->getNumParams() + OpNum)
6082 return error(
"Insufficient operands to call");
6084 SmallVector<Value*, 16>
Args;
6085 SmallVector<unsigned, 16> ArgTyIDs;
6087 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6089 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6090 if (FTy->getParamType(i)->isLabelTy())
6091 Arg = getBasicBlock(Record[OpNum]);
6093 Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6096 return error(
"Invalid callbr record");
6097 Args.push_back(Arg);
6102 if (!FTy->isVarArg()) {
6103 if (OpNum !=
Record.size())
6104 return error(
"Invalid callbr record");
6106 while (OpNum !=
Record.size()) {
6109 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6110 return error(
"Invalid callbr record");
6117 if (!OperandBundles.empty())
6122 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6125 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6130 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6131 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6132 unsigned LabelNo = ArgNo - FirstBlockArg;
6134 if (!BA || BA->getFunction() !=
F ||
6135 LabelNo > IndirectDests.
size() ||
6136 BA->getBasicBlock() != IndirectDests[LabelNo])
6137 return error(
"callbr argument does not match indirect dest");
6142 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6146 for (
Value *Arg : Args)
6149 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6152 std::string Constraints =
IA->getConstraintString().str();
6155 for (
const auto &CI : ConstraintInfo) {
6157 if (ArgNo >= FirstBlockArg)
6158 Constraints.insert(Pos,
"!");
6163 Pos = Constraints.find(
',', Pos);
6164 if (Pos == std::string::npos)
6170 IA->hasSideEffects(),
IA->isAlignStack(),
6171 IA->getDialect(),
IA->canThrow());
6177 ResTypeID = getContainedTypeID(FTyID);
6178 OperandBundles.clear();
6195 return error(
"Invalid phi record");
6197 unsigned TyID =
Record[0];
6198 Type *Ty = getTypeByID(TyID);
6200 return error(
"Invalid phi record");
6205 size_t NumArgs = (
Record.size() - 1) / 2;
6209 return error(
"Invalid phi record");
6213 SmallDenseMap<BasicBlock *, Value *>
Args;
6214 for (
unsigned i = 0; i != NumArgs; i++) {
6215 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6218 return error(
"Invalid phi BB");
6225 auto It =
Args.find(BB);
6227 if (It !=
Args.end()) {
6241 if (!PhiConstExprBB)
6243 EdgeBB = PhiConstExprBB;
6251 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6253 V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6257 return error(
"Invalid phi record");
6260 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6261 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6262 PhiConstExprBB =
nullptr;
6265 Args.insert({BB,
V});
6271 if (
Record.size() % 2 == 0) {
6275 I->setFastMathFlags(FMF);
6287 return error(
"Invalid landingpad record");
6291 return error(
"Invalid landingpad record");
6293 ResTypeID =
Record[Idx++];
6294 Type *Ty = getTypeByID(ResTypeID);
6296 return error(
"Invalid landingpad record");
6298 Value *PersFn =
nullptr;
6299 unsigned PersFnTypeID;
6300 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6302 return error(
"Invalid landingpad record");
6304 if (!
F->hasPersonalityFn())
6307 return error(
"Personality function mismatch");
6310 bool IsCleanup = !!
Record[Idx++];
6311 unsigned NumClauses =
Record[Idx++];
6314 for (
unsigned J = 0; J != NumClauses; ++J) {
6320 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6323 return error(
"Invalid landingpad record");
6328 "Catch clause has a invalid type!");
6331 "Filter clause has invalid type!");
6342 return error(
"Invalid alloca record");
6343 using APV = AllocaPackedValues;
6344 const uint64_t Rec =
Record[3];
6347 unsigned TyID =
Record[0];
6348 Type *Ty = getTypeByID(TyID);
6350 TyID = getContainedTypeID(TyID);
6351 Ty = getTypeByID(TyID);
6353 return error(
"Missing element type for old-style alloca");
6355 unsigned OpTyID =
Record[1];
6356 Type *OpTy = getTypeByID(OpTyID);
6357 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6362 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6366 return error(
"Invalid alloca record");
6368 const DataLayout &
DL = TheModule->getDataLayout();
6369 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6371 SmallPtrSet<Type *, 4> Visited;
6372 if (!Align && !Ty->
isSized(&Visited))
6373 return error(
"alloca of unsized type");
6375 Align =
DL.getPrefTypeAlign(Ty);
6377 if (!
Size->getType()->isIntegerTy())
6378 return error(
"alloca element count must have integer type");
6380 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6384 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6392 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6393 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6394 return error(
"Invalid load record");
6397 return error(
"Load operand is not a pointer type");
6400 if (OpNum + 3 ==
Record.size()) {
6401 ResTypeID =
Record[OpNum++];
6402 Ty = getTypeByID(ResTypeID);
6404 ResTypeID = getContainedTypeID(OpTypeID);
6405 Ty = getTypeByID(ResTypeID);
6409 return error(
"Missing load type");
6411 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6415 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6417 SmallPtrSet<Type *, 4> Visited;
6418 if (!Align && !Ty->
isSized(&Visited))
6419 return error(
"load of unsized type");
6421 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6422 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6431 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6432 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size()))
6433 return error(
"Invalid load atomic record");
6436 return error(
"Load operand is not a pointer type");
6439 if (OpNum + 5 ==
Record.size()) {
6440 ResTypeID =
Record[OpNum++];
6441 Ty = getTypeByID(ResTypeID);
6443 ResTypeID = getContainedTypeID(OpTypeID);
6444 Ty = getTypeByID(ResTypeID);
6448 return error(
"Missing atomic load type");
6450 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6454 if (Ordering == AtomicOrdering::NotAtomic ||
6455 Ordering == AtomicOrdering::Release ||
6456 Ordering == AtomicOrdering::AcquireRelease)
6457 return error(
"Invalid load atomic record");
6458 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6459 return error(
"Invalid load atomic record");
6460 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6463 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6466 return error(
"Alignment missing from atomic load");
6467 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align, Ordering, SSID);
6475 unsigned PtrTypeID, ValTypeID;
6476 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6477 return error(
"Invalid store record");
6480 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6481 return error(
"Invalid store record");
6483 ValTypeID = getContainedTypeID(PtrTypeID);
6484 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6485 ValTypeID, Val, CurBB))
6486 return error(
"Invalid store record");
6489 if (OpNum + 2 !=
Record.size())
6490 return error(
"Invalid store record");
6495 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6497 SmallPtrSet<Type *, 4> Visited;
6499 return error(
"store of unsized type");
6501 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6502 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6511 unsigned PtrTypeID, ValTypeID;
6512 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6514 return error(
"Invalid store atomic record");
6516 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6517 return error(
"Invalid store atomic record");
6519 ValTypeID = getContainedTypeID(PtrTypeID);
6520 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6521 ValTypeID, Val, CurBB))
6522 return error(
"Invalid store atomic record");
6525 if (OpNum + 4 !=
Record.size())
6526 return error(
"Invalid store atomic record");
6531 if (Ordering == AtomicOrdering::NotAtomic ||
6532 Ordering == AtomicOrdering::Acquire ||
6533 Ordering == AtomicOrdering::AcquireRelease)
6534 return error(
"Invalid store atomic record");
6535 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6536 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6537 return error(
"Invalid store atomic record");
6540 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6543 return error(
"Alignment missing from atomic store");
6544 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6551 const size_t NumRecords =
Record.size();
6553 Value *Ptr =
nullptr;
6555 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6556 return error(
"Invalid cmpxchg record");
6559 return error(
"Cmpxchg operand is not a pointer type");
6562 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6563 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6564 CmpTypeID, Cmp, CurBB))
6565 return error(
"Invalid cmpxchg record");
6568 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6570 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6571 return error(
"Invalid cmpxchg record");
6575 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6576 SuccessOrdering == AtomicOrdering::Unordered)
6577 return error(
"Invalid cmpxchg record");
6579 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6581 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6589 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6590 FailureOrdering == AtomicOrdering::Unordered)
6591 return error(
"Invalid cmpxchg record");
6593 const Align Alignment(
6594 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6596 I =
new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6597 FailureOrdering, SSID);
6600 if (NumRecords < 8) {
6604 I->insertInto(CurBB, CurBB->
end());
6606 ResTypeID = CmpTypeID;
6609 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6610 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6619 const size_t NumRecords =
Record.size();
6621 Value *Ptr =
nullptr;
6623 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6624 return error(
"Invalid cmpxchg record");
6627 return error(
"Cmpxchg operand is not a pointer type");
6631 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6632 return error(
"Invalid cmpxchg record");
6634 Value *Val =
nullptr;
6635 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6637 return error(
"Invalid cmpxchg record");
6639 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6640 return error(
"Invalid cmpxchg record");
6642 const bool IsVol =
Record[OpNum];
6647 return error(
"Invalid cmpxchg success ordering");
6649 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6651 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6657 return error(
"Invalid cmpxchg failure ordering");
6659 const bool IsWeak =
Record[OpNum + 4];
6661 MaybeAlign Alignment;
6663 if (NumRecords == (OpNum + 6)) {
6664 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6669 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6671 I =
new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6672 FailureOrdering, SSID);
6676 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6677 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6686 const size_t NumRecords =
Record.size();
6689 Value *Ptr =
nullptr;
6691 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6692 return error(
"Invalid atomicrmw record");
6695 return error(
"Invalid atomicrmw record");
6697 Value *Val =
nullptr;
6698 unsigned ValTypeID = InvalidTypeID;
6700 ValTypeID = getContainedTypeID(PtrTypeID);
6701 if (popValue(Record, OpNum, NextValueNo,
6702 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6703 return error(
"Invalid atomicrmw record");
6705 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6706 return error(
"Invalid atomicrmw record");
6709 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6710 return error(
"Invalid atomicrmw record");
6716 return error(
"Invalid atomicrmw record");
6718 const bool IsVol =
Record[OpNum + 1];
6721 if (Ordering == AtomicOrdering::NotAtomic ||
6722 Ordering == AtomicOrdering::Unordered)
6723 return error(
"Invalid atomicrmw record");
6725 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6727 MaybeAlign Alignment;
6729 if (NumRecords == (OpNum + 5)) {
6730 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6736 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6738 I =
new AtomicRMWInst(
Operation, Ptr, Val, *Alignment, Ordering, SSID);
6739 ResTypeID = ValTypeID;
6747 return error(
"Invalid fence record");
6749 if (Ordering == AtomicOrdering::NotAtomic ||
6750 Ordering == AtomicOrdering::Unordered ||
6751 Ordering == AtomicOrdering::Monotonic)
6752 return error(
"Invalid fence record");
6754 I =
new FenceInst(
Context, Ordering, SSID);
6761 SeenDebugRecord =
true;
6764 return error(
"Invalid dbg record: missing instruction");
6767 Inst->
getParent()->insertDbgRecordBefore(
6778 SeenDebugRecord =
true;
6781 return error(
"Invalid dbg record: missing instruction");
6798 DILocalVariable *Var =
6800 DIExpression *Expr =
6813 unsigned SlotBefore =
Slot;
6814 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6815 return error(
"Invalid dbg record: invalid value");
6817 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6820 RawLocation = getFnMetadataByID(Record[Slot++]);
6823 DbgVariableRecord *DVR =
nullptr;
6827 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6828 DbgVariableRecord::LocationType::Value);
6831 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6832 DbgVariableRecord::LocationType::Declare);
6835 DVR =
new DbgVariableRecord(
6836 RawLocation, Var, Expr, DIL,
6837 DbgVariableRecord::LocationType::DeclareValue);
6841 DIExpression *AddrExpr =
6843 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6844 DVR =
new DbgVariableRecord(RawLocation, Var, Expr,
ID, Addr, AddrExpr,
6857 return error(
"Invalid call record");
6861 unsigned CCInfo =
Record[OpNum++];
6867 return error(
"Fast math flags indicator set for call with no FMF");
6870 unsigned FTyID = InvalidTypeID;
6871 FunctionType *FTy =
nullptr;
6876 return error(
"Explicit call type is not a function type");
6880 unsigned CalleeTypeID;
6881 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6883 return error(
"Invalid call record");
6887 return error(
"Callee is not a pointer type");
6889 FTyID = getContainedTypeID(CalleeTypeID);
6892 return error(
"Callee is not of pointer to function type");
6894 if (
Record.size() < FTy->getNumParams() + OpNum)
6895 return error(
"Insufficient operands to call");
6897 SmallVector<Value*, 16>
Args;
6898 SmallVector<unsigned, 16> ArgTyIDs;
6900 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6901 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6902 if (FTy->getParamType(i)->isLabelTy())
6903 Args.push_back(getBasicBlock(Record[OpNum]));
6905 Args.push_back(getValue(Record, OpNum, NextValueNo,
6906 FTy->getParamType(i), ArgTyID, CurBB));
6909 return error(
"Invalid call record");
6913 if (!FTy->isVarArg()) {
6914 if (OpNum !=
Record.size())
6915 return error(
"Invalid call record");
6917 while (OpNum !=
Record.size()) {
6920 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6921 return error(
"Invalid call record");
6928 if (!OperandBundles.empty())
6932 ResTypeID = getContainedTypeID(FTyID);
6933 OperandBundles.clear();
6947 SeenDebugIntrinsic =
true;
6954 return error(
"Fast-math-flags specified for call without "
6955 "floating-point scalar or vector return type");
6956 I->setFastMathFlags(FMF);
6962 return error(
"Invalid va_arg record");
6963 unsigned OpTyID =
Record[0];
6964 Type *OpTy = getTypeByID(OpTyID);
6965 Value *
Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6967 Type *ResTy = getTypeByID(ResTypeID);
6968 if (!OpTy || !
Op || !ResTy)
6969 return error(
"Invalid va_arg record");
6970 I =
new VAArgInst(
Op, ResTy);
6980 if (
Record.empty() || Record[0] >= BundleTags.size())
6981 return error(
"Invalid operand bundle record");
6983 std::vector<Value *> Inputs;
6986 while (OpNum !=
Record.size()) {
6988 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
6989 return error(
"Invalid operand bundle record");
6990 Inputs.push_back(
Op);
6993 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
7001 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
7002 return error(
"Invalid freeze record");
7003 if (OpNum !=
Record.size())
7004 return error(
"Invalid freeze record");
7006 I =
new FreezeInst(
Op);
7007 ResTypeID = OpTypeID;
7017 return error(
"Invalid instruction with no BB");
7019 if (!OperandBundles.empty()) {
7021 return error(
"Operand bundles found with no consumer");
7023 I->insertInto(CurBB, CurBB->
end());
7026 if (
I->isTerminator()) {
7028 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
7032 if (!
I->getType()->isVoidTy()) {
7033 assert(
I->getType() == getTypeByID(ResTypeID) &&
7034 "Incorrect result type ID");
7042 if (!OperandBundles.empty())
7043 return error(
"Operand bundles found with no consumer");
7047 if (!
A->getParent()) {
7049 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
7055 return error(
"Never resolved value found in function");
7060 if (MDLoader->hasFwdRefs())
7061 return error(
"Invalid function metadata: outgoing forward refs");
7066 for (
const auto &Pair : ConstExprEdgeBBs) {
7077 ValueList.
shrinkTo(ModuleValueListSize);
7078 MDLoader->shrinkTo(ModuleMDLoaderSize);
7079 std::vector<BasicBlock*>().swap(FunctionBBs);
7084Error BitcodeReader::findFunctionInStream(
7086 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7087 while (DeferredFunctionInfoIterator->second == 0) {
7092 assert(VSTOffset == 0 || !
F->hasName());
7095 if (
Error Err = rememberAndSkipFunctionBodies())
7101SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
7104 if (Val >= SSIDs.
size())
7113Error BitcodeReader::materialize(GlobalValue *GV) {
7116 if (!
F || !
F->isMaterializable())
7119 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.
find(
F);
7120 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
7123 if (DFII->second == 0)
7124 if (
Error Err = findFunctionInStream(
F, DFII))
7128 if (
Error Err = materializeMetadata())
7135 if (
Error Err = parseFunctionBody(
F))
7137 F->setIsMaterializable(
false);
7141 if (SeenDebugIntrinsic && SeenDebugRecord)
7142 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7148 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7149 F->setSubprogram(SP);
7152 if (!MDLoader->isStrippingTBAA()) {
7154 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7157 MDLoader->setStripTBAA(
true);
7164 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7165 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7171 unsigned ExpectedNumOperands = 0;
7173 ExpectedNumOperands = 2;
7175 ExpectedNumOperands =
SI->getNumSuccessors();
7177 ExpectedNumOperands = 1;
7181 ExpectedNumOperands = 2;
7188 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7189 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7195 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7196 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7198 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7199 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7200 CI->getArgOperand(ArgNo)->getType(),
7201 CI->getParamAttributes(ArgNo)));
7204 if (Function *OldFn = CI->getCalledFunction()) {
7205 auto It = UpgradedIntrinsics.find(OldFn);
7206 if (It != UpgradedIntrinsics.end())
7217 return materializeForwardReferencedFunctions();
7220Error BitcodeReader::materializeModule() {
7221 if (
Error Err = materializeMetadata())
7225 WillMaterializeAllForwardRefs =
true;
7229 for (Function &
F : *TheModule) {
7230 if (
Error Err = materialize(&
F))
7236 if (LastFunctionBlockBit || NextUnreadBit)
7238 ? LastFunctionBlockBit
7244 if (!BasicBlockFwdRefs.
empty())
7245 return error(
"Never resolved function from blockaddress");
7251 for (
auto &
I : UpgradedIntrinsics) {
7252 for (
auto *U :
I.first->users()) {
7256 if (
I.first !=
I.second) {
7257 if (!
I.first->use_empty())
7258 I.first->replaceAllUsesWith(
I.second);
7259 I.first->eraseFromParent();
7262 UpgradedIntrinsics.clear();
7277std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7278 return IdentifiedStructTypes;
7281ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7282 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7284 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7285 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7287void ModuleSummaryIndexBitcodeReader::addThisModule() {
7292ModuleSummaryIndexBitcodeReader::getThisModule() {
7296template <
bool AllowNullValueInfo>
7297std::pair<ValueInfo, GlobalValue::GUID>
7298ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7299 auto VGI = ValueIdToValueInfoMap[ValueId];
7306 assert(AllowNullValueInfo || std::get<0>(VGI));
7310void ModuleSummaryIndexBitcodeReader::setValueGUID(
7312 StringRef SourceFileName) {
7313 std::string GlobalId =
7316 auto OriginalNameID = ValueGUID;
7320 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7326 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7335Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7337 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7344 if (!MaybeCurrentBit)
7346 uint64_t CurrentBit = MaybeCurrentBit.
get();
7351 SmallVector<uint64_t, 64>
Record;
7360 BitstreamEntry
Entry = MaybeEntry.
get();
7362 switch (
Entry.Kind) {
7365 return error(
"Malformed block");
7381 switch (MaybeRecord.
get()) {
7386 return error(
"Invalid vst_code_entry record");
7387 unsigned ValueID =
Record[0];
7389 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7390 assert(VLI != ValueIdToLinkageMap.
end() &&
7391 "No linkage found for VST entry?");
7400 return error(
"Invalid vst_code_fnentry record");
7401 unsigned ValueID =
Record[0];
7403 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7404 assert(VLI != ValueIdToLinkageMap.
end() &&
7405 "No linkage found for VST entry?");
7413 unsigned ValueID =
Record[0];
7417 ValueIdToValueInfoMap[ValueID] =
7428Error ModuleSummaryIndexBitcodeReader::parseModule() {
7432 SmallVector<uint64_t, 64>
Record;
7433 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7434 unsigned ValueId = 0;
7438 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
7441 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7443 switch (
Entry.Kind) {
7445 return error(
"Malformed block");
7457 if (
Error Err = readBlockInfo())
7463 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7464 !SeenGlobalValSummary) &&
7465 "Expected early VST parse via VSTOffset record");
7472 if (!SourceFileName.
empty())
7474 assert(!SeenValueSymbolTable &&
7475 "Already read VST when parsing summary block?");
7480 if (VSTOffset > 0) {
7481 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7483 SeenValueSymbolTable =
true;
7485 SeenGlobalValSummary =
true;
7486 if (
Error Err = parseEntireSummary(
Entry.ID))
7490 if (
Error Err = parseModuleStringTable())
7498 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7501 switch (MaybeBitCode.
get()) {
7505 if (
Error Err = parseVersionRecord(Record).takeError())
7513 return error(
"Invalid source filename record");
7520 return error(
"Invalid hash length " + Twine(
Record.size()).str());
7521 auto &Hash = getThisModule()->second;
7523 for (
auto &Val : Record) {
7524 assert(!(Val >> 32) &&
"Unexpected high bits set");
7532 return error(
"Invalid vstoffset record");
7536 VSTOffset =
Record[0] - 1;
7546 ArrayRef<uint64_t> GVRecord;
7547 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7548 if (GVRecord.
size() <= 3)
7549 return error(
"Invalid global record");
7550 uint64_t RawLinkage = GVRecord[3];
7553 ValueIdToLinkageMap[ValueId++] =
Linkage;
7557 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7568ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7571 for (uint64_t RefValueId : Record)
7572 Ret.
push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7577ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7578 bool IsOldProfileFormat,
7579 bool HasProfile,
bool HasRelBF) {
7583 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7588 for (
unsigned I = 0,
E =
Record.size();
I !=
E; ++
I) {
7590 bool HasTailCall =
false;
7592 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7593 if (IsOldProfileFormat) {
7597 }
else if (HasProfile)
7598 std::tie(Hotness, HasTailCall) =
7632 static_cast<size_t>(
Record[Slot + 1])};
7655 while (Slot <
Record.size())
7659std::vector<FunctionSummary::ParamAccess>
7660ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7661 auto ReadRange = [&]() {
7663 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7665 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7672 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7673 while (!
Record.empty()) {
7674 PendingParamAccesses.emplace_back();
7675 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7677 ParamAccess.
Use = ReadRange();
7682 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7683 Call.Offsets = ReadRange();
7686 return PendingParamAccesses;
7689void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7690 ArrayRef<uint64_t> Record,
size_t &Slot,
7693 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7697void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7698 ArrayRef<uint64_t> Record) {
7706 while (Slot <
Record.size())
7707 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7710SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7711 ArrayRef<uint64_t> Record,
unsigned &
I) {
7712 SmallVector<unsigned> StackIdList;
7716 if (RadixArray.empty()) {
7717 unsigned NumStackEntries =
Record[
I++];
7719 StackIdList.
reserve(NumStackEntries);
7720 for (
unsigned J = 0; J < NumStackEntries; J++) {
7721 assert(Record[
I] < StackIds.size());
7722 StackIdList.
push_back(getStackIdIndex(Record[
I++]));
7725 unsigned RadixIndex =
Record[
I++];
7731 assert(RadixIndex < RadixArray.size());
7732 unsigned NumStackIds = RadixArray[RadixIndex++];
7733 StackIdList.
reserve(NumStackIds);
7734 while (NumStackIds--) {
7735 assert(RadixIndex < RadixArray.size());
7736 unsigned Elem = RadixArray[RadixIndex];
7737 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7738 RadixIndex = RadixIndex - Elem;
7739 assert(RadixIndex < RadixArray.size());
7740 Elem = RadixArray[RadixIndex];
7742 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7745 StackIdList.
push_back(getStackIdIndex(Elem));
7755 unsigned FirstWORef = Refs.
size() - WOCnt;
7756 unsigned RefNo = FirstWORef - ROCnt;
7757 for (; RefNo < FirstWORef; ++RefNo)
7758 Refs[RefNo].setReadOnly();
7759 for (; RefNo < Refs.
size(); ++RefNo)
7760 Refs[RefNo].setWriteOnly();
7765Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7768 SmallVector<uint64_t, 64>
Record;
7775 BitstreamEntry
Entry = MaybeEntry.
get();
7778 return error(
"Invalid Summary Block: record for version expected");
7783 return error(
"Invalid Summary Block: version expected");
7786 const bool IsOldProfileFormat =
Version == 1;
7789 const bool MemProfAfterFunctionSummary =
Version >= 13;
7791 return error(
"Invalid summary version " + Twine(
Version) +
7792 ". Version should be in the range [1-" +
7799 GlobalValueSummary *LastSeenSummary =
nullptr;
7809 FunctionSummary *CurrentPrevailingFS =
nullptr;
7814 std::vector<GlobalValue::GUID> PendingTypeTests;
7815 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7816 PendingTypeCheckedLoadVCalls;
7817 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7818 PendingTypeCheckedLoadConstVCalls;
7819 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7821 std::vector<CallsiteInfo> PendingCallsites;
7822 std::vector<AllocInfo> PendingAllocs;
7823 std::vector<uint64_t> PendingContextIds;
7829 BitstreamEntry
Entry = MaybeEntry.
get();
7831 switch (
Entry.Kind) {
7834 return error(
"Malformed block");
7850 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7853 unsigned BitCode = MaybeBitCode.
get();
7863 uint64_t ValueID =
Record[0];
7870 ValueIdToValueInfoMap[ValueID] =
7888 unsigned ValueID =
Record[0];
7889 uint64_t RawFlags =
Record[1];
7890 unsigned InstCount =
Record[2];
7891 uint64_t RawFunFlags = 0;
7892 unsigned NumRefs =
Record[3];
7893 unsigned NumRORefs = 0, NumWORefs = 0;
7894 int RefListStartIndex = 4;
7898 RefListStartIndex = 5;
7901 RefListStartIndex = 6;
7904 RefListStartIndex = 7;
7915 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7917 "Record size inconsistent with number of references");
7919 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7924 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7925 IsOldProfileFormat, HasProfile, HasRelBF);
7927 auto [
VI,
GUID] = getValueInfoFromValueId(ValueID);
7934 IsPrevailing(
VI.getGUID());
7940 assert(!MemProfAfterFunctionSummary ||
7941 (PendingCallsites.empty() && PendingAllocs.empty()));
7942 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
7943 PendingCallsites.clear();
7944 PendingAllocs.clear();
7947 auto FS = std::make_unique<FunctionSummary>(
7949 std::move(Calls), std::move(PendingTypeTests),
7950 std::move(PendingTypeTestAssumeVCalls),
7951 std::move(PendingTypeCheckedLoadVCalls),
7952 std::move(PendingTypeTestAssumeConstVCalls),
7953 std::move(PendingTypeCheckedLoadConstVCalls),
7954 std::move(PendingParamAccesses), std::move(PendingCallsites),
7955 std::move(PendingAllocs));
7956 FS->setModulePath(getThisModule()->first());
7957 FS->setOriginalName(GUID);
7960 if (MemProfAfterFunctionSummary) {
7961 if (IsPrevailingSym)
7962 CurrentPrevailingFS =
FS.get();
7964 CurrentPrevailingFS =
nullptr;
7973 unsigned ValueID =
Record[0];
7974 uint64_t RawFlags =
Record[1];
7975 unsigned AliaseeID =
Record[2];
7977 auto AS = std::make_unique<AliasSummary>(Flags);
7983 AS->setModulePath(getThisModule()->first());
7985 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7987 if (!AliaseeInModule)
7988 return error(
"Alias expects aliasee summary to be parsed");
7989 AS->setAliasee(AliaseeVI, AliaseeInModule);
7991 auto GUID = getValueInfoFromValueId(ValueID);
7992 AS->setOriginalName(std::get<1>(GUID));
7998 unsigned ValueID =
Record[0];
7999 uint64_t RawFlags =
Record[1];
8000 unsigned RefArrayStart = 2;
8001 GlobalVarSummary::GVarFlags GVF(
false,
8011 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8013 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8014 FS->setModulePath(getThisModule()->first());
8015 auto GUID = getValueInfoFromValueId(ValueID);
8016 FS->setOriginalName(std::get<1>(GUID));
8024 unsigned ValueID =
Record[0];
8025 uint64_t RawFlags =
Record[1];
8027 unsigned NumRefs =
Record[3];
8028 unsigned RefListStartIndex = 4;
8029 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
8032 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8034 for (
unsigned I = VTableListStartIndex,
E =
Record.size();
I !=
E; ++
I) {
8035 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
8040 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8041 VS->setModulePath(getThisModule()->first());
8042 VS->setVTableFuncs(VTableFuncs);
8043 auto GUID = getValueInfoFromValueId(ValueID);
8044 VS->setOriginalName(std::get<1>(GUID));
8056 unsigned ValueID =
Record[0];
8057 uint64_t ModuleId =
Record[1];
8058 uint64_t RawFlags =
Record[2];
8059 unsigned InstCount =
Record[3];
8060 uint64_t RawFunFlags = 0;
8061 unsigned NumRefs =
Record[4];
8062 unsigned NumRORefs = 0, NumWORefs = 0;
8063 int RefListStartIndex = 5;
8067 RefListStartIndex = 6;
8068 size_t NumRefsIndex = 5;
8070 unsigned NumRORefsOffset = 1;
8071 RefListStartIndex = 7;
8074 RefListStartIndex = 8;
8076 RefListStartIndex = 9;
8078 NumRORefsOffset = 2;
8081 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
8083 NumRefs =
Record[NumRefsIndex];
8087 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8089 "Record size inconsistent with number of references");
8091 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8094 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8095 IsOldProfileFormat, HasProfile,
false);
8096 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8098 auto FS = std::make_unique<FunctionSummary>(
8100 std::move(Edges), std::move(PendingTypeTests),
8101 std::move(PendingTypeTestAssumeVCalls),
8102 std::move(PendingTypeCheckedLoadVCalls),
8103 std::move(PendingTypeTestAssumeConstVCalls),
8104 std::move(PendingTypeCheckedLoadConstVCalls),
8105 std::move(PendingParamAccesses), std::move(PendingCallsites),
8106 std::move(PendingAllocs));
8107 LastSeenSummary =
FS.get();
8108 if (MemProfAfterFunctionSummary)
8109 CurrentPrevailingFS =
FS.get();
8110 LastSeenGUID =
VI.getGUID();
8111 FS->setModulePath(ModuleIdMap[ModuleId]);
8119 unsigned ValueID =
Record[0];
8120 uint64_t ModuleId =
Record[1];
8121 uint64_t RawFlags =
Record[2];
8122 unsigned AliaseeValueId =
Record[3];
8124 auto AS = std::make_unique<AliasSummary>(Flags);
8125 LastSeenSummary = AS.get();
8126 AS->setModulePath(ModuleIdMap[ModuleId]);
8128 auto AliaseeVI = std::get<0>(
8129 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8131 auto AliaseeInModule =
8133 AS->setAliasee(AliaseeVI, AliaseeInModule);
8135 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8136 LastSeenGUID =
VI.getGUID();
8142 unsigned ValueID =
Record[0];
8143 uint64_t ModuleId =
Record[1];
8144 uint64_t RawFlags =
Record[2];
8145 unsigned RefArrayStart = 3;
8146 GlobalVarSummary::GVarFlags GVF(
false,
8156 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8158 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8159 LastSeenSummary =
FS.get();
8160 FS->setModulePath(ModuleIdMap[ModuleId]);
8161 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8162 LastSeenGUID =
VI.getGUID();
8168 uint64_t OriginalName =
Record[0];
8169 if (!LastSeenSummary)
8170 return error(
"Name attachment that does not follow a combined record");
8174 LastSeenSummary =
nullptr;
8179 assert(PendingTypeTests.empty());
8184 assert(PendingTypeTestAssumeVCalls.empty());
8185 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8186 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8190 assert(PendingTypeCheckedLoadVCalls.empty());
8191 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8192 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8196 PendingTypeTestAssumeConstVCalls.push_back(
8201 PendingTypeCheckedLoadConstVCalls.push_back(
8207 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8209 static_cast<size_t>(Record[
I + 1]));
8215 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8217 static_cast<size_t>(Record[
I + 1]));
8226 parseTypeIdCompatibleVtableSummaryRecord(Record);
8234 PendingParamAccesses = parseParamAccesses(Record);
8241 assert(StackIds.empty());
8243 StackIds = ArrayRef<uint64_t>(Record);
8249 StackIds.reserve(
Record.size() / 2);
8250 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8251 StackIds.push_back(*R << 32 | *(R + 1));
8253 assert(StackIdToIndex.empty());
8255 StackIdToIndex.resize(StackIds.size(), UninitializedStackIdIndex);
8260 RadixArray = ArrayRef<uint64_t>(Record);
8267 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8269 unsigned ValueID =
Record[0];
8270 SmallVector<unsigned> StackIdList;
8272 assert(R < StackIds.size());
8273 StackIdList.
push_back(getStackIdIndex(R));
8275 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8276 if (MemProfAfterFunctionSummary)
8278 CallsiteInfo({
VI, std::move(StackIdList)}));
8280 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8287 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8288 auto RecordIter =
Record.begin();
8289 unsigned ValueID = *RecordIter++;
8290 unsigned NumStackIds = *RecordIter++;
8291 unsigned NumVersions = *RecordIter++;
8292 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8293 SmallVector<unsigned> StackIdList;
8294 for (
unsigned J = 0; J < NumStackIds; J++) {
8295 assert(*RecordIter < StackIds.size());
8296 StackIdList.
push_back(getStackIdIndex(*RecordIter++));
8298 SmallVector<unsigned> Versions;
8299 for (
unsigned J = 0; J < NumVersions; J++)
8301 ValueInfo
VI = std::get<0>(
8302 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8303 if (MemProfAfterFunctionSummary)
8305 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8307 PendingCallsites.push_back(
8308 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8315 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8320 PendingContextIds.reserve(
Record.size() / 2);
8321 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8322 PendingContextIds.push_back(*R << 32 | *(R + 1));
8329 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8330 PendingContextIds.clear();
8334 std::vector<MIBInfo> MIBs;
8335 unsigned NumMIBs = 0;
8338 unsigned MIBsRead = 0;
8339 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8343 auto StackIdList = parseAllocInfoContext(Record,
I);
8344 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8350 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8352 assert(!PendingContextIds.empty() &&
8353 "Missing context ids for alloc sizes");
8354 unsigned ContextIdIndex = 0;
8360 while (MIBsRead++ < NumMIBs) {
8362 unsigned NumContextSizeInfoEntries =
Record[
I++];
8364 std::vector<ContextTotalSize> ContextSizes;
8365 ContextSizes.reserve(NumContextSizeInfoEntries);
8366 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8367 assert(ContextIdIndex < PendingContextIds.size());
8369 if (PendingContextIds[ContextIdIndex] == 0) {
8378 ContextSizes.push_back(
8379 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8381 AllContextSizes.push_back(std::move(ContextSizes));
8383 PendingContextIds.clear();
8385 AllocInfo AI(std::move(MIBs));
8386 if (!AllContextSizes.empty()) {
8387 assert(AI.MIBs.size() == AllContextSizes.size());
8388 AI.ContextSizeInfos = std::move(AllContextSizes);
8391 if (MemProfAfterFunctionSummary)
8392 CurrentPrevailingFS->
addAlloc(std::move(AI));
8394 PendingAllocs.push_back(std::move(AI));
8402 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8404 std::vector<MIBInfo> MIBs;
8405 unsigned NumMIBs =
Record[
I++];
8406 unsigned NumVersions =
Record[
I++];
8407 unsigned MIBsRead = 0;
8408 while (MIBsRead++ < NumMIBs) {
8411 SmallVector<unsigned> StackIdList;
8413 StackIdList = parseAllocInfoContext(Record,
I);
8414 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8417 SmallVector<uint8_t> Versions;
8418 for (
unsigned J = 0; J < NumVersions; J++)
8421 AllocInfo AI(std::move(Versions), std::move(MIBs));
8422 if (MemProfAfterFunctionSummary)
8423 CurrentPrevailingFS->
addAlloc(std::move(AI));
8425 PendingAllocs.push_back(std::move(AI));
8435Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8439 SmallVector<uint64_t, 64>
Record;
8441 SmallString<128> ModulePath;
8448 BitstreamEntry
Entry = MaybeEntry.
get();
8450 switch (
Entry.Kind) {
8453 return error(
"Malformed block");
8465 switch (MaybeRecord.
get()) {
8470 uint64_t ModuleId =
Record[0];
8473 return error(
"Invalid code_entry record");
8475 LastSeenModule = TheIndex.
addModule(ModulePath);
8476 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8484 return error(
"Invalid hash length " + Twine(
Record.size()).str());
8485 if (!LastSeenModule)
8486 return error(
"Invalid hash that does not follow a module path");
8488 for (
auto &Val : Record) {
8489 assert(!(Val >> 32) &&
"Unexpected high bits set");
8490 LastSeenModule->
second[Pos++] = Val;
8493 LastSeenModule =
nullptr;
8506class BitcodeErrorCategoryType :
public std::error_category {
8507 const char *
name()
const noexcept
override {
8508 return "llvm.bitcode";
8511 std::string message(
int IE)
const override {
8514 case BitcodeError::CorruptedBitcode:
8515 return "Corrupted bitcode";
8524 static BitcodeErrorCategoryType ErrorCategory;
8525 return ErrorCategory;
8529 unsigned Block,
unsigned RecordID) {
8531 return std::move(Err);
8540 switch (Entry.Kind) {
8545 return error(
"Malformed block");
8549 return std::move(Err);
8559 if (MaybeRecord.
get() == RecordID)
8570Expected<std::vector<BitcodeModule>>
8574 return FOrErr.takeError();
8575 return std::move(FOrErr->Mods);
8600 switch (Entry.Kind) {
8603 return error(
"Malformed block");
8606 uint64_t IdentificationBit = -1ull;
8610 return std::move(Err);
8616 Entry = MaybeEntry.
get();
8621 return error(
"Malformed block");
8627 return std::move(Err);
8646 if (!
I.Strtab.empty())
8653 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8654 F.StrtabForSymtab = *Strtab;
8670 if (
F.Symtab.empty())
8671 F.Symtab = *SymtabOrErr;
8676 return std::move(Err);
8681 return std::move(E);
8696BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8697 bool ShouldLazyLoadMetadata,
bool IsImporting,
8701 std::string ProducerIdentification;
8702 if (IdentificationBit != -1ull) {
8704 return std::move(JumpFailed);
8707 return std::move(
E);
8711 return std::move(JumpFailed);
8712 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8715 std::unique_ptr<Module>
M =
8716 std::make_unique<Module>(ModuleIdentifier,
Context);
8717 M->setMaterializer(R);
8720 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8721 IsImporting, Callbacks))
8722 return std::move(Err);
8724 if (MaterializeAll) {
8726 if (
Error Err =
M->materializeAll())
8727 return std::move(Err);
8730 if (
Error Err =
R->materializeForwardReferencedFunctions())
8731 return std::move(Err);
8734 return std::move(M);
8737Expected<std::unique_ptr<Module>>
8740 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8755 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8756 ModulePath, IsPrevailing);
8757 return R.parseModule();
8764 return std::move(JumpFailed);
8766 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8767 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8768 ModuleIdentifier, 0);
8770 if (
Error Err = R.parseModule())
8771 return std::move(Err);
8773 return std::move(Index);
8779 return std::move(Err);
8785 return std::move(
E);
8787 switch (Entry.Kind) {
8790 return error(
"Malformed block");
8793 return std::make_pair(
false,
false);
8805 switch (MaybeBitCode.
get()) {
8811 assert(Flags <= 0x7ff &&
"Unexpected bits in flag");
8813 bool EnableSplitLTOUnit = Flags & 0x8;
8814 bool UnifiedLTO = Flags & 0x200;
8815 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8826 return std::move(JumpFailed);
8829 return std::move(Err);
8834 return std::move(E);
8836 switch (Entry.Kind) {
8838 return error(
"Malformed block");
8849 return Flags.takeError();
8859 return std::move(Err);
8866 return StreamFailed.takeError();
8876 if (MsOrErr->size() != 1)
8877 return error(
"Expected a single module");
8879 return (*MsOrErr)[0];
8882Expected<std::unique_ptr<Module>>
8884 bool ShouldLazyLoadMetadata,
bool IsImporting,
8890 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8895 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
8896 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
8898 IsImporting, Callbacks);
8900 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8906 return getModuleImpl(Context,
true,
false,
false, Callbacks);
8918 return BM->parseModule(Context, Callbacks);
8951 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8960 return BM->getSummary();
8968 return BM->getLTOInfo();
8973 bool IgnoreEmptyThinLTOIndexFile) {
8978 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF, bool &HasTailCall)
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
static cl::opt< bool > PrintSummaryGUIDs("print-summary-global-ids", cl::init(false), cl::Hidden, cl::desc("Print the global id for each value when reading the module summary"))
static AtomicOrdering getDecodedOrdering(unsigned Val)
static std::pair< CalleeInfo::HotnessType, bool > getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)
static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags)
static std::optional< CodeModel::Model > getDecodedCodeModel(unsigned Val)
static void setSpecialRefs(SmallVectorImpl< ValueInfo > &Refs, unsigned ROCnt, unsigned WOCnt)
static bool getDecodedDSOLocal(unsigned Val)
static bool convertToString(ArrayRef< uint64_t > Record, unsigned Idx, StrTy &Result)
Convert a string from a record into an std::string, return true on failure.
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
static void stripTBAA(Module *M)
static int getDecodedUnaryOpcode(unsigned Val, Type *Ty)
static Expected< std::string > readTriple(BitstreamCursor &Stream)
static void parseWholeProgramDevirtResolutionByArg(ArrayRef< uint64_t > Record, size_t &Slot, WholeProgramDevirtResolution &Wpd)
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags)
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
static Expected< uint64_t > jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
static Expected< bool > hasObjCCategoryInModule(BitstreamCursor &Stream)
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags)
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs, uint64_t AttrIdx)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
static bool hasImplicitComdat(size_t Val)
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream)
static Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
static void parseWholeProgramDevirtResolution(ArrayRef< uint64_t > Record, StringRef Strtab, size_t &Slot, TypeIdSummary &TypeId)
static void inferDSOLocal(GlobalValue *GV)
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V)
static Expected< BitstreamCursor > initStream(MemoryBufferRef Buffer)
static cl::opt< bool > ExpandConstantExprs("expand-constant-exprs", cl::Hidden, cl::desc("Expand constant expressions to instructions for testing purposes"))
static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind)
static Expected< StringRef > readBlobInRecord(BitstreamCursor &Stream, unsigned Block, unsigned RecordID)
static Expected< std::string > readIdentificationBlock(BitstreamCursor &Stream)
Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the "epoch" encoded in the bit...
static Expected< std::pair< bool, bool > > getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, unsigned ID)
static bool isConstExprSupported(const BitcodeConstant *BC)
static int getDecodedCastOpcode(unsigned Val)
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase)
This file defines the DenseMap class.
Provides ErrorOr<T> smart pointer.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Machine Check Debug Module
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
PowerPC Reduce CR logical Operation
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallString class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Class for arbitrary precision integers.
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
PointerType * getType() const
Overload to return most specific pointer type.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
static bool isValidFailureOrdering(AtomicOrdering Ordering)
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
static bool isTypeAttrKind(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
@ None
No attributes have been set.
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
@ EndAttrKinds
Sentinel value useful for loops.
LLVM Basic Block Representation.
const Instruction & back() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Represents a module in a bitcode file.
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(GlobalValue::GUID)> IsPrevailing=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
void push_back(Value *V, unsigned TypeID)
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
void shrinkTo(unsigned N)
unsigned getTypeID(unsigned ValNo) const
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
ArrayRef< uint8_t > getBitcodeBytes() const
Expected< word_t > Read(unsigned NumBits)
Expected< BitstreamEntry > advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Expected< BitstreamEntry > advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
Error SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block.
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
uint64_t getCurrentByteNo() const
LLVM_ABI Expected< std::optional< BitstreamBlockInfo > > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
unsigned getAbbrevIDWidth() const
Return the number of bits used to encode an abbrev #.
bool canSkipToPos(size_t pos) const
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
@ MIN_BYTE_BITS
Minimum number of bits that can be specified.
@ MAX_BYTE_BITS
Maximum number of bits that can be specified Note that bit width is stored in the Type classes Subcla...
static LLVM_ABI ByteType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing a ByteType.
bool isInlineAsm() const
Check if this call is an inline asm statement.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo createFromIntValue(uint32_t Data)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void emplace(Args &&...A)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
bool isFPPredicate() const
bool isIntPredicate() const
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of array type with a float element type taken from argument ...
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getByte(Type *ElementType, ArrayRef< uint8_t > Elts)
getByte() constructors - Return a constant of array type with a byte element type taken from argument...
static LLVM_ABI Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of vector type with a float element type taken from argument...
static LLVM_ABI Constant * getByte(Type *ElementType, ArrayRef< uint8_t > Elts)
getByte() constructors - Return a constant of vector type with a byte element type taken from argumen...
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static LLVM_ABI bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
LLVM_ABI bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static DeadOnReturnInfo createFromIntValue(uint64_t Data)
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Base class for error info classes.
virtual std::string message() const
Return the error message as a string.
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
Convenience struct for specifying and reasoning about fast-math flags.
void setFast(bool B=true)
void setAllowContract(bool B=true)
void setAllowReciprocal(bool B=true)
void setNoSignedZeros(bool B=true)
void setNoNaNs(bool B=true)
void setAllowReassoc(bool B=true)
Flag setters.
void setApproxFunc(bool B=true)
void setNoInfs(bool B=true)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
void addCallsite(CallsiteInfo &&Callsite)
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
void addAlloc(AllocInfo &&Alloc)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
BasicBlockListType::iterator iterator
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
bool hasDefaultVisibility() const
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
bool hasExternalWeakLinkage() const
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
LLVM_ABI void setPartition(StringRef Part)
void setAttributes(AttributeSet A)
Set attribute list for this global.
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
std::vector< ConstraintInfo > ConstraintInfoVector
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
const char * getOpcodeName() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
@ MIN_INT_BITS
Minimum number of bits that can be specified.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
LLVM_ABI StringRef getString() const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
ValueT lookup(const KeyT &Key) const
size_t getBufferSize() const
StringRef getBufferIdentifier() const
const char * getBufferStart() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static MemoryEffectsBase readOnly()
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase errnoMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase createFromIntValue(uint32_t Data)
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static constexpr uint64_t BitcodeSummaryVersion
StringRef saveString(StringRef String)
LLVM_ABI void setFlags(uint64_t Flags)
CfiFunctionIndex & cfiFunctionDecls()
void addBlockCount(uint64_t C)
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
CfiFunctionIndex & cfiFunctionDefs()
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
unsigned addOrGetStackIdIndex(uint64_t StackId)
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
constexpr bool empty() const
empty - Check if the string is empty.
constexpr size_t size() const
size - Get the string size.
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
LLVM_ABI void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Triple - Helper class for working with autoconf configuration names.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isByteTy() const
True if this is an instance of ByteType.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
Type * getArrayElementType() const
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isStructTy() const
True if this is an instance of StructType.
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
const ParentTy * getParent() const
self_iterator getIterator()
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
@ BasicBlock
Various leaf nodes.
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
@ System
Synchronized with respect to all concurrently executing threads.
@ TYPE_CODE_OPAQUE_POINTER
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_CE_INBOUNDS_GEP
@ CST_CODE_INLINEASM_OLD3
@ CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_INLINEASM_OLD2
@ CST_CODE_CE_GEP_WITH_INRANGE
@ VST_CODE_COMBINED_ENTRY
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_INACCESSIBLEMEM_ONLY
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ FUNC_CODE_INST_ATOMICRMW_OLD
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_INBOUNDS_GEP_OLD
@ FUNC_CODE_INST_STOREATOMIC_OLD
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_INST_LANDINGPAD_OLD
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_STORE_OLD
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_CMPXCHG_OLD
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ PARAMATTR_CODE_ENTRY_OLD
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
FunctionAddr VTableAddr Value
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
StringMapEntry< Value * > ValueName
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
LLVM_ABI const std::error_category & BitcodeErrorCategory()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI void UpgradeInlineAsmString(std::string *AsmStr)
Upgrade comment in call to inline asm that represents an objc retain release marker.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
std::error_code make_error_code(BitcodeError E)
LLVM_ABI bool stripDebugInfo(Function &F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeAttributes(AttrBuilder &B)
Upgrade attributes that changed format or kind.
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
LLVM_ABI std::unique_ptr< Module > parseModule(const uint8_t *Data, size_t Size, LLVMContext &Context)
Fuzzer friendly interface for the llvm bitcode parser.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto uninitialized_copy(R &&Src, IterTy Dst)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
LLVM_ABI void UpgradeOperandBundles(std::vector< OperandBundleDef > &OperandBundles)
Upgrade operand bundles (without knowing about their user instruction).
LLVM_ABI Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
FunctionAddr VTableAddr uintptr_t uintptr_t Version
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
auto reverse(ContainerTy &&C)
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI std::string UpgradeDataLayoutString(StringRef DL, StringRef Triple)
Upgrade the datalayout string by adding a section for address space pointers.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ ArgMem
Access to memory via argument pointers.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
LLVM_ABI Instruction * UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, Instruction *&Temp)
This is an auto-upgrade for bitcast between pointers with different address spaces: the instruction i...
MaybeAlign decodeMaybeAlign(unsigned Value)
Dual operation of the encode function above.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
LLVM_ABI void UpgradeFunctionAttributes(Function &F)
Correct any IR that is relying on old function attribute behavior.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
LLVM_ABI void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
LLVM_ABI Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
LLVM_ABI std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Basic information extracted from a bitcode module to be used for LTO.
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
static constexpr DenormalFPEnv createFromIntValue(uint32_t Data)
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
ConstantRange Use
The range contains byte offsets from the parameter pointer which accessed by the function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const char * BranchWeights
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
std::optional< DataLayoutCallbackFuncTy > DataLayout
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
Kind
Specifies which kind of type check we should emit for this byte array.
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName