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 = {});
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())
793 unsigned ValID = Record[
Slot++];
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;
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");
881 unsigned BitWidth = Record[OpNum++];
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;
988 ModuleSummaryIndexBitcodeReader(
989 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
990 StringRef ModulePath,
996 void setValueGUID(uint64_t ValueID, StringRef
ValueName,
998 StringRef SourceFileName);
999 Error parseValueSymbolTable(
1001 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1004 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1005 bool HasProfile,
bool HasRelBF);
1006 Error parseEntireSummary(
unsigned ID);
1007 Error parseModuleStringTable();
1008 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1009 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1011 std::vector<FunctionSummary::ParamAccess>
1012 parseParamAccesses(ArrayRef<uint64_t> Record);
1013 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1016 template <
bool AllowNullValueInfo = false>
1017 std::pair<ValueInfo, GlobalValue::GUID>
1018 getValueInfoFromValueId(
unsigned ValueId);
1020 void addThisModule();
1036 return std::error_code();
1042 : BitcodeReaderBase(
std::
move(Stream), Strtab), Context(Context),
1043 ValueList(this->Stream.SizeInBytes(),
1045 return materializeValue(
ValID, InsertBB);
1047 this->ProducerIdentification = std::string(ProducerIdentification);
1050Error BitcodeReader::materializeForwardReferencedFunctions() {
1051 if (WillMaterializeAllForwardRefs)
1055 WillMaterializeAllForwardRefs =
true;
1057 while (!BasicBlockFwdRefQueue.empty()) {
1058 Function *
F = BasicBlockFwdRefQueue.front();
1059 BasicBlockFwdRefQueue.pop_front();
1060 assert(
F &&
"Expected valid function");
1061 if (!BasicBlockFwdRefs.
count(
F))
1069 if (!
F->isMaterializable())
1070 return error(
"Never resolved function from blockaddress");
1073 if (
Error Err = materialize(
F))
1076 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1078 for (Function *
F : BackwardRefFunctions)
1079 if (
Error Err = materialize(
F))
1081 BackwardRefFunctions.clear();
1084 WillMaterializeAllForwardRefs =
false;
1149 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1150 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1151 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1152 Flags.NoInline = (RawFlags >> 4) & 0x1;
1153 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1154 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1155 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1156 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1157 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1173 RawFlags = RawFlags >> 4;
1174 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1178 bool Live = (RawFlags & 0x2) || Version < 3;
1179 bool Local = (RawFlags & 0x4);
1180 bool AutoHide = (RawFlags & 0x8);
1183 Live,
Local, AutoHide, IK);
1189 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1190 (RawFlags & 0x4) ?
true :
false,
1194static std::pair<CalleeInfo::HotnessType, bool>
1198 bool HasTailCall = (RawFlags & 0x8);
1199 return {Hotness, HasTailCall};
1203 bool &HasTailCall) {
1204 static constexpr uint64_t RelBlockFreqMask =
1206 RelBF = RawFlags & RelBlockFreqMask;
1232 case 0:
return false;
1233 case 1:
return true;
1295 bool IsFP = Ty->isFPOrFPVectorTy();
1297 if (!IsFP && !Ty->isIntOrIntVectorTy())
1304 return IsFP ? Instruction::FNeg : -1;
1309 bool IsFP = Ty->isFPOrFPVectorTy();
1311 if (!IsFP && !Ty->isIntOrIntVectorTy())
1318 return IsFP ? Instruction::FAdd : Instruction::Add;
1320 return IsFP ? Instruction::FSub : Instruction::Sub;
1322 return IsFP ? Instruction::FMul : Instruction::Mul;
1324 return IsFP ? -1 : Instruction::UDiv;
1326 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1328 return IsFP ? -1 : Instruction::URem;
1330 return IsFP ? Instruction::FRem : Instruction::SRem;
1332 return IsFP ? -1 : Instruction::Shl;
1334 return IsFP ? -1 : Instruction::LShr;
1336 return IsFP ? -1 : Instruction::AShr;
1338 return IsFP ? -1 : Instruction::And;
1340 return IsFP ? -1 : Instruction::Or;
1342 return IsFP ? -1 : Instruction::Xor;
1439Type *BitcodeReader::getTypeByID(
unsigned ID) {
1441 if (
ID >= TypeList.size())
1444 if (
Type *Ty = TypeList[
ID])
1449 return TypeList[
ID] = createIdentifiedStructType(
Context);
1452unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1453 auto It = ContainedTypeIDs.
find(
ID);
1454 if (It == ContainedTypeIDs.
end())
1455 return InvalidTypeID;
1457 if (Idx >= It->second.size())
1458 return InvalidTypeID;
1460 return It->second[Idx];
1463Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1464 if (
ID >= TypeList.size())
1471 return getTypeByID(getContainedTypeID(
ID, 0));
1474unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1475 ArrayRef<unsigned> ChildTypeIDs) {
1476 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1477 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1478 auto It = VirtualTypeIDs.
find(CacheKey);
1479 if (It != VirtualTypeIDs.
end()) {
1485 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1486 "Incorrect cached contained type IDs");
1490 unsigned TypeID = TypeList.size();
1491 TypeList.push_back(Ty);
1492 if (!ChildTypeIDs.
empty())
1513 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1527 if (Opcode == Instruction::GetElementPtr)
1531 case Instruction::FNeg:
1532 case Instruction::Select:
1533 case Instruction::ICmp:
1534 case Instruction::FCmp:
1541Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1542 BasicBlock *InsertBB) {
1544 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1546 return ValueList[StartValID];
1548 SmallDenseMap<unsigned, Value *> MaterializedValues;
1549 SmallVector<unsigned> Worklist;
1551 while (!Worklist.
empty()) {
1552 unsigned ValID = Worklist.
back();
1553 if (MaterializedValues.
count(ValID)) {
1559 if (ValID >= ValueList.
size() || !ValueList[ValID])
1560 return error(
"Invalid value ID");
1562 Value *
V = ValueList[ValID];
1565 MaterializedValues.
insert({ValID,
V});
1573 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1574 auto It = MaterializedValues.
find(OpID);
1575 if (It != MaterializedValues.
end())
1576 Ops.push_back(It->second);
1583 if (
Ops.size() != BC->getOperandIDs().size())
1585 std::reverse(
Ops.begin(),
Ops.end());
1602 switch (BC->Opcode) {
1603 case BitcodeConstant::ConstantPtrAuthOpcode: {
1606 return error(
"ptrauth key operand must be ConstantInt");
1610 return error(
"ptrauth disc operand must be ConstantInt");
1615 case BitcodeConstant::NoCFIOpcode: {
1618 return error(
"no_cfi operand must be GlobalValue");
1622 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1625 return error(
"dso_local operand must be GlobalValue");
1629 case BitcodeConstant::BlockAddressOpcode: {
1632 return error(
"blockaddress operand must be a function");
1637 unsigned BBID = BC->BlockAddressBB;
1640 return error(
"Invalid ID");
1643 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1645 return error(
"Invalid ID");
1652 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1654 BasicBlockFwdRefQueue.push_back(Fn);
1655 if (FwdBBs.size() < BBID + 1)
1656 FwdBBs.resize(BBID + 1);
1664 case BitcodeConstant::ConstantStructOpcode: {
1666 if (
ST->getNumElements() != ConstOps.
size())
1667 return error(
"Invalid number of elements in struct initializer");
1669 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1670 if (
Op->getType() != Ty)
1671 return error(
"Incorrect type in struct initializer");
1676 case BitcodeConstant::ConstantArrayOpcode: {
1678 if (AT->getNumElements() != ConstOps.
size())
1679 return error(
"Invalid number of elements in array initializer");
1681 for (Constant *
Op : ConstOps)
1682 if (
Op->getType() != AT->getElementType())
1683 return error(
"Incorrect type in array initializer");
1688 case BitcodeConstant::ConstantVectorOpcode: {
1690 if (VT->getNumElements() != ConstOps.size())
1691 return error(
"Invalid number of elements in vector initializer");
1693 for (Constant *
Op : ConstOps)
1694 if (
Op->getType() != VT->getElementType())
1695 return error(
"Incorrect type in vector initializer");
1700 case Instruction::GetElementPtr:
1702 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1705 case Instruction::ExtractElement:
1708 case Instruction::InsertElement:
1712 case Instruction::ShuffleVector: {
1713 SmallVector<int, 16>
Mask;
1725 MaterializedValues.
insert({ValID,
C});
1731 return error(Twine(
"Value referenced by initializer is an unsupported "
1732 "constant expression of type ") +
1733 BC->getOpcodeName());
1739 BC->getType(),
"constexpr", InsertBB);
1742 "constexpr", InsertBB);
1745 Ops[1],
"constexpr", InsertBB);
1748 I->setHasNoSignedWrap();
1750 I->setHasNoUnsignedWrap();
1756 switch (BC->Opcode) {
1757 case BitcodeConstant::ConstantVectorOpcode: {
1758 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1761 Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1768 case BitcodeConstant::ConstantStructOpcode:
1769 case BitcodeConstant::ConstantArrayOpcode: {
1773 "constexpr.ins", InsertBB);
1777 case Instruction::ICmp:
1778 case Instruction::FCmp:
1781 "constexpr", InsertBB);
1783 case Instruction::GetElementPtr:
1789 case Instruction::Select:
1792 case Instruction::ExtractElement:
1795 case Instruction::InsertElement:
1799 case Instruction::ShuffleVector:
1800 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1808 MaterializedValues.
insert({ValID,
I});
1812 return MaterializedValues[StartValID];
1815Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1816 Expected<Value *> MaybeV = materializeValue(
ID,
nullptr);
1824StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1827 IdentifiedStructTypes.push_back(Ret);
1831StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1833 IdentifiedStructTypes.push_back(Ret);
1849 case Attribute::ZExt:
return 1 << 0;
1850 case Attribute::SExt:
return 1 << 1;
1851 case Attribute::NoReturn:
return 1 << 2;
1852 case Attribute::InReg:
return 1 << 3;
1853 case Attribute::StructRet:
return 1 << 4;
1854 case Attribute::NoUnwind:
return 1 << 5;
1855 case Attribute::NoAlias:
return 1 << 6;
1856 case Attribute::ByVal:
return 1 << 7;
1857 case Attribute::Nest:
return 1 << 8;
1858 case Attribute::ReadNone:
return 1 << 9;
1859 case Attribute::ReadOnly:
return 1 << 10;
1860 case Attribute::NoInline:
return 1 << 11;
1861 case Attribute::AlwaysInline:
return 1 << 12;
1862 case Attribute::OptimizeForSize:
return 1 << 13;
1863 case Attribute::StackProtect:
return 1 << 14;
1864 case Attribute::StackProtectReq:
return 1 << 15;
1865 case Attribute::Alignment:
return 31 << 16;
1867 case Attribute::NoRedZone:
return 1 << 22;
1868 case Attribute::NoImplicitFloat:
return 1 << 23;
1869 case Attribute::Naked:
return 1 << 24;
1870 case Attribute::InlineHint:
return 1 << 25;
1871 case Attribute::StackAlignment:
return 7 << 26;
1872 case Attribute::ReturnsTwice:
return 1 << 29;
1873 case Attribute::UWTable:
return 1 << 30;
1874 case Attribute::NonLazyBind:
return 1U << 31;
1875 case Attribute::SanitizeAddress:
return 1ULL << 32;
1876 case Attribute::MinSize:
return 1ULL << 33;
1877 case Attribute::NoDuplicate:
return 1ULL << 34;
1878 case Attribute::StackProtectStrong:
return 1ULL << 35;
1879 case Attribute::SanitizeThread:
return 1ULL << 36;
1880 case Attribute::SanitizeMemory:
return 1ULL << 37;
1881 case Attribute::NoBuiltin:
return 1ULL << 38;
1882 case Attribute::Returned:
return 1ULL << 39;
1883 case Attribute::Cold:
return 1ULL << 40;
1884 case Attribute::Builtin:
return 1ULL << 41;
1885 case Attribute::OptimizeNone:
return 1ULL << 42;
1886 case Attribute::InAlloca:
return 1ULL << 43;
1887 case Attribute::NonNull:
return 1ULL << 44;
1888 case Attribute::JumpTable:
return 1ULL << 45;
1889 case Attribute::Convergent:
return 1ULL << 46;
1890 case Attribute::SafeStack:
return 1ULL << 47;
1891 case Attribute::NoRecurse:
return 1ULL << 48;
1894 case Attribute::SwiftSelf:
return 1ULL << 51;
1895 case Attribute::SwiftError:
return 1ULL << 52;
1896 case Attribute::WriteOnly:
return 1ULL << 53;
1897 case Attribute::Speculatable:
return 1ULL << 54;
1898 case Attribute::StrictFP:
return 1ULL << 55;
1899 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1900 case Attribute::NoCfCheck:
return 1ULL << 57;
1901 case Attribute::OptForFuzzing:
return 1ULL << 58;
1902 case Attribute::ShadowCallStack:
return 1ULL << 59;
1903 case Attribute::SpeculativeLoadHardening:
1905 case Attribute::ImmArg:
1907 case Attribute::WillReturn:
1909 case Attribute::NoFree:
1925 if (
I == Attribute::Alignment)
1926 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
1927 else if (
I == Attribute::StackAlignment)
1928 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
1930 B.addTypeAttr(
I,
nullptr);
1944 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1946 "Alignment must be a power of two.");
1949 B.addAlignmentAttr(Alignment);
1951 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1952 (EncodedAttrs & 0xffff);
1954 if (AttrIdx == AttributeList::FunctionIndex) {
1957 if (Attrs & (1ULL << 9)) {
1959 Attrs &= ~(1ULL << 9);
1962 if (Attrs & (1ULL << 10)) {
1964 Attrs &= ~(1ULL << 10);
1967 if (Attrs & (1ULL << 49)) {
1969 Attrs &= ~(1ULL << 49);
1972 if (Attrs & (1ULL << 50)) {
1974 Attrs &= ~(1ULL << 50);
1977 if (Attrs & (1ULL << 53)) {
1979 Attrs &= ~(1ULL << 53);
1983 B.addMemoryAttr(ME);
1987 if (Attrs & (1ULL << 21)) {
1988 Attrs &= ~(1ULL << 21);
1995Error BitcodeReader::parseAttributeBlock() {
1999 if (!MAttributes.empty())
2000 return error(
"Invalid multiple blocks");
2002 SmallVector<uint64_t, 64> Record;
2008 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2011 BitstreamEntry
Entry = MaybeEntry.
get();
2013 switch (
Entry.Kind) {
2016 return error(
"Malformed block");
2026 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2029 switch (MaybeRecord.
get()) {
2034 if (Record.
size() & 1)
2035 return error(
"Invalid parameter attribute record");
2037 for (
unsigned i = 0, e = Record.
size(); i != e; i += 2) {
2043 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2047 for (uint64_t Val : Record)
2048 Attrs.push_back(MAttributeGroups[Val]);
2050 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2063 return Attribute::Alignment;
2065 return Attribute::AlwaysInline;
2067 return Attribute::Builtin;
2069 return Attribute::ByVal;
2071 return Attribute::InAlloca;
2073 return Attribute::Cold;
2075 return Attribute::Convergent;
2077 return Attribute::DisableSanitizerInstrumentation;
2079 return Attribute::ElementType;
2081 return Attribute::FnRetThunkExtern;
2083 return Attribute::InlineHint;
2085 return Attribute::InReg;
2087 return Attribute::JumpTable;
2089 return Attribute::Memory;
2091 return Attribute::NoFPClass;
2093 return Attribute::MinSize;
2095 return Attribute::Naked;
2097 return Attribute::Nest;
2099 return Attribute::NoAlias;
2101 return Attribute::NoBuiltin;
2103 return Attribute::NoCallback;
2105 return Attribute::NoDivergenceSource;
2107 return Attribute::NoDuplicate;
2109 return Attribute::NoFree;
2111 return Attribute::NoImplicitFloat;
2113 return Attribute::NoInline;
2115 return Attribute::NoRecurse;
2117 return Attribute::NoMerge;
2119 return Attribute::NonLazyBind;
2121 return Attribute::NonNull;
2123 return Attribute::Dereferenceable;
2125 return Attribute::DereferenceableOrNull;
2127 return Attribute::AllocAlign;
2129 return Attribute::AllocKind;
2131 return Attribute::AllocSize;
2133 return Attribute::AllocatedPointer;
2135 return Attribute::NoRedZone;
2137 return Attribute::NoReturn;
2139 return Attribute::NoSync;
2141 return Attribute::NoCfCheck;
2143 return Attribute::NoProfile;
2145 return Attribute::SkipProfile;
2147 return Attribute::NoUnwind;
2149 return Attribute::NoSanitizeBounds;
2151 return Attribute::NoSanitizeCoverage;
2153 return Attribute::NullPointerIsValid;
2155 return Attribute::OptimizeForDebugging;
2157 return Attribute::OptForFuzzing;
2159 return Attribute::OptimizeForSize;
2161 return Attribute::OptimizeNone;
2163 return Attribute::ReadNone;
2165 return Attribute::ReadOnly;
2167 return Attribute::Returned;
2169 return Attribute::ReturnsTwice;
2171 return Attribute::SExt;
2173 return Attribute::Speculatable;
2175 return Attribute::StackAlignment;
2177 return Attribute::StackProtect;
2179 return Attribute::StackProtectReq;
2181 return Attribute::StackProtectStrong;
2183 return Attribute::SafeStack;
2185 return Attribute::ShadowCallStack;
2187 return Attribute::StrictFP;
2189 return Attribute::StructRet;
2191 return Attribute::SanitizeAddress;
2193 return Attribute::SanitizeHWAddress;
2195 return Attribute::SanitizeThread;
2197 return Attribute::SanitizeType;
2199 return Attribute::SanitizeMemory;
2201 return Attribute::SanitizeNumericalStability;
2203 return Attribute::SanitizeRealtime;
2205 return Attribute::SanitizeRealtimeBlocking;
2207 return Attribute::SanitizeAllocToken;
2209 return Attribute::SpeculativeLoadHardening;
2211 return Attribute::SwiftError;
2213 return Attribute::SwiftSelf;
2215 return Attribute::SwiftAsync;
2217 return Attribute::UWTable;
2219 return Attribute::VScaleRange;
2221 return Attribute::WillReturn;
2223 return Attribute::WriteOnly;
2225 return Attribute::ZExt;
2227 return Attribute::ImmArg;
2229 return Attribute::SanitizeMemTag;
2231 return Attribute::Preallocated;
2233 return Attribute::NoUndef;
2235 return Attribute::ByRef;
2237 return Attribute::MustProgress;
2239 return Attribute::Hot;
2241 return Attribute::PresplitCoroutine;
2243 return Attribute::Writable;
2245 return Attribute::CoroDestroyOnlyWhenComplete;
2247 return Attribute::DeadOnUnwind;
2249 return Attribute::Range;
2251 return Attribute::Initializes;
2253 return Attribute::CoroElideSafe;
2255 return Attribute::NoExt;
2257 return Attribute::Captures;
2259 return Attribute::DeadOnReturn;
2261 return Attribute::NoCreateUndefOrPoison;
2266 MaybeAlign &Alignment) {
2269 if (
Exponent > Value::MaxAlignmentExponent + 1)
2270 return error(
"Invalid alignment value");
2275Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2277 if (*Kind == Attribute::None)
2278 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2283 switch (EncodedKind) {
2307Error BitcodeReader::parseAttributeGroupBlock() {
2311 if (!MAttributeGroups.empty())
2312 return error(
"Invalid multiple blocks");
2314 SmallVector<uint64_t, 64> Record;
2318 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2321 BitstreamEntry
Entry = MaybeEntry.
get();
2323 switch (
Entry.Kind) {
2326 return error(
"Malformed block");
2336 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2339 switch (MaybeRecord.
get()) {
2343 if (Record.
size() < 3)
2344 return error(
"Invalid grp record");
2346 uint64_t GrpID = Record[0];
2347 uint64_t Idx = Record[1];
2351 for (
unsigned i = 2, e = Record.
size(); i != e; ++i) {
2352 if (Record[i] == 0) {
2353 Attribute::AttrKind
Kind;
2354 uint64_t EncodedKind = Record[++i];
2355 if (Idx == AttributeList::FunctionIndex &&
2364 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2370 if (Kind == Attribute::ByVal)
2371 B.addByValAttr(
nullptr);
2372 else if (Kind == Attribute::StructRet)
2373 B.addStructRetAttr(
nullptr);
2374 else if (Kind == Attribute::InAlloca)
2375 B.addInAllocaAttr(
nullptr);
2376 else if (Kind == Attribute::UWTable)
2377 B.addUWTableAttr(UWTableKind::Default);
2378 else if (Attribute::isEnumAttrKind(Kind))
2379 B.addAttribute(Kind);
2381 return error(
"Not an enum attribute");
2382 }
else if (Record[i] == 1) {
2383 Attribute::AttrKind
Kind;
2384 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2386 if (!Attribute::isIntAttrKind(Kind))
2387 return error(
"Not an int attribute");
2388 if (Kind == Attribute::Alignment)
2389 B.addAlignmentAttr(Record[++i]);
2390 else if (Kind == Attribute::StackAlignment)
2391 B.addStackAlignmentAttr(Record[++i]);
2392 else if (Kind == Attribute::Dereferenceable)
2393 B.addDereferenceableAttr(Record[++i]);
2394 else if (Kind == Attribute::DereferenceableOrNull)
2395 B.addDereferenceableOrNullAttr(Record[++i]);
2396 else if (Kind == Attribute::AllocSize)
2397 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2398 else if (Kind == Attribute::VScaleRange)
2399 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2400 else if (Kind == Attribute::UWTable)
2402 else if (Kind == Attribute::AllocKind)
2403 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2404 else if (Kind == Attribute::Memory) {
2405 uint64_t EncodedME = Record[++i];
2406 const uint8_t
Version = (EncodedME >> 56);
2418 B.addMemoryAttr(ME);
2423 EncodedME & 0x00FFFFFFFFFFFFFFULL));
2425 }
else if (Kind == Attribute::Captures)
2427 else if (Kind == Attribute::NoFPClass)
2430 }
else if (Record[i] == 3 || Record[i] == 4) {
2431 bool HasValue = (Record[i++] == 4);
2432 SmallString<64> KindStr;
2433 SmallString<64> ValStr;
2435 while (Record[i] != 0 && i != e)
2436 KindStr += Record[i++];
2437 assert(Record[i] == 0 &&
"Kind string not null terminated");
2442 while (Record[i] != 0 && i != e)
2443 ValStr += Record[i++];
2444 assert(Record[i] == 0 &&
"Value string not null terminated");
2447 B.addAttribute(KindStr.
str(), ValStr.
str());
2448 }
else if (Record[i] == 5 || Record[i] == 6) {
2449 bool HasType = Record[i] == 6;
2450 Attribute::AttrKind
Kind;
2451 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2453 if (!Attribute::isTypeAttrKind(Kind))
2454 return error(
"Not a type attribute");
2456 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2457 }
else if (Record[i] == 7) {
2458 Attribute::AttrKind
Kind;
2461 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2463 if (!Attribute::isConstantRangeAttrKind(Kind))
2464 return error(
"Not a ConstantRange attribute");
2466 Expected<ConstantRange> MaybeCR =
2467 readBitWidthAndConstantRange(Record, i);
2472 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2473 }
else if (Record[i] == 8) {
2474 Attribute::AttrKind
Kind;
2477 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2479 if (!Attribute::isConstantRangeListAttrKind(Kind))
2480 return error(
"Not a constant range list attribute");
2484 return error(
"Too few records for constant range list");
2485 unsigned RangeSize = Record[i++];
2487 for (
unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2488 Expected<ConstantRange> MaybeCR =
2489 readConstantRange(Record, i,
BitWidth);
2497 return error(
"Invalid (unordered or overlapping) range list");
2498 B.addConstantRangeListAttr(Kind, Val);
2500 return error(
"Invalid attribute group entry");
2505 B.addMemoryAttr(ME);
2508 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2515Error BitcodeReader::parseTypeTable() {
2519 return parseTypeTableBody();
2522Error BitcodeReader::parseTypeTableBody() {
2523 if (!TypeList.empty())
2524 return error(
"Invalid multiple blocks");
2526 SmallVector<uint64_t, 64> Record;
2527 unsigned NumRecords = 0;
2533 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2536 BitstreamEntry
Entry = MaybeEntry.
get();
2538 switch (
Entry.Kind) {
2541 return error(
"Malformed block");
2543 if (NumRecords != TypeList.size())
2544 return error(
"Malformed block");
2553 Type *ResultTy =
nullptr;
2554 SmallVector<unsigned> ContainedIDs;
2555 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2558 switch (MaybeRecord.
get()) {
2560 return error(
"Invalid value");
2565 return error(
"Invalid numentry record");
2566 TypeList.resize(Record[0]);
2569 ResultTy = Type::getVoidTy(
Context);
2572 ResultTy = Type::getHalfTy(
Context);
2575 ResultTy = Type::getBFloatTy(
Context);
2578 ResultTy = Type::getFloatTy(
Context);
2581 ResultTy = Type::getDoubleTy(
Context);
2584 ResultTy = Type::getX86_FP80Ty(
Context);
2587 ResultTy = Type::getFP128Ty(
Context);
2590 ResultTy = Type::getPPC_FP128Ty(
Context);
2593 ResultTy = Type::getLabelTy(
Context);
2596 ResultTy = Type::getMetadataTy(
Context);
2604 ResultTy = Type::getX86_AMXTy(
Context);
2607 ResultTy = Type::getTokenTy(
Context);
2611 return error(
"Invalid integer record");
2613 uint64_t NumBits = Record[0];
2616 return error(
"Bitwidth for integer type out of range");
2623 return error(
"Invalid pointer record");
2625 if (Record.
size() == 2)
2627 ResultTy = getTypeByID(Record[0]);
2629 !PointerType::isValidElementType(ResultTy))
2630 return error(
"Invalid type");
2636 if (Record.
size() != 1)
2637 return error(
"Invalid opaque pointer record");
2645 if (Record.
size() < 3)
2646 return error(
"Invalid function record");
2648 for (
unsigned i = 3, e = Record.
size(); i != e; ++i) {
2649 if (
Type *
T = getTypeByID(Record[i]))
2655 ResultTy = getTypeByID(Record[2]);
2656 if (!ResultTy || ArgTys.
size() < Record.
size()-3)
2657 return error(
"Invalid type");
2660 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2665 if (Record.
size() < 2)
2666 return error(
"Invalid function record");
2668 for (
unsigned i = 2, e = Record.
size(); i != e; ++i) {
2669 if (
Type *
T = getTypeByID(Record[i])) {
2670 if (!FunctionType::isValidArgumentType(
T))
2671 return error(
"Invalid function argument type");
2678 ResultTy = getTypeByID(Record[1]);
2679 if (!ResultTy || ArgTys.
size() < Record.
size()-2)
2680 return error(
"Invalid type");
2683 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2688 return error(
"Invalid anon struct record");
2690 for (
unsigned i = 1, e = Record.
size(); i != e; ++i) {
2691 if (
Type *
T = getTypeByID(Record[i]))
2696 if (EltTys.
size() != Record.
size()-1)
2697 return error(
"Invalid type");
2704 return error(
"Invalid struct name record");
2709 return error(
"Invalid named struct record");
2711 if (NumRecords >= TypeList.size())
2712 return error(
"Invalid TYPE table");
2718 TypeList[NumRecords] =
nullptr;
2720 Res = createIdentifiedStructType(
Context, TypeName);
2724 for (
unsigned i = 1, e = Record.
size(); i != e; ++i) {
2725 if (
Type *
T = getTypeByID(Record[i]))
2730 if (EltTys.
size() != Record.
size()-1)
2731 return error(
"Invalid named struct record");
2739 if (Record.
size() != 1)
2740 return error(
"Invalid opaque type record");
2742 if (NumRecords >= TypeList.size())
2743 return error(
"Invalid TYPE table");
2749 TypeList[NumRecords] =
nullptr;
2751 Res = createIdentifiedStructType(
Context, TypeName);
2757 if (Record.
size() < 1)
2758 return error(
"Invalid target extension type record");
2760 if (NumRecords >= TypeList.size())
2761 return error(
"Invalid TYPE table");
2763 if (Record[0] >= Record.
size())
2764 return error(
"Too many type parameters");
2766 unsigned NumTys = Record[0];
2768 SmallVector<unsigned, 8> IntParams;
2769 for (
unsigned i = 0; i < NumTys; i++) {
2770 if (
Type *
T = getTypeByID(Record[i + 1]))
2773 return error(
"Invalid type");
2776 for (
unsigned i = NumTys + 1, e = Record.
size(); i < e; i++) {
2777 if (Record[i] > UINT_MAX)
2778 return error(
"Integer parameter too large");
2783 if (
auto E = TTy.takeError())
2790 if (Record.
size() < 2)
2791 return error(
"Invalid array type record");
2792 ResultTy = getTypeByID(Record[1]);
2793 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2794 return error(
"Invalid type");
2796 ResultTy = ArrayType::get(ResultTy, Record[0]);
2800 if (Record.
size() < 2)
2801 return error(
"Invalid vector type record");
2803 return error(
"Invalid vector length");
2804 ResultTy = getTypeByID(Record[1]);
2805 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2806 return error(
"Invalid type");
2807 bool Scalable = Record.
size() > 2 ? Record[2] :
false;
2809 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2813 if (NumRecords >= TypeList.size())
2814 return error(
"Invalid TYPE table");
2815 if (TypeList[NumRecords])
2817 "Invalid TYPE table: Only named structs can be forward referenced");
2818 assert(ResultTy &&
"Didn't read a type?");
2819 TypeList[NumRecords] = ResultTy;
2820 if (!ContainedIDs.
empty())
2821 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2826Error BitcodeReader::parseOperandBundleTags() {
2830 if (!BundleTags.empty())
2831 return error(
"Invalid multiple blocks");
2833 SmallVector<uint64_t, 64> Record;
2836 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2839 BitstreamEntry
Entry = MaybeEntry.
get();
2841 switch (
Entry.Kind) {
2844 return error(
"Malformed block");
2854 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2858 return error(
"Invalid operand bundle record");
2861 BundleTags.emplace_back();
2863 return error(
"Invalid operand bundle record");
2868Error BitcodeReader::parseSyncScopeNames() {
2873 return error(
"Invalid multiple synchronization scope names blocks");
2875 SmallVector<uint64_t, 64> Record;
2877 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2880 BitstreamEntry
Entry = MaybeEntry.
get();
2882 switch (
Entry.Kind) {
2885 return error(
"Malformed block");
2888 return error(
"Invalid empty synchronization scope names block");
2898 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2902 return error(
"Invalid sync scope record");
2904 SmallString<16> SSN;
2906 return error(
"Invalid sync scope record");
2914Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2915 unsigned NameIndex, Triple &TT) {
2918 return error(
"Invalid record");
2919 unsigned ValueID = Record[0];
2920 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
2921 return error(
"Invalid record");
2922 Value *
V = ValueList[ValueID];
2925 if (NameStr.contains(0))
2926 return error(
"Invalid value name");
2927 V->setName(NameStr);
2929 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
2942 return std::move(JumpFailed);
2948 return error(
"Expected value symbol table subblock");
2952void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
2954 ArrayRef<uint64_t> Record) {
2958 uint64_t FuncWordOffset = Record[1] - 1;
2959 uint64_t FuncBitOffset = FuncWordOffset * 32;
2960 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2964 if (FuncBitOffset > LastFunctionBlockBit)
2965 LastFunctionBlockBit = FuncBitOffset;
2969Error BitcodeReader::parseGlobalValueSymbolTable() {
2970 unsigned FuncBitcodeOffsetDelta =
2976 SmallVector<uint64_t, 64> Record;
2978 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2981 BitstreamEntry
Entry = MaybeEntry.
get();
2983 switch (
Entry.Kind) {
2986 return error(
"Malformed block");
2994 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
2997 switch (MaybeRecord.
get()) {
2999 unsigned ValueID = Record[0];
3000 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3001 return error(
"Invalid value reference in symbol table");
3002 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3012Error BitcodeReader::parseValueSymbolTable(uint64_t
Offset) {
3013 uint64_t CurrentBit;
3019 if (!MaybeCurrentBit)
3021 CurrentBit = MaybeCurrentBit.
get();
3024 if (
Error Err = parseGlobalValueSymbolTable())
3026 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
3045 unsigned FuncBitcodeOffsetDelta =
3051 SmallVector<uint64_t, 64> Record;
3059 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3062 BitstreamEntry
Entry = MaybeEntry.
get();
3064 switch (
Entry.Kind) {
3067 return error(
"Malformed block");
3070 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
3080 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
3083 switch (MaybeRecord.
get()) {
3087 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3095 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3103 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3108 return error(
"Invalid bbentry record");
3111 return error(
"Invalid bbentry record");
3123uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3133Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3134 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3135 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3136 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3138 GlobalInitWorklist.swap(GlobalInits);
3139 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3140 FunctionOperandWorklist.swap(FunctionOperands);
3142 while (!GlobalInitWorklist.empty()) {
3143 unsigned ValID = GlobalInitWorklist.back().second;
3144 if (ValID >= ValueList.
size()) {
3146 GlobalInits.push_back(GlobalInitWorklist.back());
3148 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3151 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3153 GlobalInitWorklist.pop_back();
3156 while (!IndirectSymbolInitWorklist.empty()) {
3157 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3158 if (ValID >= ValueList.
size()) {
3159 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3161 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3165 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3168 return error(
"Alias and aliasee types don't match");
3173 return error(
"Expected an alias or an ifunc");
3176 IndirectSymbolInitWorklist.pop_back();
3179 while (!FunctionOperandWorklist.empty()) {
3180 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3181 if (
Info.PersonalityFn) {
3182 unsigned ValID =
Info.PersonalityFn - 1;
3183 if (ValID < ValueList.
size()) {
3184 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3187 Info.F->setPersonalityFn(MaybeC.
get());
3188 Info.PersonalityFn = 0;
3192 unsigned ValID =
Info.Prefix - 1;
3193 if (ValID < ValueList.
size()) {
3194 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3197 Info.F->setPrefixData(MaybeC.
get());
3201 if (
Info.Prologue) {
3202 unsigned ValID =
Info.Prologue - 1;
3203 if (ValID < ValueList.
size()) {
3204 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3207 Info.F->setPrologueData(MaybeC.
get());
3211 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3212 FunctionOperands.push_back(
Info);
3213 FunctionOperandWorklist.pop_back();
3222 BitcodeReader::decodeSignRotatedValue);
3224 return APInt(TypeBits, Words);
3227Error BitcodeReader::parseConstants() {
3235 unsigned Int32TyID = getVirtualTypeID(CurTy);
3236 unsigned CurTyID = Int32TyID;
3237 Type *CurElemTy =
nullptr;
3238 unsigned NextCstNo = ValueList.
size();
3246 switch (Entry.Kind) {
3249 return error(
"Malformed block");
3251 if (NextCstNo != ValueList.
size())
3252 return error(
"Invalid constant reference");
3263 Expected<unsigned> MaybeBitCode = Stream.readRecord(
Entry.ID, Record);
3266 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3276 return error(
"Invalid settype record");
3277 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3278 return error(
"Invalid settype record");
3279 if (TypeList[Record[0]] == VoidType)
3280 return error(
"Invalid constant type");
3281 CurTyID = Record[0];
3282 CurTy = TypeList[CurTyID];
3283 CurElemTy = getPtrElementTypeByID(CurTyID);
3287 return error(
"Invalid type for a constant null value");
3290 return error(
"Invalid type for a constant null value");
3295 return error(
"Invalid integer const record");
3300 return error(
"Invalid wide integer const record");
3303 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3304 V = ConstantInt::get(CurTy, VInt);
3309 return error(
"Invalid float const record");
3312 if (ScalarTy->isHalfTy())
3313 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3314 APInt(16, (uint16_t)Record[0])));
3315 else if (ScalarTy->isBFloatTy())
3316 V = ConstantFP::get(
3317 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3318 else if (ScalarTy->isFloatTy())
3319 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3320 APInt(32, (uint32_t)Record[0])));
3321 else if (ScalarTy->isDoubleTy())
3322 V = ConstantFP::get(
3323 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3324 else if (ScalarTy->isX86_FP80Ty()) {
3326 uint64_t Rearrange[2];
3327 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
3328 Rearrange[1] = Record[0] >> 48;
3329 V = ConstantFP::get(
3330 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3331 }
else if (ScalarTy->isFP128Ty())
3332 V = ConstantFP::get(CurTy,
3333 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3334 else if (ScalarTy->isPPC_FP128Ty())
3335 V = ConstantFP::get(
3336 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3344 return error(
"Invalid aggregate record");
3346 SmallVector<unsigned, 16> Elts;
3350 V = BitcodeConstant::create(
3351 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3353 V = BitcodeConstant::create(
Alloc, CurTy,
3354 BitcodeConstant::ConstantArrayOpcode, Elts);
3356 V = BitcodeConstant::create(
3357 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3366 return error(
"Invalid string record");
3368 SmallString<16> Elts(Record.begin(), Record.end());
3375 return error(
"Invalid data record");
3379 EltTy =
Array->getElementType();
3389 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3395 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3401 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3407 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3413 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3419 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3425 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3431 return error(
"Invalid type for value");
3436 if (Record.size() < 2)
3437 return error(
"Invalid unary op constexpr record");
3442 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3447 if (Record.size() < 3)
3448 return error(
"Invalid binary op constexpr record");
3454 if (Record.size() >= 4) {
3455 if (
Opc == Instruction::Add ||
3456 Opc == Instruction::Sub ||
3457 Opc == Instruction::Mul ||
3458 Opc == Instruction::Shl) {
3463 }
else if (
Opc == Instruction::SDiv ||
3464 Opc == Instruction::UDiv ||
3465 Opc == Instruction::LShr ||
3466 Opc == Instruction::AShr) {
3471 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3472 {(unsigned)Record[1], (
unsigned)Record[2]});
3477 if (Record.size() < 3)
3478 return error(
"Invalid cast constexpr record");
3483 unsigned OpTyID = Record[1];
3484 Type *OpTy = getTypeByID(OpTyID);
3486 return error(
"Invalid cast constexpr record");
3487 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3498 if (Record.size() < 2)
3499 return error(
"Constant GEP record must have at least two elements");
3501 Type *PointeeType =
nullptr;
3505 PointeeType = getTypeByID(Record[OpNum++]);
3508 std::optional<ConstantRange>
InRange;
3510 uint64_t
Op = Record[OpNum++];
3512 unsigned InRangeIndex =
Op >> 1;
3517 Flags = Record[OpNum++];
3518 Expected<ConstantRange> MaybeInRange =
3519 readBitWidthAndConstantRange(Record, OpNum);
3524 Flags = Record[OpNum++];
3528 SmallVector<unsigned, 16> Elts;
3529 unsigned BaseTypeID = Record[OpNum];
3530 while (OpNum != Record.size()) {
3531 unsigned ElTyID = Record[OpNum++];
3532 Type *ElTy = getTypeByID(ElTyID);
3534 return error(
"Invalid getelementptr constexpr record");
3538 if (Elts.
size() < 1)
3539 return error(
"Invalid gep with no operands");
3543 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3544 BaseType = getTypeByID(BaseTypeID);
3549 return error(
"GEP base operand must be pointer or vector of pointer");
3552 PointeeType = getPtrElementTypeByID(BaseTypeID);
3554 return error(
"Missing element type for old-style constant GEP");
3557 V = BitcodeConstant::create(
3559 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3564 if (Record.size() < 3)
3565 return error(
"Invalid select constexpr record");
3567 V = BitcodeConstant::create(
3568 Alloc, CurTy, Instruction::Select,
3569 {(unsigned)Record[0], (
unsigned)Record[1], (unsigned)Record[2]});
3574 if (Record.size() < 3)
3575 return error(
"Invalid extractelement constexpr record");
3576 unsigned OpTyID = Record[0];
3580 return error(
"Invalid extractelement constexpr record");
3582 if (Record.size() == 4) {
3583 unsigned IdxTyID = Record[2];
3584 Type *IdxTy = getTypeByID(IdxTyID);
3586 return error(
"Invalid extractelement constexpr record");
3587 IdxRecord = Record[3];
3590 IdxRecord = Record[2];
3592 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3593 {(unsigned)Record[1], IdxRecord});
3599 if (Record.size() < 3 || !OpTy)
3600 return error(
"Invalid insertelement constexpr record");
3602 if (Record.size() == 4) {
3603 unsigned IdxTyID = Record[2];
3604 Type *IdxTy = getTypeByID(IdxTyID);
3606 return error(
"Invalid insertelement constexpr record");
3607 IdxRecord = Record[3];
3610 IdxRecord = Record[2];
3612 V = BitcodeConstant::create(
3613 Alloc, CurTy, Instruction::InsertElement,
3614 {(unsigned)Record[0], (
unsigned)Record[1], IdxRecord});
3619 if (Record.size() < 3 || !OpTy)
3620 return error(
"Invalid shufflevector constexpr record");
3621 V = BitcodeConstant::create(
3622 Alloc, CurTy, Instruction::ShuffleVector,
3623 {(unsigned)Record[0], (
unsigned)Record[1], (unsigned)Record[2]});
3630 if (Record.size() < 4 || !RTy || !OpTy)
3631 return error(
"Invalid shufflevector constexpr record");
3632 V = BitcodeConstant::create(
3633 Alloc, CurTy, Instruction::ShuffleVector,
3634 {(unsigned)Record[1], (
unsigned)Record[2], (unsigned)Record[3]});
3638 if (Record.size() < 4)
3639 return error(
"Invalid cmp constexpt record");
3640 unsigned OpTyID = Record[0];
3641 Type *OpTy = getTypeByID(OpTyID);
3643 return error(
"Invalid cmp constexpr record");
3644 V = BitcodeConstant::create(
3647 : Instruction::ICmp),
3648 (uint8_t)Record[3]},
3649 {(unsigned)Record[1], (
unsigned)Record[2]});
3655 if (Record.size() < 2)
3656 return error(
"Invalid inlineasm record");
3657 std::string AsmStr, ConstrStr;
3658 bool HasSideEffects = Record[0] & 1;
3659 bool IsAlignStack = Record[0] >> 1;
3660 unsigned AsmStrSize = Record[1];
3661 if (2+AsmStrSize >= Record.size())
3662 return error(
"Invalid inlineasm record");
3663 unsigned ConstStrSize = Record[2+AsmStrSize];
3664 if (3+AsmStrSize+ConstStrSize > Record.size())
3665 return error(
"Invalid inlineasm record");
3667 for (
unsigned i = 0; i != AsmStrSize; ++i)
3668 AsmStr += (
char)Record[2+i];
3669 for (
unsigned i = 0; i != ConstStrSize; ++i)
3670 ConstrStr += (
char)Record[3+AsmStrSize+i];
3673 return error(
"Missing element type for old-style inlineasm");
3675 HasSideEffects, IsAlignStack);
3681 if (Record.size() < 2)
3682 return error(
"Invalid inlineasm record");
3683 std::string AsmStr, ConstrStr;
3684 bool HasSideEffects = Record[0] & 1;
3685 bool IsAlignStack = (Record[0] >> 1) & 1;
3686 unsigned AsmDialect = Record[0] >> 2;
3687 unsigned AsmStrSize = Record[1];
3688 if (2+AsmStrSize >= Record.size())
3689 return error(
"Invalid inlineasm record");
3690 unsigned ConstStrSize = Record[2+AsmStrSize];
3691 if (3+AsmStrSize+ConstStrSize > Record.size())
3692 return error(
"Invalid inlineasm record");
3694 for (
unsigned i = 0; i != AsmStrSize; ++i)
3695 AsmStr += (
char)Record[2+i];
3696 for (
unsigned i = 0; i != ConstStrSize; ++i)
3697 ConstrStr += (
char)Record[3+AsmStrSize+i];
3700 return error(
"Missing element type for old-style inlineasm");
3702 HasSideEffects, IsAlignStack,
3708 if (Record.size() < 2)
3709 return error(
"Invalid inlineasm record");
3711 std::string AsmStr, ConstrStr;
3712 bool HasSideEffects = Record[OpNum] & 1;
3713 bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3714 unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3715 bool CanThrow = (Record[OpNum] >> 3) & 1;
3717 unsigned AsmStrSize = Record[OpNum];
3719 if (OpNum + AsmStrSize >= Record.size())
3720 return error(
"Invalid inlineasm record");
3721 unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3722 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3723 return error(
"Invalid inlineasm record");
3725 for (
unsigned i = 0; i != AsmStrSize; ++i)
3726 AsmStr += (
char)Record[OpNum + i];
3728 for (
unsigned i = 0; i != ConstStrSize; ++i)
3729 ConstrStr += (
char)Record[OpNum + AsmStrSize + i];
3732 return error(
"Missing element type for old-style inlineasm");
3734 HasSideEffects, IsAlignStack,
3740 if (Record.size() < 3)
3741 return error(
"Invalid inlineasm record");
3746 return error(
"Invalid inlineasm record");
3747 std::string AsmStr, ConstrStr;
3748 bool HasSideEffects = Record[OpNum] & 1;
3749 bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3750 unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3751 bool CanThrow = (Record[OpNum] >> 3) & 1;
3753 unsigned AsmStrSize = Record[OpNum];
3755 if (OpNum + AsmStrSize >= Record.size())
3756 return error(
"Invalid inlineasm record");
3757 unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3758 if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3759 return error(
"Invalid inlineasm record");
3761 for (
unsigned i = 0; i != AsmStrSize; ++i)
3762 AsmStr += (
char)Record[OpNum + i];
3764 for (
unsigned i = 0; i != ConstStrSize; ++i)
3765 ConstrStr += (
char)Record[OpNum + AsmStrSize + i];
3767 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3772 if (Record.size() < 3)
3773 return error(
"Invalid blockaddress record");
3774 unsigned FnTyID = Record[0];
3775 Type *FnTy = getTypeByID(FnTyID);
3777 return error(
"Invalid blockaddress record");
3778 V = BitcodeConstant::create(
3780 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3785 if (Record.size() < 2)
3786 return error(
"Invalid dso_local record");
3787 unsigned GVTyID = Record[0];
3788 Type *GVTy = getTypeByID(GVTyID);
3790 return error(
"Invalid dso_local record");
3791 V = BitcodeConstant::create(
3792 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3796 if (Record.size() < 2)
3797 return error(
"Invalid no_cfi record");
3798 unsigned GVTyID = Record[0];
3799 Type *GVTy = getTypeByID(GVTyID);
3801 return error(
"Invalid no_cfi record");
3802 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3807 if (Record.size() < 4)
3808 return error(
"Invalid ptrauth record");
3810 V = BitcodeConstant::create(
Alloc, CurTy,
3811 BitcodeConstant::ConstantPtrAuthOpcode,
3812 {(unsigned)Record[0], (
unsigned)Record[1],
3813 (unsigned)Record[2], (
unsigned)Record[3]});
3818 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3825Error BitcodeReader::parseUseLists() {
3830 SmallVector<uint64_t, 64> Record;
3833 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3836 BitstreamEntry
Entry = MaybeEntry.
get();
3838 switch (
Entry.Kind) {
3841 return error(
"Malformed block");
3852 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
3855 switch (MaybeRecord.
get()) {
3863 if (RecordLength < 3)
3865 return error(
"Invalid record");
3870 assert(
ID < FunctionBBs.size() &&
"Basic block not found");
3871 V = FunctionBBs[
ID];
3875 if (!
V->hasUseList())
3878 unsigned NumUses = 0;
3879 SmallDenseMap<const Use *, unsigned, 16> Order;
3880 for (
const Use &U :
V->materialized_uses()) {
3881 if (++NumUses > Record.
size())
3883 Order[&
U] = Record[NumUses - 1];
3885 if (Order.
size() != Record.
size() || NumUses > Record.
size())
3890 V->sortUseList([&](
const Use &L,
const Use &R) {
3901Error BitcodeReader::rememberAndSkipMetadata() {
3903 uint64_t CurBit = Stream.GetCurrentBitNo();
3904 DeferredMetadataInfo.push_back(CurBit);
3907 if (
Error Err = Stream.SkipBlock())
3912Error BitcodeReader::materializeMetadata() {
3913 for (uint64_t BitPos : DeferredMetadataInfo) {
3915 if (
Error JumpFailed = Stream.JumpToBit(BitPos))
3917 if (
Error Err = MDLoader->parseModuleMetadata())
3926 NamedMDNode *LinkerOpts =
3928 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
3933 DeferredMetadataInfo.clear();
3937void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
3941Error BitcodeReader::rememberAndSkipFunctionBody() {
3943 if (FunctionsWithBodies.empty())
3944 return error(
"Insufficient function protos");
3946 Function *Fn = FunctionsWithBodies.back();
3947 FunctionsWithBodies.pop_back();
3950 uint64_t CurBit = Stream.GetCurrentBitNo();
3952 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3953 "Mismatch between VST and scanned function offsets");
3954 DeferredFunctionInfo[Fn] = CurBit;
3957 if (
Error Err = Stream.SkipBlock())
3962Error BitcodeReader::globalCleanup() {
3964 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
3966 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3967 return error(
"Malformed global initializer set");
3971 for (Function &
F : *TheModule) {
3972 MDLoader->upgradeDebugIntrinsics(
F);
3975 UpgradedIntrinsics[&
F] = NewFn;
3981 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3982 for (GlobalVariable &GV : TheModule->globals())
3984 UpgradedVariables.emplace_back(&GV, Upgraded);
3985 for (
auto &Pair : UpgradedVariables) {
3986 Pair.first->eraseFromParent();
3987 TheModule->insertGlobalVariable(Pair.second);
3992 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
3993 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4001Error BitcodeReader::rememberAndSkipFunctionBodies() {
4002 if (
Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
4005 if (Stream.AtEndOfStream())
4006 return error(
"Could not find function in stream");
4008 if (!SeenFirstFunctionBody)
4009 return error(
"Trying to materialize functions before seeing function blocks");
4013 assert(SeenValueSymbolTable);
4016 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4019 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4021 switch (
Entry.Kind) {
4023 return error(
"Expect SubBlock");
4027 return error(
"Expect function block");
4029 if (
Error Err = rememberAndSkipFunctionBody())
4031 NextUnreadBit = Stream.GetCurrentBitNo();
4038Error BitcodeReaderBase::readBlockInfo() {
4039 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4041 if (!MaybeNewBlockInfo)
4043 std::optional<BitstreamBlockInfo> NewBlockInfo =
4044 std::move(MaybeNewBlockInfo.
get());
4046 return error(
"Malformed block");
4047 BlockInfo = std::move(*NewBlockInfo);
4051Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4055 std::tie(Name, Record) = readNameFromStrtab(Record);
4058 return error(
"Invalid record");
4060 std::string OldFormatName;
4062 if (Record.
size() < 2)
4063 return error(
"Invalid record");
4064 unsigned ComdatNameSize = Record[1];
4065 if (ComdatNameSize > Record.
size() - 2)
4066 return error(
"Comdat name size too large");
4067 OldFormatName.reserve(ComdatNameSize);
4068 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4069 OldFormatName += (
char)Record[2 + i];
4070 Name = OldFormatName;
4072 Comdat *
C = TheModule->getOrInsertComdat(Name);
4073 C->setSelectionKind(SK);
4074 ComdatList.push_back(
C);
4088 Meta.NoAddress =
true;
4090 Meta.NoHWAddress =
true;
4094 Meta.IsDynInit =
true;
4098Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4106 std::tie(Name, Record) = readNameFromStrtab(Record);
4108 if (Record.
size() < 6)
4109 return error(
"Invalid record");
4110 unsigned TyID = Record[0];
4111 Type *Ty = getTypeByID(TyID);
4113 return error(
"Invalid record");
4115 bool explicitType = Record[1] & 2;
4121 return error(
"Invalid type for value");
4123 TyID = getContainedTypeID(TyID);
4124 Ty = getTypeByID(TyID);
4126 return error(
"Missing element type for old-style global");
4129 uint64_t RawLinkage = Record[3];
4131 MaybeAlign Alignment;
4132 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4136 if (Record[5] - 1 >= SectionTable.size())
4137 return error(
"Invalid ID");
4138 Section = SectionTable[Record[5] - 1];
4146 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4147 if (Record.
size() > 7)
4151 if (Record.
size() > 8)
4154 bool ExternallyInitialized =
false;
4155 if (Record.
size() > 9)
4156 ExternallyInitialized = Record[9];
4158 GlobalVariable *NewGV =
4168 if (Record.
size() > 10) {
4180 if (
unsigned InitID = Record[2])
4181 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4183 if (Record.
size() > 11) {
4184 if (
unsigned ComdatID = Record[11]) {
4185 if (ComdatID > ComdatList.size())
4186 return error(
"Invalid global variable comdat ID");
4187 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4190 ImplicitComdatObjects.
insert(NewGV);
4193 if (Record.
size() > 12) {
4198 if (Record.
size() > 13) {
4204 if (Record.
size() > 15)
4205 NewGV->
setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
4207 if (Record.
size() > 16 && Record[16]) {
4208 llvm::GlobalValue::SanitizerMetadata
Meta =
4213 if (Record.
size() > 17 && Record[17]) {
4217 return error(
"Invalid global variable code model");
4223void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4224 if (ValueTypeCallback) {
4225 (*ValueTypeCallback)(
4226 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4227 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4231Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4237 std::tie(Name, Record) = readNameFromStrtab(Record);
4239 if (Record.
size() < 8)
4240 return error(
"Invalid record");
4241 unsigned FTyID = Record[0];
4242 Type *FTy = getTypeByID(FTyID);
4244 return error(
"Invalid record");
4246 FTyID = getContainedTypeID(FTyID, 0);
4247 FTy = getTypeByID(FTyID);
4249 return error(
"Missing element type for old-style function");
4253 return error(
"Invalid type for value");
4254 auto CC =
static_cast<CallingConv::ID
>(Record[1]);
4255 if (CC & ~CallingConv::MaxID)
4256 return error(
"Invalid calling convention ID");
4258 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4259 if (Record.
size() > 16)
4260 AddrSpace = Record[16];
4264 AddrSpace, Name, TheModule);
4267 "Incorrect fully specified type provided for function");
4268 FunctionTypeIDs[
Func] = FTyID;
4270 Func->setCallingConv(CC);
4271 bool isProto = Record[2];
4272 uint64_t RawLinkage = Record[3];
4275 callValueTypeCallback(Func, FTyID);
4280 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4281 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4282 Attribute::InAlloca}) {
4283 if (!
Func->hasParamAttribute(i, Kind))
4286 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4289 Func->removeParamAttr(i, Kind);
4291 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4292 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4294 return error(
"Missing param element type for attribute upgrade");
4298 case Attribute::ByVal:
4299 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4301 case Attribute::StructRet:
4302 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4304 case Attribute::InAlloca:
4305 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4311 Func->addParamAttr(i, NewAttr);
4315 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4316 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4317 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4318 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4320 return error(
"Missing param element type for x86_intrcc upgrade");
4322 Func->addParamAttr(0, NewAttr);
4325 MaybeAlign Alignment;
4326 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4329 Func->setAlignment(*Alignment);
4331 if (Record[6] - 1 >= SectionTable.size())
4332 return error(
"Invalid ID");
4333 Func->setSection(SectionTable[Record[6] - 1]);
4337 if (!
Func->hasLocalLinkage())
4339 if (Record.
size() > 8 && Record[8]) {
4340 if (Record[8] - 1 >= GCTable.size())
4341 return error(
"Invalid ID");
4342 Func->setGC(GCTable[Record[8] - 1]);
4345 if (Record.
size() > 9)
4347 Func->setUnnamedAddr(UnnamedAddr);
4349 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4350 if (Record.
size() > 10)
4351 OperandInfo.Prologue = Record[10];
4353 if (Record.
size() > 11) {
4355 if (!
Func->hasLocalLinkage()) {
4362 if (Record.
size() > 12) {
4363 if (
unsigned ComdatID = Record[12]) {
4364 if (ComdatID > ComdatList.size())
4365 return error(
"Invalid function comdat ID");
4366 Func->setComdat(ComdatList[ComdatID - 1]);
4369 ImplicitComdatObjects.
insert(Func);
4372 if (Record.
size() > 13)
4373 OperandInfo.Prefix = Record[13];
4375 if (Record.
size() > 14)
4376 OperandInfo.PersonalityFn = Record[14];
4378 if (Record.
size() > 15) {
4387 if (Record.
size() > 18 && Strtab.data() &&
4388 Record[17] + Record[18] <= Strtab.size()) {
4389 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
4392 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4394 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4395 FunctionOperands.push_back(OperandInfo);
4400 Func->setIsMaterializable(
true);
4401 FunctionsWithBodies.push_back(Func);
4402 DeferredFunctionInfo[
Func] = 0;
4407Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4408 unsigned BitCode, ArrayRef<uint64_t> Record) {
4418 std::tie(Name, Record) = readNameFromStrtab(Record);
4421 if (Record.
size() < (3 + (
unsigned)NewRecord))
4422 return error(
"Invalid record");
4424 unsigned TypeID = Record[OpNum++];
4427 return error(
"Invalid record");
4433 return error(
"Invalid type for value");
4434 AddrSpace = PTy->getAddressSpace();
4436 Ty = getTypeByID(
TypeID);
4438 return error(
"Missing element type for old-style indirect symbol");
4440 AddrSpace = Record[OpNum++];
4443 auto Val = Record[OpNum++];
4444 auto Linkage = Record[OpNum++];
4452 nullptr, TheModule);
4456 if (OpNum != Record.
size()) {
4457 auto VisInd = OpNum++;
4463 if (OpNum != Record.
size()) {
4464 auto S = Record[OpNum++];
4471 if (OpNum != Record.
size())
4473 if (OpNum != Record.
size())
4476 if (OpNum != Record.
size())
4481 if (OpNum + 1 < Record.
size()) {
4483 if (Record[OpNum] + Record[OpNum + 1] > Strtab.size())
4484 return error(
"Malformed partition, too large.");
4486 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
4490 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4494Error BitcodeReader::parseModule(uint64_t ResumeBit,
4495 bool ShouldLazyLoadMetadata,
4496 ParserCallbacks Callbacks) {
4497 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4499 if (
Error JumpFailed = Stream.JumpToBit(ResumeBit))
4504 SmallVector<uint64_t, 64> Record;
4508 bool ResolvedDataLayout =
false;
4513 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4515 auto ResolveDataLayout = [&]() ->
Error {
4516 if (ResolvedDataLayout)
4520 ResolvedDataLayout =
true;
4524 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4528 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4529 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4530 TentativeDataLayoutStr = *LayoutOverride;
4538 TheModule->setDataLayout(MaybeDL.
get());
4544 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4547 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4549 switch (
Entry.Kind) {
4551 return error(
"Malformed block");
4553 if (
Error Err = ResolveDataLayout())
4555 return globalCleanup();
4560 if (
Error Err = Stream.SkipBlock())
4564 if (
Error Err = readBlockInfo())
4568 if (
Error Err = parseAttributeBlock())
4572 if (
Error Err = parseAttributeGroupBlock())
4576 if (
Error Err = parseTypeTable())
4580 if (!SeenValueSymbolTable) {
4586 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4587 if (
Error Err = parseValueSymbolTable())
4589 SeenValueSymbolTable =
true;
4594 if (
Error Err = Stream.SkipBlock())
4599 if (
Error Err = parseConstants())
4601 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4605 if (ShouldLazyLoadMetadata) {
4606 if (
Error Err = rememberAndSkipMetadata())
4610 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4611 if (
Error Err = MDLoader->parseModuleMetadata())
4615 if (
Error Err = MDLoader->parseMetadataKinds())
4619 if (
Error Err = ResolveDataLayout())
4624 if (!SeenFirstFunctionBody) {
4625 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4626 if (
Error Err = globalCleanup())
4628 SeenFirstFunctionBody =
true;
4631 if (VSTOffset > 0) {
4635 if (!SeenValueSymbolTable) {
4636 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4638 SeenValueSymbolTable =
true;
4650 if (
Error Err = Stream.SkipBlock())
4660 if (
Error Err = rememberAndSkipFunctionBody())
4667 if (SeenValueSymbolTable) {
4668 NextUnreadBit = Stream.GetCurrentBitNo();
4671 return globalCleanup();
4675 if (
Error Err = parseUseLists())
4679 if (
Error Err = parseOperandBundleTags())
4683 if (
Error Err = parseSyncScopeNames())
4695 Expected<unsigned> MaybeBitCode = Stream.readRecord(
Entry.ID, Record);
4698 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4701 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4704 UseRelativeIDs = *VersionOrErr >= 1;
4708 if (ResolvedDataLayout)
4709 return error(
"target triple too late in module");
4712 return error(
"Invalid record");
4713 TheModule->setTargetTriple(Triple(std::move(S)));
4717 if (ResolvedDataLayout)
4718 return error(
"datalayout too late in module");
4720 return error(
"Invalid record");
4726 return error(
"Invalid record");
4727 TheModule->setModuleInlineAsm(S);
4734 return error(
"Invalid record");
4741 return error(
"Invalid record");
4742 SectionTable.push_back(S);
4748 return error(
"Invalid record");
4749 GCTable.push_back(S);
4753 if (
Error Err = parseComdatRecord(Record))
4762 if (
Error Err = parseGlobalVarRecord(Record))
4766 if (
Error Err = ResolveDataLayout())
4768 if (
Error Err = parseFunctionRecord(Record))
4774 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4780 return error(
"Invalid record");
4784 VSTOffset = Record[0] - 1;
4790 return error(
"Invalid record");
4791 TheModule->setSourceFileName(
ValueName);
4796 this->ValueTypeCallback = std::nullopt;
4800Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4802 ParserCallbacks Callbacks) {
4804 MetadataLoaderCallbacks MDCallbacks;
4805 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(
ID); };
4807 return getContainedTypeID(
I, J);
4810 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4811 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4814Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4816 return error(
"Load/Store operand is not a pointer type");
4817 if (!PointerType::isLoadableOrStorableType(ValType))
4818 return error(
"Cannot load/store from pointer");
4822Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4823 ArrayRef<unsigned> ArgTyIDs) {
4825 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4826 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4827 Attribute::InAlloca}) {
4828 if (!
Attrs.hasParamAttr(i, Kind) ||
4829 Attrs.getParamAttr(i, Kind).getValueAsType())
4832 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4834 return error(
"Missing element type for typed attribute upgrade");
4838 case Attribute::ByVal:
4839 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4841 case Attribute::StructRet:
4842 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4844 case Attribute::InAlloca:
4845 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4858 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
4862 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
4863 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4865 return error(
"Missing element type for inline asm upgrade");
4868 Attribute::get(
Context, Attribute::ElementType, ElemTy));
4876 case Intrinsic::preserve_array_access_index:
4877 case Intrinsic::preserve_struct_access_index:
4878 case Intrinsic::aarch64_ldaxr:
4879 case Intrinsic::aarch64_ldxr:
4880 case Intrinsic::aarch64_stlxr:
4881 case Intrinsic::aarch64_stxr:
4882 case Intrinsic::arm_ldaex:
4883 case Intrinsic::arm_ldrex:
4884 case Intrinsic::arm_stlex:
4885 case Intrinsic::arm_strex: {
4888 case Intrinsic::aarch64_stlxr:
4889 case Intrinsic::aarch64_stxr:
4890 case Intrinsic::arm_stlex:
4891 case Intrinsic::arm_strex:
4898 if (!
Attrs.getParamElementType(ArgNo)) {
4899 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4901 return error(
"Missing element type for elementtype upgrade");
4916Error BitcodeReader::parseFunctionBody(Function *
F) {
4921 if (MDLoader->hasFwdRefs())
4922 return error(
"Invalid function metadata: incoming forward references");
4924 InstructionList.
clear();
4925 unsigned ModuleValueListSize = ValueList.
size();
4926 unsigned ModuleMDLoaderSize = MDLoader->size();
4930 unsigned FTyID = FunctionTypeIDs[
F];
4931 for (Argument &
I :
F->args()) {
4932 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4933 assert(
I.getType() == getTypeByID(ArgTyID) &&
4934 "Incorrect fully specified type for Function Argument");
4938 unsigned NextValueNo = ValueList.
size();
4940 unsigned CurBBNo = 0;
4945 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
4949 auto getLastInstruction = [&]() -> Instruction * {
4950 if (CurBB && !CurBB->
empty())
4951 return &CurBB->
back();
4952 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4953 !FunctionBBs[CurBBNo - 1]->
empty())
4954 return &FunctionBBs[CurBBNo - 1]->back();
4958 std::vector<OperandBundleDef> OperandBundles;
4961 SmallVector<uint64_t, 64> Record;
4964 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4967 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4969 switch (
Entry.Kind) {
4971 return error(
"Malformed block");
4973 goto OutOfRecordLoop;
4978 if (
Error Err = Stream.SkipBlock())
4982 if (
Error Err = parseConstants())
4984 NextValueNo = ValueList.
size();
4987 if (
Error Err = parseValueSymbolTable())
4991 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
4995 assert(DeferredMetadataInfo.empty() &&
4996 "Must read all module-level metadata before function-level");
4997 if (
Error Err = MDLoader->parseFunctionMetadata())
5001 if (
Error Err = parseUseLists())
5015 unsigned ResTypeID = InvalidTypeID;
5016 Expected<unsigned> MaybeBitCode = Stream.readRecord(
Entry.ID, Record);
5019 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5021 return error(
"Invalid value");
5023 if (Record.
empty() || Record[0] == 0)
5024 return error(
"Invalid record");
5026 FunctionBBs.resize(Record[0]);
5029 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5030 if (BBFRI == BasicBlockFwdRefs.
end()) {
5031 for (BasicBlock *&BB : FunctionBBs)
5034 auto &BBRefs = BBFRI->second;
5036 if (BBRefs.size() > FunctionBBs.size())
5037 return error(
"Invalid ID");
5038 assert(!BBRefs.empty() &&
"Unexpected empty array");
5039 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5040 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5042 if (
I < RE && BBRefs[
I]) {
5043 BBRefs[
I]->insertInto(
F);
5044 FunctionBBs[
I] = BBRefs[
I];
5050 BasicBlockFwdRefs.
erase(BBFRI);
5053 CurBB = FunctionBBs[0];
5060 return error(
"Invalid record");
5074 for (uint64_t ValID : Record)
5076 BackwardRefFunctions.push_back(
F);
5078 return error(
"Invalid record");
5085 I = getLastInstruction();
5088 return error(
"Invalid record");
5089 I->setDebugLoc(LastLoc);
5094 I = getLastInstruction();
5095 if (!
I || Record.size() < 4)
5096 return error(
"Invalid record");
5098 unsigned Line = Record[0], Col = Record[1];
5099 unsigned ScopeID = Record[2], IAID = Record[3];
5100 bool isImplicitCode = Record.size() >= 5 && Record[4];
5101 uint64_t AtomGroup = Record.size() == 7 ? Record[5] : 0;
5102 uint8_t AtomRank = Record.size() == 7 ? Record[6] : 0;
5104 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5107 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5109 return error(
"Invalid record");
5113 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5115 return error(
"Invalid record");
5118 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5119 isImplicitCode, AtomGroup, AtomRank);
5120 I->setDebugLoc(LastLoc);
5128 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5129 OpNum+1 > Record.size())
5130 return error(
"Invalid record");
5134 return error(
"Invalid record");
5138 if (OpNum < Record.size()) {
5142 I->setFastMathFlags(FMF);
5151 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5154 OpNum+1 > Record.size())
5155 return error(
"Invalid record");
5159 return error(
"Invalid record");
5163 if (OpNum < Record.size()) {
5164 if (
Opc == Instruction::Add ||
5165 Opc == Instruction::Sub ||
5166 Opc == Instruction::Mul ||
5167 Opc == Instruction::Shl) {
5172 }
else if (
Opc == Instruction::SDiv ||
5173 Opc == Instruction::UDiv ||
5174 Opc == Instruction::LShr ||
5175 Opc == Instruction::AShr) {
5178 }
else if (
Opc == Instruction::Or) {
5184 I->setFastMathFlags(FMF);
5193 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5194 OpNum + 1 > Record.size())
5195 return error(
"Invalid record");
5197 ResTypeID = Record[OpNum++];
5198 Type *ResTy = getTypeByID(ResTypeID);
5201 if (
Opc == -1 || !ResTy)
5202 return error(
"Invalid record");
5207 assert(CurBB &&
"No current BB?");
5213 return error(
"Invalid cast");
5217 if (OpNum < Record.size()) {
5218 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5221 }
else if (
Opc == Instruction::Trunc) {
5230 I->setFastMathFlags(FMF);
5248 TyID = Record[OpNum++];
5249 Ty = getTypeByID(TyID);
5253 TyID = InvalidTypeID;
5258 unsigned BasePtrTypeID;
5259 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5261 return error(
"Invalid record");
5264 TyID = getContainedTypeID(BasePtrTypeID);
5265 if (
BasePtr->getType()->isVectorTy())
5266 TyID = getContainedTypeID(TyID);
5267 Ty = getTypeByID(TyID);
5270 SmallVector<Value*, 16> GEPIdx;
5271 while (OpNum != Record.size()) {
5274 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5275 return error(
"Invalid record");
5286 unsigned SubType = 0;
5287 if (GTI.isStruct()) {
5289 Idx->getType()->isVectorTy()
5291 :
cast<ConstantInt>(Idx);
5294 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5301 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5302 if (
I->getType()->isVectorTy())
5303 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5306 GEP->setNoWrapFlags(NW);
5315 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5316 return error(
"Invalid record");
5319 unsigned RecSize = Record.size();
5320 if (OpNum == RecSize)
5321 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5323 SmallVector<unsigned, 4> EXTRACTVALIdx;
5324 ResTypeID = AggTypeID;
5325 for (; OpNum != RecSize; ++OpNum) {
5328 uint64_t
Index = Record[OpNum];
5330 if (!IsStruct && !IsArray)
5331 return error(
"EXTRACTVAL: Invalid type");
5332 if ((
unsigned)Index != Index)
5333 return error(
"Invalid value");
5335 return error(
"EXTRACTVAL: Invalid struct index");
5337 return error(
"EXTRACTVAL: Invalid array index");
5338 EXTRACTVALIdx.
push_back((
unsigned)Index);
5342 ResTypeID = getContainedTypeID(ResTypeID, Index);
5345 ResTypeID = getContainedTypeID(ResTypeID);
5359 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5360 return error(
"Invalid record");
5363 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5364 return error(
"Invalid record");
5366 unsigned RecSize = Record.size();
5367 if (OpNum == RecSize)
5368 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5370 SmallVector<unsigned, 4> INSERTVALIdx;
5372 for (; OpNum != RecSize; ++OpNum) {
5375 uint64_t
Index = Record[OpNum];
5377 if (!IsStruct && !IsArray)
5378 return error(
"INSERTVAL: Invalid type");
5379 if ((
unsigned)Index != Index)
5380 return error(
"Invalid value");
5382 return error(
"INSERTVAL: Invalid struct index");
5384 return error(
"INSERTVAL: Invalid array index");
5386 INSERTVALIdx.
push_back((
unsigned)Index);
5394 return error(
"Inserted value type doesn't match aggregate type");
5397 ResTypeID = AggTypeID;
5409 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5411 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5413 popValue(Record, OpNum, NextValueNo, CondType,
5414 getVirtualTypeID(CondType),
Cond, CurBB))
5415 return error(
"Invalid record");
5428 unsigned ValTypeID, CondTypeID;
5429 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5431 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5433 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5434 return error(
"Invalid record");
5437 if (VectorType* vector_type =
5440 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5441 return error(
"Invalid type for value");
5445 return error(
"Invalid type for value");
5449 ResTypeID = ValTypeID;
5454 I->setFastMathFlags(FMF);
5462 unsigned VecTypeID, IdxTypeID;
5463 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5464 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5465 return error(
"Invalid record");
5467 return error(
"Invalid type for value");
5469 ResTypeID = getContainedTypeID(VecTypeID);
5476 Value *Vec, *Elt, *Idx;
5477 unsigned VecTypeID, IdxTypeID;
5478 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5479 return error(
"Invalid record");
5481 return error(
"Invalid type for value");
5482 if (popValue(Record, OpNum, NextValueNo,
5484 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5485 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5486 return error(
"Invalid record");
5488 ResTypeID = VecTypeID;
5496 unsigned Vec1TypeID;
5497 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5499 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5501 return error(
"Invalid record");
5503 unsigned MaskTypeID;
5504 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5505 return error(
"Invalid record");
5507 return error(
"Invalid type for value");
5509 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5511 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5526 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5527 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5529 return error(
"Invalid record");
5531 if (OpNum >= Record.size())
5533 "Invalid record: operand number exceeded available operands");
5538 if (IsFP && Record.size() > OpNum+1)
5543 return error(
"Invalid fcmp predicate");
5544 I =
new FCmpInst(PredVal,
LHS,
RHS);
5547 return error(
"Invalid icmp predicate");
5548 I =
new ICmpInst(PredVal,
LHS,
RHS);
5549 if (Record.size() > OpNum + 1 &&
5554 if (OpNum + 1 != Record.size())
5555 return error(
"Invalid record");
5557 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5559 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5562 I->setFastMathFlags(FMF);
5569 unsigned Size = Record.size();
5579 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5580 return error(
"Invalid record");
5581 if (OpNum != Record.size())
5582 return error(
"Invalid record");
5589 if (Record.size() != 1 && Record.size() != 3)
5590 return error(
"Invalid record");
5591 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5593 return error(
"Invalid record");
5595 if (Record.size() == 1) {
5600 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5602 Value *
Cond = getValue(Record, 2, NextValueNo, CondType,
5603 getVirtualTypeID(CondType), CurBB);
5604 if (!FalseDest || !
Cond)
5605 return error(
"Invalid record");
5612 if (Record.size() != 1 && Record.size() != 2)
5613 return error(
"Invalid record");
5616 Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5617 getVirtualTypeID(TokenTy), CurBB);
5619 return error(
"Invalid record");
5621 if (Record.size() == 2) {
5622 UnwindDest = getBasicBlock(Record[Idx++]);
5624 return error(
"Invalid record");
5632 if (Record.size() != 2)
5633 return error(
"Invalid record");
5636 Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5637 getVirtualTypeID(TokenTy), CurBB);
5639 return error(
"Invalid record");
5640 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5642 return error(
"Invalid record");
5650 if (Record.size() < 2)
5651 return error(
"Invalid record");
5656 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5657 getVirtualTypeID(TokenTy), CurBB);
5659 return error(
"Invalid record");
5661 unsigned NumHandlers = Record[Idx++];
5664 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5665 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5667 return error(
"Invalid record");
5672 if (Idx + 1 == Record.size()) {
5673 UnwindDest = getBasicBlock(Record[Idx++]);
5675 return error(
"Invalid record");
5678 if (Record.size() != Idx)
5679 return error(
"Invalid record");
5683 for (BasicBlock *Handler : Handlers)
5684 CatchSwitch->addHandler(Handler);
5686 ResTypeID = getVirtualTypeID(
I->getType());
5693 if (Record.size() < 2)
5694 return error(
"Invalid record");
5699 Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5700 getVirtualTypeID(TokenTy), CurBB);
5702 return error(
"Invald record");
5704 unsigned NumArgOperands = Record[Idx++];
5706 SmallVector<Value *, 2>
Args;
5707 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5710 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5711 return error(
"Invalid record");
5712 Args.push_back(Val);
5715 if (Record.size() != Idx)
5716 return error(
"Invalid record");
5722 ResTypeID = getVirtualTypeID(
I->getType());
5728 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5734 unsigned OpTyID = Record[1];
5735 Type *OpTy = getTypeByID(OpTyID);
5738 Value *
Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
5741 return error(
"Invalid record");
5743 unsigned NumCases = Record[4];
5748 unsigned CurIdx = 5;
5749 for (
unsigned i = 0; i != NumCases; ++i) {
5751 unsigned NumItems = Record[CurIdx++];
5752 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5753 bool isSingleNumber = Record[CurIdx++];
5756 unsigned ActiveWords = 1;
5757 if (ValueBitWidth > 64)
5758 ActiveWords = Record[CurIdx++];
5761 CurIdx += ActiveWords;
5763 if (!isSingleNumber) {
5765 if (ValueBitWidth > 64)
5766 ActiveWords = Record[CurIdx++];
5769 CurIdx += ActiveWords;
5780 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5781 for (ConstantInt *Cst : CaseVals)
5782 SI->addCase(Cst, DestBB);
5790 if (Record.size() < 3 || (Record.size() & 1) == 0)
5791 return error(
"Invalid record");
5792 unsigned OpTyID = Record[0];
5793 Type *OpTy = getTypeByID(OpTyID);
5794 Value *
Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5797 return error(
"Invalid record");
5798 unsigned NumCases = (Record.size()-3)/2;
5801 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
5803 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
5804 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5805 if (!CaseVal || !DestBB) {
5807 return error(
"Invalid record");
5809 SI->addCase(CaseVal, DestBB);
5815 if (Record.size() < 2)
5816 return error(
"Invalid record");
5817 unsigned OpTyID = Record[0];
5818 Type *OpTy = getTypeByID(OpTyID);
5819 Value *
Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5821 return error(
"Invalid record");
5822 unsigned NumDests = Record.size()-2;
5825 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
5826 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5830 return error(
"Invalid record");
5839 if (Record.size() < 4)
5840 return error(
"Invalid record");
5843 unsigned CCInfo = Record[OpNum++];
5844 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5845 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5847 unsigned FTyID = InvalidTypeID;
5848 FunctionType *FTy =
nullptr;
5849 if ((CCInfo >> 13) & 1) {
5850 FTyID = Record[OpNum++];
5853 return error(
"Explicit invoke type is not a function type");
5857 unsigned CalleeTypeID;
5858 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5860 return error(
"Invalid record");
5864 return error(
"Callee is not a pointer");
5866 FTyID = getContainedTypeID(CalleeTypeID);
5869 return error(
"Callee is not of pointer to function type");
5871 if (Record.size() < FTy->getNumParams() + OpNum)
5872 return error(
"Insufficient operands to call");
5874 SmallVector<Value*, 16>
Ops;
5875 SmallVector<unsigned, 16> ArgTyIDs;
5876 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5877 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5878 Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5882 return error(
"Invalid record");
5885 if (!FTy->isVarArg()) {
5886 if (Record.size() != OpNum)
5887 return error(
"Invalid record");
5890 while (OpNum != Record.size()) {
5893 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5894 return error(
"Invalid record");
5901 if (!OperandBundles.empty())
5906 ResTypeID = getContainedTypeID(FTyID);
5907 OperandBundles.clear();
5910 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
5921 Value *Val =
nullptr;
5923 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5924 return error(
"Invalid record");
5933 unsigned CCInfo = Record[OpNum++];
5935 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5936 unsigned NumIndirectDests = Record[OpNum++];
5937 SmallVector<BasicBlock *, 16> IndirectDests;
5938 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
5939 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
5941 unsigned FTyID = InvalidTypeID;
5942 FunctionType *FTy =
nullptr;
5944 FTyID = Record[OpNum++];
5947 return error(
"Explicit call type is not a function type");
5951 unsigned CalleeTypeID;
5952 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5954 return error(
"Invalid record");
5958 return error(
"Callee is not a pointer type");
5960 FTyID = getContainedTypeID(CalleeTypeID);
5963 return error(
"Callee is not of pointer to function type");
5965 if (Record.size() < FTy->getNumParams() + OpNum)
5966 return error(
"Insufficient operands to call");
5968 SmallVector<Value*, 16>
Args;
5969 SmallVector<unsigned, 16> ArgTyIDs;
5971 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5973 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5974 if (FTy->getParamType(i)->isLabelTy())
5975 Arg = getBasicBlock(Record[OpNum]);
5977 Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5980 return error(
"Invalid record");
5981 Args.push_back(Arg);
5986 if (!FTy->isVarArg()) {
5987 if (OpNum != Record.size())
5988 return error(
"Invalid record");
5990 while (OpNum != Record.size()) {
5993 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5994 return error(
"Invalid record");
6001 if (!OperandBundles.empty())
6006 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6009 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6014 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6015 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6016 unsigned LabelNo = ArgNo - FirstBlockArg;
6018 if (!BA || BA->getFunction() !=
F ||
6019 LabelNo > IndirectDests.
size() ||
6020 BA->getBasicBlock() != IndirectDests[LabelNo])
6021 return error(
"callbr argument does not match indirect dest");
6026 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6030 for (
Value *Arg : Args)
6033 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6036 std::string Constraints =
IA->getConstraintString().str();
6039 for (
const auto &CI : ConstraintInfo) {
6041 if (ArgNo >= FirstBlockArg)
6042 Constraints.insert(Pos,
"!");
6047 Pos = Constraints.find(
',', Pos);
6048 if (Pos == std::string::npos)
6054 IA->hasSideEffects(),
IA->isAlignStack(),
6055 IA->getDialect(),
IA->canThrow());
6061 ResTypeID = getContainedTypeID(FTyID);
6062 OperandBundles.clear();
6079 return error(
"Invalid phi record");
6081 unsigned TyID = Record[0];
6082 Type *Ty = getTypeByID(TyID);
6084 return error(
"Invalid phi record");
6089 size_t NumArgs = (Record.size() - 1) / 2;
6093 return error(
"Invalid phi record");
6097 SmallDenseMap<BasicBlock *, Value *>
Args;
6098 for (
unsigned i = 0; i != NumArgs; i++) {
6099 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6102 return error(
"Invalid phi BB");
6109 auto It =
Args.find(BB);
6111 if (It !=
Args.end()) {
6125 if (!PhiConstExprBB)
6127 EdgeBB = PhiConstExprBB;
6135 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6137 V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6141 return error(
"Invalid phi record");
6144 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6145 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6146 PhiConstExprBB =
nullptr;
6149 Args.insert({BB,
V});
6155 if (Record.size() % 2 == 0) {
6159 I->setFastMathFlags(FMF);
6170 if (Record.size() < 3)
6171 return error(
"Invalid record");
6174 if (Record.size() < 4)
6175 return error(
"Invalid record");
6177 ResTypeID = Record[Idx++];
6178 Type *Ty = getTypeByID(ResTypeID);
6180 return error(
"Invalid record");
6182 Value *PersFn =
nullptr;
6183 unsigned PersFnTypeID;
6184 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6186 return error(
"Invalid record");
6188 if (!
F->hasPersonalityFn())
6191 return error(
"Personality function mismatch");
6194 bool IsCleanup = !!Record[Idx++];
6195 unsigned NumClauses = Record[Idx++];
6198 for (
unsigned J = 0; J != NumClauses; ++J) {
6204 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6207 return error(
"Invalid record");
6212 "Catch clause has a invalid type!");
6215 "Filter clause has invalid type!");
6225 if (Record.size() != 4 && Record.size() != 5)
6226 return error(
"Invalid record");
6227 using APV = AllocaPackedValues;
6228 const uint64_t Rec = Record[3];
6231 unsigned TyID = Record[0];
6232 Type *Ty = getTypeByID(TyID);
6234 TyID = getContainedTypeID(TyID);
6235 Ty = getTypeByID(TyID);
6237 return error(
"Missing element type for old-style alloca");
6239 unsigned OpTyID = Record[1];
6240 Type *OpTy = getTypeByID(OpTyID);
6241 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6246 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6250 return error(
"Invalid record");
6252 const DataLayout &
DL = TheModule->getDataLayout();
6253 unsigned AS = Record.
size() == 5 ? Record[4] :
DL.getAllocaAddrSpace();
6255 SmallPtrSet<Type *, 4> Visited;
6256 if (!Align && !Ty->
isSized(&Visited))
6257 return error(
"alloca of unsized type");
6259 Align =
DL.getPrefTypeAlign(Ty);
6261 if (!
Size->getType()->isIntegerTy())
6262 return error(
"alloca element count must have integer type");
6264 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6268 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6276 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6277 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
6278 return error(
"Invalid record");
6281 return error(
"Load operand is not a pointer type");
6284 if (OpNum + 3 == Record.size()) {
6285 ResTypeID = Record[OpNum++];
6286 Ty = getTypeByID(ResTypeID);
6288 ResTypeID = getContainedTypeID(OpTypeID);
6289 Ty = getTypeByID(ResTypeID);
6293 return error(
"Missing load type");
6295 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6299 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6301 SmallPtrSet<Type *, 4> Visited;
6302 if (!Align && !Ty->
isSized(&Visited))
6303 return error(
"load of unsized type");
6305 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6306 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6315 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6316 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
6317 return error(
"Invalid record");
6320 return error(
"Load operand is not a pointer type");
6323 if (OpNum + 5 == Record.size()) {
6324 ResTypeID = Record[OpNum++];
6325 Ty = getTypeByID(ResTypeID);
6327 ResTypeID = getContainedTypeID(OpTypeID);
6328 Ty = getTypeByID(ResTypeID);
6332 return error(
"Missing atomic load type");
6334 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6338 if (Ordering == AtomicOrdering::NotAtomic ||
6339 Ordering == AtomicOrdering::Release ||
6340 Ordering == AtomicOrdering::AcquireRelease)
6341 return error(
"Invalid record");
6342 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6343 return error(
"Invalid record");
6344 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6347 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6350 return error(
"Alignment missing from atomic load");
6351 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align, Ordering, SSID);
6359 unsigned PtrTypeID, ValTypeID;
6360 if (getValueTypePair(Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6361 return error(
"Invalid record");
6364 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6365 return error(
"Invalid record");
6367 ValTypeID = getContainedTypeID(PtrTypeID);
6368 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6369 ValTypeID, Val, CurBB))
6370 return error(
"Invalid record");
6373 if (OpNum + 2 != Record.size())
6374 return error(
"Invalid record");
6376 if (
Error Err = typeCheckLoadStoreInst(Val->
getType(),
Ptr->getType()))
6379 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6381 SmallPtrSet<Type *, 4> Visited;
6383 return error(
"store of unsized type");
6385 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6386 I =
new StoreInst(Val,
Ptr, Record[OpNum + 1], *Align);
6395 unsigned PtrTypeID, ValTypeID;
6396 if (getValueTypePair(Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB) ||
6398 return error(
"Invalid record");
6400 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6401 return error(
"Invalid record");
6403 ValTypeID = getContainedTypeID(PtrTypeID);
6404 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6405 ValTypeID, Val, CurBB))
6406 return error(
"Invalid record");
6409 if (OpNum + 4 != Record.size())
6410 return error(
"Invalid record");
6412 if (
Error Err = typeCheckLoadStoreInst(Val->
getType(),
Ptr->getType()))
6415 if (Ordering == AtomicOrdering::NotAtomic ||
6416 Ordering == AtomicOrdering::Acquire ||
6417 Ordering == AtomicOrdering::AcquireRelease)
6418 return error(
"Invalid record");
6419 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6420 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6421 return error(
"Invalid record");
6424 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6427 return error(
"Alignment missing from atomic store");
6428 I =
new StoreInst(Val,
Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6435 const size_t NumRecords = Record.size();
6439 if (getValueTypePair(Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6440 return error(
"Invalid record");
6443 return error(
"Cmpxchg operand is not a pointer type");
6446 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6447 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6448 CmpTypeID, Cmp, CurBB))
6449 return error(
"Invalid record");
6452 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6454 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6455 return error(
"Invalid record");
6459 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6460 SuccessOrdering == AtomicOrdering::Unordered)
6461 return error(
"Invalid record");
6463 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6465 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(),
Ptr->getType()))
6473 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6474 FailureOrdering == AtomicOrdering::Unordered)
6475 return error(
"Invalid record");
6477 const Align Alignment(
6478 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6480 I =
new AtomicCmpXchgInst(
Ptr, Cmp, New, Alignment, SuccessOrdering,
6481 FailureOrdering, SSID);
6484 if (NumRecords < 8) {
6488 I->insertInto(CurBB, CurBB->
end());
6490 ResTypeID = CmpTypeID;
6493 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6494 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6503 const size_t NumRecords = Record.size();
6507 if (getValueTypePair(Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6508 return error(
"Invalid record");
6511 return error(
"Cmpxchg operand is not a pointer type");
6515 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6516 return error(
"Invalid record");
6518 Value *Val =
nullptr;
6519 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6521 return error(
"Invalid record");
6523 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6524 return error(
"Invalid record");
6526 const bool IsVol = Record[OpNum];
6531 return error(
"Invalid cmpxchg success ordering");
6533 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6535 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(),
Ptr->getType()))
6541 return error(
"Invalid cmpxchg failure ordering");
6543 const bool IsWeak = Record[OpNum + 4];
6545 MaybeAlign Alignment;
6547 if (NumRecords == (OpNum + 6)) {
6548 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6553 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6555 I =
new AtomicCmpXchgInst(
Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6556 FailureOrdering, SSID);
6560 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6561 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6570 const size_t NumRecords = Record.size();
6575 if (getValueTypePair(Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6576 return error(
"Invalid record");
6579 return error(
"Invalid record");
6581 Value *Val =
nullptr;
6582 unsigned ValTypeID = InvalidTypeID;
6584 ValTypeID = getContainedTypeID(PtrTypeID);
6585 if (popValue(Record, OpNum, NextValueNo,
6586 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6587 return error(
"Invalid record");
6589 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6590 return error(
"Invalid record");
6593 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6594 return error(
"Invalid record");
6600 return error(
"Invalid record");
6602 const bool IsVol = Record[OpNum + 1];
6605 if (Ordering == AtomicOrdering::NotAtomic ||
6606 Ordering == AtomicOrdering::Unordered)
6607 return error(
"Invalid record");
6609 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6611 MaybeAlign Alignment;
6613 if (NumRecords == (OpNum + 5)) {
6614 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6620 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6622 I =
new AtomicRMWInst(
Operation,
Ptr, Val, *Alignment, Ordering, SSID);
6623 ResTypeID = ValTypeID;
6630 if (2 != Record.size())
6631 return error(
"Invalid record");
6633 if (Ordering == AtomicOrdering::NotAtomic ||
6634 Ordering == AtomicOrdering::Unordered ||
6635 Ordering == AtomicOrdering::Monotonic)
6636 return error(
"Invalid record");
6638 I =
new FenceInst(
Context, Ordering, SSID);
6645 SeenDebugRecord =
true;
6648 return error(
"Invalid dbg record: missing instruction");
6651 Inst->
getParent()->insertDbgRecordBefore(
6661 SeenDebugRecord =
true;
6664 return error(
"Invalid dbg record: missing instruction");
6679 DILocalVariable *Var =
6681 DIExpression *Expr =
6694 unsigned SlotBefore =
Slot;
6695 if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6696 return error(
"Invalid dbg record: invalid value");
6698 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6701 RawLocation = getFnMetadataByID(Record[Slot++]);
6704 DbgVariableRecord *DVR =
nullptr;
6708 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6709 DbgVariableRecord::LocationType::Value);
6712 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6713 DbgVariableRecord::LocationType::Declare);
6717 DIExpression *AddrExpr =
6719 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6720 DVR =
new DbgVariableRecord(RawLocation, Var, Expr,
ID, Addr, AddrExpr,
6732 if (Record.size() < 3)
6733 return error(
"Invalid record");
6737 unsigned CCInfo = Record[OpNum++];
6743 return error(
"Fast math flags indicator set for call with no FMF");
6746 unsigned FTyID = InvalidTypeID;
6747 FunctionType *FTy =
nullptr;
6749 FTyID = Record[OpNum++];
6752 return error(
"Explicit call type is not a function type");
6756 unsigned CalleeTypeID;
6757 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6759 return error(
"Invalid record");
6763 return error(
"Callee is not a pointer type");
6765 FTyID = getContainedTypeID(CalleeTypeID);
6768 return error(
"Callee is not of pointer to function type");
6770 if (Record.size() < FTy->getNumParams() + OpNum)
6771 return error(
"Insufficient operands to call");
6773 SmallVector<Value*, 16>
Args;
6774 SmallVector<unsigned, 16> ArgTyIDs;
6776 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6777 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6778 if (FTy->getParamType(i)->isLabelTy())
6779 Args.push_back(getBasicBlock(Record[OpNum]));
6781 Args.push_back(getValue(Record, OpNum, NextValueNo,
6782 FTy->getParamType(i), ArgTyID, CurBB));
6785 return error(
"Invalid record");
6789 if (!FTy->isVarArg()) {
6790 if (OpNum != Record.size())
6791 return error(
"Invalid record");
6793 while (OpNum != Record.size()) {
6796 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6797 return error(
"Invalid record");
6804 if (!OperandBundles.empty())
6808 ResTypeID = getContainedTypeID(FTyID);
6809 OperandBundles.clear();
6823 SeenDebugIntrinsic =
true;
6830 return error(
"Fast-math-flags specified for call without "
6831 "floating-point scalar or vector return type");
6832 I->setFastMathFlags(FMF);
6837 if (Record.size() < 3)
6838 return error(
"Invalid record");
6839 unsigned OpTyID = Record[0];
6840 Type *OpTy = getTypeByID(OpTyID);
6841 Value *
Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6842 ResTypeID = Record[2];
6843 Type *ResTy = getTypeByID(ResTypeID);
6844 if (!OpTy || !
Op || !ResTy)
6845 return error(
"Invalid record");
6846 I =
new VAArgInst(
Op, ResTy);
6856 if (Record.empty() || Record[0] >= BundleTags.size())
6857 return error(
"Invalid record");
6859 std::vector<Value *> Inputs;
6862 while (OpNum != Record.size()) {
6864 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
6865 return error(
"Invalid record");
6866 Inputs.push_back(
Op);
6869 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6877 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6878 return error(
"Invalid record");
6879 if (OpNum != Record.size())
6880 return error(
"Invalid record");
6882 I =
new FreezeInst(
Op);
6883 ResTypeID = OpTypeID;
6893 return error(
"Invalid instruction with no BB");
6895 if (!OperandBundles.empty()) {
6897 return error(
"Operand bundles found with no consumer");
6899 I->insertInto(CurBB, CurBB->
end());
6902 if (
I->isTerminator()) {
6904 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
6908 if (!
I->getType()->isVoidTy()) {
6909 assert(
I->getType() == getTypeByID(ResTypeID) &&
6910 "Incorrect result type ID");
6918 if (!OperandBundles.empty())
6919 return error(
"Operand bundles found with no consumer");
6923 if (!
A->getParent()) {
6925 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
6931 return error(
"Never resolved value found in function");
6936 if (MDLoader->hasFwdRefs())
6937 return error(
"Invalid function metadata: outgoing forward refs");
6942 for (
const auto &Pair : ConstExprEdgeBBs) {
6953 ValueList.
shrinkTo(ModuleValueListSize);
6954 MDLoader->shrinkTo(ModuleMDLoaderSize);
6955 std::vector<BasicBlock*>().swap(FunctionBBs);
6960Error BitcodeReader::findFunctionInStream(
6962 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
6963 while (DeferredFunctionInfoIterator->second == 0) {
6968 assert(VSTOffset == 0 || !
F->hasName());
6971 if (
Error Err = rememberAndSkipFunctionBodies())
6977SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
6980 if (Val >= SSIDs.
size())
6989Error BitcodeReader::materialize(GlobalValue *GV) {
6992 if (!
F || !
F->isMaterializable())
6995 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.
find(
F);
6996 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
6999 if (DFII->second == 0)
7000 if (
Error Err = findFunctionInStream(
F, DFII))
7004 if (
Error Err = materializeMetadata())
7008 if (
Error JumpFailed = Stream.JumpToBit(DFII->second))
7011 if (
Error Err = parseFunctionBody(
F))
7013 F->setIsMaterializable(
false);
7017 if (SeenDebugIntrinsic && SeenDebugRecord)
7018 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7024 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7025 F->setSubprogram(SP);
7028 if (!MDLoader->isStrippingTBAA()) {
7030 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7033 MDLoader->setStripTBAA(
true);
7040 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7041 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7047 unsigned ExpectedNumOperands = 0;
7049 ExpectedNumOperands = BI->getNumSuccessors();
7051 ExpectedNumOperands =
SI->getNumSuccessors();
7053 ExpectedNumOperands = 1;
7057 ExpectedNumOperands = 2;
7064 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7065 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7071 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7072 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7074 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7075 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7076 CI->getArgOperand(ArgNo)->getType(),
7077 CI->getParamAttributes(ArgNo)));
7080 if (Function *OldFn = CI->getCalledFunction()) {
7081 auto It = UpgradedIntrinsics.find(OldFn);
7082 if (It != UpgradedIntrinsics.end())
7093 return materializeForwardReferencedFunctions();
7096Error BitcodeReader::materializeModule() {
7097 if (
Error Err = materializeMetadata())
7101 WillMaterializeAllForwardRefs =
true;
7105 for (Function &
F : *TheModule) {
7106 if (
Error Err = materialize(&
F))
7112 if (LastFunctionBlockBit || NextUnreadBit)
7114 ? LastFunctionBlockBit
7120 if (!BasicBlockFwdRefs.
empty())
7121 return error(
"Never resolved function from blockaddress");
7127 for (
auto &
I : UpgradedIntrinsics) {
7128 for (
auto *U :
I.first->users()) {
7132 if (
I.first !=
I.second) {
7133 if (!
I.first->use_empty())
7134 I.first->replaceAllUsesWith(
I.second);
7135 I.first->eraseFromParent();
7138 UpgradedIntrinsics.clear();
7153std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7154 return IdentifiedStructTypes;
7157ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7158 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7160 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7161 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7163void ModuleSummaryIndexBitcodeReader::addThisModule() {
7168ModuleSummaryIndexBitcodeReader::getThisModule() {
7172template <
bool AllowNullValueInfo>
7173std::pair<ValueInfo, GlobalValue::GUID>
7174ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7175 auto VGI = ValueIdToValueInfoMap[ValueId];
7180 assert(AllowNullValueInfo || std::get<0>(VGI));
7184void ModuleSummaryIndexBitcodeReader::setValueGUID(
7186 StringRef SourceFileName) {
7187 std::string GlobalId =
7190 auto OriginalNameID = ValueGUID;
7194 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7200 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7209Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7211 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7218 if (!MaybeCurrentBit)
7220 uint64_t CurrentBit = MaybeCurrentBit.
get();
7225 SmallVector<uint64_t, 64> Record;
7231 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7234 BitstreamEntry
Entry = MaybeEntry.
get();
7236 switch (
Entry.Kind) {
7239 return error(
"Malformed block");
7242 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
7252 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
7255 switch (MaybeRecord.
get()) {
7260 return error(
"Invalid record");
7261 unsigned ValueID = Record[0];
7263 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7264 assert(VLI != ValueIdToLinkageMap.
end() &&
7265 "No linkage found for VST entry?");
7274 return error(
"Invalid record");
7275 unsigned ValueID = Record[0];
7277 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7278 assert(VLI != ValueIdToLinkageMap.
end() &&
7279 "No linkage found for VST entry?");
7287 unsigned ValueID = Record[0];
7291 ValueIdToValueInfoMap[ValueID] =
7302Error ModuleSummaryIndexBitcodeReader::parseModule() {
7306 SmallVector<uint64_t, 64> Record;
7307 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7308 unsigned ValueId = 0;
7312 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7315 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7317 switch (
Entry.Kind) {
7319 return error(
"Malformed block");
7326 if (
Error Err = Stream.SkipBlock())
7331 if (
Error Err = readBlockInfo())
7337 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7338 !SeenGlobalValSummary) &&
7339 "Expected early VST parse via VSTOffset record");
7340 if (
Error Err = Stream.SkipBlock())
7346 if (!SourceFileName.
empty())
7348 assert(!SeenValueSymbolTable &&
7349 "Already read VST when parsing summary block?");
7354 if (VSTOffset > 0) {
7355 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7357 SeenValueSymbolTable =
true;
7359 SeenGlobalValSummary =
true;
7360 if (
Error Err = parseEntireSummary(
Entry.ID))
7364 if (
Error Err = parseModuleStringTable())
7372 Expected<unsigned> MaybeBitCode = Stream.readRecord(
Entry.ID, Record);
7375 switch (MaybeBitCode.
get()) {
7379 if (
Error Err = parseVersionRecord(Record).takeError())
7387 return error(
"Invalid record");
7393 if (Record.
size() != 5)
7394 return error(
"Invalid hash length " + Twine(Record.
size()).str());
7395 auto &Hash = getThisModule()->second;
7397 for (
auto &Val : Record) {
7398 assert(!(Val >> 32) &&
"Unexpected high bits set");
7406 return error(
"Invalid record");
7410 VSTOffset = Record[0] - 1;
7420 ArrayRef<uint64_t> GVRecord;
7421 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7422 if (GVRecord.
size() <= 3)
7423 return error(
"Invalid record");
7424 uint64_t RawLinkage = GVRecord[3];
7427 ValueIdToLinkageMap[ValueId++] =
Linkage;
7431 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7442ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7445 for (uint64_t RefValueId : Record)
7446 Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7451ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7452 bool IsOldProfileFormat,
7453 bool HasProfile,
bool HasRelBF) {
7457 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7458 Ret.reserve(Record.
size() / 2);
7462 for (
unsigned I = 0,
E = Record.
size();
I !=
E; ++
I) {
7464 bool HasTailCall =
false;
7466 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7467 if (IsOldProfileFormat) {
7471 }
else if (HasProfile)
7472 std::tie(Hotness, HasTailCall) =
7477 Callee, CalleeInfo(Hotness, HasTailCall, RelBF)});
7505 static_cast<size_t>(
Record[Slot + 1])};
7528 while (Slot <
Record.size())
7532std::vector<FunctionSummary::ParamAccess>
7533ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7534 auto ReadRange = [&]() {
7536 BitcodeReader::decodeSignRotatedValue(Record.
consume_front()));
7538 BitcodeReader::decodeSignRotatedValue(Record.
consume_front()));
7545 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7546 while (!Record.
empty()) {
7547 PendingParamAccesses.emplace_back();
7548 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7550 ParamAccess.
Use = ReadRange();
7555 std::get<0>(getValueInfoFromValueId(Record.
consume_front()));
7556 Call.Offsets = ReadRange();
7559 return PendingParamAccesses;
7562void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7563 ArrayRef<uint64_t> Record,
size_t &Slot,
7566 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7570void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7571 ArrayRef<uint64_t> Record) {
7576 static_cast<size_t>(Record[
Slot + 1])});
7579 while (Slot < Record.
size())
7580 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7583SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7584 ArrayRef<uint64_t> Record,
unsigned &
I) {
7585 SmallVector<unsigned> StackIdList;
7589 if (RadixArray.empty()) {
7590 unsigned NumStackEntries = Record[
I++];
7592 StackIdList.
reserve(NumStackEntries);
7593 for (
unsigned J = 0; J < NumStackEntries; J++) {
7594 assert(Record[
I] < StackIds.size());
7599 unsigned RadixIndex = Record[
I++];
7605 assert(RadixIndex < RadixArray.size());
7606 unsigned NumStackIds = RadixArray[RadixIndex++];
7607 StackIdList.
reserve(NumStackIds);
7608 while (NumStackIds--) {
7609 assert(RadixIndex < RadixArray.size());
7610 unsigned Elem = RadixArray[RadixIndex];
7611 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7612 RadixIndex = RadixIndex - Elem;
7613 assert(RadixIndex < RadixArray.size());
7614 Elem = RadixArray[RadixIndex];
7616 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7629 unsigned FirstWORef = Refs.
size() - WOCnt;
7630 unsigned RefNo = FirstWORef - ROCnt;
7631 for (; RefNo < FirstWORef; ++RefNo)
7632 Refs[RefNo].setReadOnly();
7633 for (; RefNo < Refs.
size(); ++RefNo)
7634 Refs[RefNo].setWriteOnly();
7639Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7640 if (
Error Err = Stream.EnterSubBlock(
ID))
7642 SmallVector<uint64_t, 64> Record;
7646 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7649 BitstreamEntry
Entry = MaybeEntry.
get();
7652 return error(
"Invalid Summary Block: record for version expected");
7653 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
7657 return error(
"Invalid Summary Block: version expected");
7659 const uint64_t
Version = Record[0];
7660 const bool IsOldProfileFormat =
Version == 1;
7662 return error(
"Invalid summary version " + Twine(
Version) +
7663 ". Version should be in the range [1-" +
7670 GlobalValueSummary *LastSeenSummary =
nullptr;
7676 std::vector<GlobalValue::GUID> PendingTypeTests;
7677 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7678 PendingTypeCheckedLoadVCalls;
7679 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7680 PendingTypeCheckedLoadConstVCalls;
7681 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7683 std::vector<CallsiteInfo> PendingCallsites;
7684 std::vector<AllocInfo> PendingAllocs;
7685 std::vector<uint64_t> PendingContextIds;
7688 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7691 BitstreamEntry
Entry = MaybeEntry.
get();
7693 switch (
Entry.Kind) {
7696 return error(
"Malformed block");
7712 Expected<unsigned> MaybeBitCode = Stream.readRecord(
Entry.ID, Record);
7715 switch (
unsigned BitCode = MaybeBitCode.
get()) {
7723 uint64_t ValueID = Record[0];
7726 RefGUID = Record[1] << 32 | Record[2];
7728 RefGUID = Record[1];
7730 ValueIdToValueInfoMap[ValueID] =
7746 unsigned ValueID = Record[0];
7747 uint64_t RawFlags = Record[1];
7748 unsigned InstCount = Record[2];
7749 uint64_t RawFunFlags = 0;
7750 unsigned NumRefs = Record[3];
7751 unsigned NumRORefs = 0, NumWORefs = 0;
7752 int RefListStartIndex = 4;
7754 RawFunFlags = Record[3];
7755 NumRefs = Record[4];
7756 RefListStartIndex = 5;
7758 NumRORefs = Record[5];
7759 RefListStartIndex = 6;
7761 NumWORefs = Record[6];
7762 RefListStartIndex = 7;
7773 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7774 assert(Record.
size() >= RefListStartIndex + NumRefs &&
7775 "Record size inconsistent with number of references");
7777 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7781 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7782 IsOldProfileFormat, HasProfile, HasRelBF);
7784 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7790 !IsPrevailing(VIAndOriginalGUID.first.getGUID())) {
7791 PendingCallsites.clear();
7792 PendingAllocs.clear();
7794 auto FS = std::make_unique<FunctionSummary>(
7796 std::move(Calls), std::move(PendingTypeTests),
7797 std::move(PendingTypeTestAssumeVCalls),
7798 std::move(PendingTypeCheckedLoadVCalls),
7799 std::move(PendingTypeTestAssumeConstVCalls),
7800 std::move(PendingTypeCheckedLoadConstVCalls),
7801 std::move(PendingParamAccesses), std::move(PendingCallsites),
7802 std::move(PendingAllocs));
7803 FS->setModulePath(getThisModule()->first());
7804 FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7813 unsigned ValueID = Record[0];
7814 uint64_t RawFlags = Record[1];
7815 unsigned AliaseeID = Record[2];
7817 auto AS = std::make_unique<AliasSummary>(Flags);
7823 AS->setModulePath(getThisModule()->first());
7825 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7827 if (!AliaseeInModule)
7828 return error(
"Alias expects aliasee summary to be parsed");
7829 AS->setAliasee(AliaseeVI, AliaseeInModule);
7831 auto GUID = getValueInfoFromValueId(ValueID);
7832 AS->setOriginalName(std::get<1>(GUID));
7838 unsigned ValueID = Record[0];
7839 uint64_t RawFlags = Record[1];
7840 unsigned RefArrayStart = 2;
7841 GlobalVarSummary::GVarFlags GVF(
false,
7851 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7853 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7854 FS->setModulePath(getThisModule()->first());
7855 auto GUID = getValueInfoFromValueId(ValueID);
7856 FS->setOriginalName(std::get<1>(GUID));
7864 unsigned ValueID = Record[0];
7865 uint64_t RawFlags = Record[1];
7867 unsigned NumRefs = Record[3];
7868 unsigned RefListStartIndex = 4;
7869 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7872 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7874 for (
unsigned I = VTableListStartIndex,
E = Record.
size();
I !=
E; ++
I) {
7875 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7876 uint64_t
Offset = Record[++
I];
7880 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7881 VS->setModulePath(getThisModule()->first());
7882 VS->setVTableFuncs(VTableFuncs);
7883 auto GUID = getValueInfoFromValueId(ValueID);
7884 VS->setOriginalName(std::get<1>(GUID));
7896 unsigned ValueID = Record[0];
7897 uint64_t ModuleId = Record[1];
7898 uint64_t RawFlags = Record[2];
7899 unsigned InstCount = Record[3];
7900 uint64_t RawFunFlags = 0;
7901 unsigned NumRefs = Record[4];
7902 unsigned NumRORefs = 0, NumWORefs = 0;
7903 int RefListStartIndex = 5;
7906 RawFunFlags = Record[4];
7907 RefListStartIndex = 6;
7908 size_t NumRefsIndex = 5;
7910 unsigned NumRORefsOffset = 1;
7911 RefListStartIndex = 7;
7914 RefListStartIndex = 8;
7916 RefListStartIndex = 9;
7917 NumWORefs = Record[8];
7918 NumRORefsOffset = 2;
7921 NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
7923 NumRefs = Record[NumRefsIndex];
7927 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7928 assert(Record.
size() >= RefListStartIndex + NumRefs &&
7929 "Record size inconsistent with number of references");
7931 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7934 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7935 IsOldProfileFormat, HasProfile,
false);
7936 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
7938 auto FS = std::make_unique<FunctionSummary>(
7940 std::move(Edges), std::move(PendingTypeTests),
7941 std::move(PendingTypeTestAssumeVCalls),
7942 std::move(PendingTypeCheckedLoadVCalls),
7943 std::move(PendingTypeTestAssumeConstVCalls),
7944 std::move(PendingTypeCheckedLoadConstVCalls),
7945 std::move(PendingParamAccesses), std::move(PendingCallsites),
7946 std::move(PendingAllocs));
7947 LastSeenSummary =
FS.get();
7948 LastSeenGUID =
VI.getGUID();
7949 FS->setModulePath(ModuleIdMap[ModuleId]);
7957 unsigned ValueID = Record[0];
7958 uint64_t ModuleId = Record[1];
7959 uint64_t RawFlags = Record[2];
7960 unsigned AliaseeValueId = Record[3];
7962 auto AS = std::make_unique<AliasSummary>(Flags);
7963 LastSeenSummary = AS.get();
7964 AS->setModulePath(ModuleIdMap[ModuleId]);
7966 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
7968 AS->setAliasee(AliaseeVI, AliaseeInModule);
7970 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
7971 LastSeenGUID =
VI.getGUID();
7977 unsigned ValueID = Record[0];
7978 uint64_t ModuleId = Record[1];
7979 uint64_t RawFlags = Record[2];
7980 unsigned RefArrayStart = 3;
7981 GlobalVarSummary::GVarFlags GVF(
false,
7991 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7993 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7994 LastSeenSummary =
FS.get();
7995 FS->setModulePath(ModuleIdMap[ModuleId]);
7996 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
7997 LastSeenGUID =
VI.getGUID();
8003 uint64_t OriginalName = Record[0];
8004 if (!LastSeenSummary)
8005 return error(
"Name attachment that does not follow a combined record");
8009 LastSeenSummary =
nullptr;
8014 assert(PendingTypeTests.empty());
8019 assert(PendingTypeTestAssumeVCalls.empty());
8020 for (
unsigned I = 0;
I != Record.
size();
I += 2)
8021 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8025 assert(PendingTypeCheckedLoadVCalls.empty());
8026 for (
unsigned I = 0;
I != Record.
size();
I += 2)
8027 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8031 PendingTypeTestAssumeConstVCalls.push_back(
8032 {{Record[0], Record[1]}, {Record.
begin() + 2, Record.
end()}});
8036 PendingTypeCheckedLoadConstVCalls.push_back(
8037 {{Record[0], Record[1]}, {Record.
begin() + 2, Record.
end()}});
8042 for (
unsigned I = 0;
I != Record.
size();
I += 2)
8044 static_cast<size_t>(Record[
I + 1]));
8050 for (
unsigned I = 0;
I != Record.
size();
I += 2)
8052 static_cast<size_t>(Record[
I + 1]));
8061 parseTypeIdCompatibleVtableSummaryRecord(Record);
8069 PendingParamAccesses = parseParamAccesses(Record);
8077 StackIds = ArrayRef<uint64_t>(Record);
8083 StackIds.reserve(Record.
size() / 2);
8084 for (
auto R = Record.
begin(); R != Record.
end(); R += 2)
8085 StackIds.push_back(*R << 32 | *(R + 1));
8090 RadixArray = ArrayRef<uint64_t>(Record);
8095 unsigned ValueID = Record[0];
8096 SmallVector<unsigned> StackIdList;
8098 assert(R < StackIds.size());
8101 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8102 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8107 auto RecordIter = Record.
begin();
8108 unsigned ValueID = *RecordIter++;
8109 unsigned NumStackIds = *RecordIter++;
8110 unsigned NumVersions = *RecordIter++;
8111 assert(Record.
size() == 3 + NumStackIds + NumVersions);
8112 SmallVector<unsigned> StackIdList;
8113 for (
unsigned J = 0; J < NumStackIds; J++) {
8114 assert(*RecordIter < StackIds.size());
8118 SmallVector<unsigned> Versions;
8119 for (
unsigned J = 0; J < NumVersions; J++)
8121 ValueInfo
VI = std::get<0>(
8122 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8123 PendingCallsites.push_back(
8124 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8132 PendingContextIds.reserve(Record.
size() / 2);
8133 for (
auto R = Record.
begin(); R != Record.
end(); R += 2)
8134 PendingContextIds.push_back(*R << 32 | *(R + 1));
8140 std::vector<MIBInfo> MIBs;
8141 unsigned NumMIBs = 0;
8143 NumMIBs = Record[
I++];
8144 unsigned MIBsRead = 0;
8145 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8149 auto StackIdList = parseAllocInfoContext(Record,
I);
8150 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8156 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8157 if (
I < Record.
size()) {
8158 assert(!PendingContextIds.empty() &&
8159 "Missing context ids for alloc sizes");
8160 unsigned ContextIdIndex = 0;
8166 while (MIBsRead++ < NumMIBs) {
8168 unsigned NumContextSizeInfoEntries = Record[
I++];
8169 assert(Record.
size() -
I >= NumContextSizeInfoEntries);
8170 std::vector<ContextTotalSize> ContextSizes;
8171 ContextSizes.reserve(NumContextSizeInfoEntries);
8172 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8173 assert(ContextIdIndex < PendingContextIds.size());
8175 if (PendingContextIds[ContextIdIndex] == 0) {
8184 ContextSizes.push_back(
8185 {PendingContextIds[ContextIdIndex++], Record[
I++]});
8187 AllContextSizes.push_back(std::move(ContextSizes));
8189 PendingContextIds.clear();
8191 PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
8192 if (!AllContextSizes.empty()) {
8193 assert(PendingAllocs.back().MIBs.size() == AllContextSizes.size());
8194 PendingAllocs.back().ContextSizeInfos = std::move(AllContextSizes);
8202 std::vector<MIBInfo> MIBs;
8203 unsigned NumMIBs = Record[
I++];
8204 unsigned NumVersions = Record[
I++];
8205 unsigned MIBsRead = 0;
8206 while (MIBsRead++ < NumMIBs) {
8209 SmallVector<unsigned> StackIdList;
8211 StackIdList = parseAllocInfoContext(Record,
I);
8212 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8215 SmallVector<uint8_t> Versions;
8216 for (
unsigned J = 0; J < NumVersions; J++)
8219 PendingAllocs.push_back(AllocInfo(std::move(Versions), std::move(MIBs)));
8229Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8233 SmallVector<uint64_t, 64> Record;
8235 SmallString<128> ModulePath;
8239 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
8242 BitstreamEntry
Entry = MaybeEntry.
get();
8244 switch (
Entry.Kind) {
8247 return error(
"Malformed block");
8256 Expected<unsigned> MaybeRecord = Stream.readRecord(
Entry.ID, Record);
8259 switch (MaybeRecord.
get()) {
8264 uint64_t ModuleId = Record[0];
8267 return error(
"Invalid record");
8269 LastSeenModule = TheIndex.
addModule(ModulePath);
8270 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8277 if (Record.
size() != 5)
8278 return error(
"Invalid hash length " + Twine(Record.
size()).str());
8279 if (!LastSeenModule)
8280 return error(
"Invalid hash that does not follow a module path");
8282 for (
auto &Val : Record) {
8283 assert(!(Val >> 32) &&
"Unexpected high bits set");
8284 LastSeenModule->
second[Pos++] = Val;
8287 LastSeenModule =
nullptr;
8300class BitcodeErrorCategoryType :
public std::error_category {
8301 const char *
name()
const noexcept
override {
8302 return "llvm.bitcode";
8305 std::string message(
int IE)
const override {
8308 case BitcodeError::CorruptedBitcode:
8309 return "Corrupted bitcode";
8318 static BitcodeErrorCategoryType ErrorCategory;
8319 return ErrorCategory;
8323 unsigned Block,
unsigned RecordID) {
8325 return std::move(Err);
8334 switch (Entry.Kind) {
8339 return error(
"Malformed block");
8343 return std::move(Err);
8353 if (MaybeRecord.
get() == RecordID)
8364Expected<std::vector<BitcodeModule>>
8368 return FOrErr.takeError();
8369 return std::move(FOrErr->Mods);
8394 switch (Entry.Kind) {
8397 return error(
"Malformed block");
8400 uint64_t IdentificationBit = -1ull;
8404 return std::move(Err);
8410 Entry = MaybeEntry.
get();
8415 return error(
"Malformed block");
8421 return std::move(Err);
8440 if (!
I.Strtab.empty())
8447 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8448 F.StrtabForSymtab = *Strtab;
8464 if (
F.Symtab.empty())
8465 F.Symtab = *SymtabOrErr;
8470 return std::move(Err);
8475 return std::move(E);
8490BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8491 bool ShouldLazyLoadMetadata,
bool IsImporting,
8495 std::string ProducerIdentification;
8496 if (IdentificationBit != -1ull) {
8497 if (
Error JumpFailed = Stream.JumpToBit(IdentificationBit))
8498 return std::move(JumpFailed);
8501 return std::move(
E);
8504 if (
Error JumpFailed = Stream.JumpToBit(ModuleBit))
8505 return std::move(JumpFailed);
8506 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8509 std::unique_ptr<Module>
M =
8510 std::make_unique<Module>(ModuleIdentifier,
Context);
8511 M->setMaterializer(R);
8514 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8515 IsImporting, Callbacks))
8516 return std::move(Err);
8518 if (MaterializeAll) {
8520 if (
Error Err =
M->materializeAll())
8521 return std::move(Err);
8524 if (
Error Err =
R->materializeForwardReferencedFunctions())
8525 return std::move(Err);
8528 return std::move(M);
8531Expected<std::unique_ptr<Module>>
8534 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8549 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8550 ModulePath, IsPrevailing);
8551 return R.parseModule();
8558 return std::move(JumpFailed);
8560 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8561 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8562 ModuleIdentifier, 0);
8564 if (
Error Err = R.parseModule())
8565 return std::move(Err);
8567 return std::move(Index);
8573 return std::move(Err);
8579 return std::move(
E);
8581 switch (Entry.Kind) {
8584 return error(
"Malformed block");
8587 return std::make_pair(
false,
false);
8599 switch (MaybeBitCode.
get()) {
8605 assert(Flags <= 0x7ff &&
"Unexpected bits in flag");
8607 bool EnableSplitLTOUnit = Flags & 0x8;
8608 bool UnifiedLTO = Flags & 0x200;
8609 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
8620 return std::move(JumpFailed);
8623 return std::move(Err);
8628 return std::move(E);
8630 switch (Entry.Kind) {
8632 return error(
"Malformed block");
8643 return Flags.takeError();
8653 return std::move(Err);
8660 return StreamFailed.takeError();
8670 if (MsOrErr->size() != 1)
8671 return error(
"Expected a single module");
8673 return (*MsOrErr)[0];
8676Expected<std::unique_ptr<Module>>
8678 bool ShouldLazyLoadMetadata,
bool IsImporting,
8684 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8689 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
8690 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
8692 IsImporting, Callbacks);
8694 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8700 return getModuleImpl(Context,
true,
false,
false, Callbacks);
8712 return BM->parseModule(Context, Callbacks);
8745 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8754 return BM->getSummary();
8762 return BM->getLTOInfo();
8767 bool IgnoreEmptyThinLTOIndexFile) {
8772 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
AMDGPU Prepare AGPR Alloc
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")
Analysis containing CSE Info
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.
static uint64_t decodeSignRotatedValue(uint64_t V)
Decode a signed value stored with the sign bit in the LSB for dense VBR encoding.
This file defines the SmallString class.
This file defines the SmallVector class.
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.
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
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
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
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.
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.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
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 LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
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 * 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 * 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.
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 ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
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.
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)
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
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 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 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 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_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_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 unsigned RelBlockFreqBits
The value stored in RelBlockFreq has to be interpreted as the digits of a scaled number with a scale ...
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