25#include "llvm/Config/llvm-config.h"
55#include "llvm/IR/IntrinsicsAArch64.h"
56#include "llvm/IR/IntrinsicsARM.h"
89#include <system_error>
99 "Print the global id for each value when reading the module summary"));
104 SWITCH_INST_MAGIC = 0x4B5
117 "file too small to contain bitcode header");
118 for (
unsigned C : {
'B',
'C'})
122 "file doesn't start with bitcode header");
124 return Res.takeError();
125 for (
unsigned C : {0x0, 0xC, 0xE, 0xD})
129 "file doesn't start with bitcode header");
131 return Res.takeError();
136 const unsigned char *BufPtr = (
const unsigned char *)Buffer.
getBufferStart();
137 const unsigned char *BufEnd = BufPtr + Buffer.
getBufferSize();
140 return error(
"Invalid bitcode signature");
146 return error(
"Invalid bitcode wrapper header");
150 return std::move(Err);
152 return std::move(Stream);
156template <
typename StrTy>
169 if (
F.isMaterializable())
172 I.setMetadata(LLVMContext::MD_tbaa,
nullptr);
180 return std::move(Err);
185 std::string ProducerIdentification;
192 switch (Entry.Kind) {
195 return error(
"Malformed block");
197 return ProducerIdentification;
208 switch (MaybeBitCode.
get()) {
210 return error(
"Invalid value");
218 Twine(
"Incompatible epoch: Bitcode '") +
Twine(epoch) +
237 switch (Entry.Kind) {
240 return error(
"Malformed block");
248 return std::move(Err);
260 return std::move(Err);
271 switch (Entry.Kind) {
274 return error(
"Malformed block");
286 switch (MaybeRecord.
get()) {
292 return error(
"Invalid section name record");
297 Segment = Segment.trim();
298 Section = Section.trim();
300 if (Segment ==
"__DATA" && Section.starts_with(
"__objc_catlist"))
302 if (Segment ==
"__OBJC" && Section.starts_with(
"__category"))
304 if (Segment ==
"__TEXT" && Section.starts_with(
"__swift"))
322 switch (Entry.Kind) {
324 return error(
"Malformed block");
334 return std::move(Err);
347 return std::move(Err);
360 switch (Entry.Kind) {
363 return error(
"Malformed block");
375 switch (MaybeRecord.
get()) {
380 return error(
"Invalid triple record");
399 switch (Entry.Kind) {
401 return error(
"Malformed block");
411 return std::move(Err);
418 return Skipped.takeError();
425class BitcodeReaderBase {
427 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
428 : Stream(std::
move(Stream)), Strtab(Strtab) {
429 this->Stream.setBlockInfo(&BlockInfo);
432 BitstreamBlockInfo BlockInfo;
433 BitstreamCursor Stream;
438 bool UseStrtab =
false;
440 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
445 std::pair<StringRef, ArrayRef<uint64_t>>
446 readNameFromStrtab(ArrayRef<uint64_t> Record);
448 Error readBlockInfo();
451 std::string ProducerIdentification;
458Error BitcodeReaderBase::error(
const Twine &Message) {
459 std::string FullMsg = Message.
str();
460 if (!ProducerIdentification.empty())
461 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
462 LLVM_VERSION_STRING
"')";
463 return ::error(FullMsg);
467BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
469 return error(
"Invalid version record");
470 unsigned ModuleVersion =
Record[0];
471 if (ModuleVersion > 2)
472 return error(
"Invalid value");
473 UseStrtab = ModuleVersion >= 2;
474 return ModuleVersion;
477std::pair<StringRef, ArrayRef<uint64_t>>
478BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
485 if (
Record.size() < 2 || Record[0] > Strtab.
size() ||
486 Record[1] > Strtab.
size() - Record[0])
488 return {StringRef(Strtab.
data() + Record[0], Record[1]),
Record.slice(2)};
499class BitcodeConstant final :
public Value,
500 TrailingObjects<BitcodeConstant, unsigned> {
501 friend TrailingObjects;
504 static constexpr uint8_t SubclassID = 255;
512 static constexpr uint8_t ConstantStructOpcode = 255;
513 static constexpr uint8_t ConstantArrayOpcode = 254;
514 static constexpr uint8_t ConstantVectorOpcode = 253;
515 static constexpr uint8_t NoCFIOpcode = 252;
516 static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
517 static constexpr uint8_t BlockAddressOpcode = 250;
518 static constexpr uint8_t ConstantPtrAuthOpcode = 249;
519 static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
526 unsigned BlockAddressBB = 0;
527 Type *SrcElemTy =
nullptr;
528 std::optional<ConstantRange>
InRange;
530 ExtraInfo(uint8_t Opcode, uint8_t Flags = 0,
Type *SrcElemTy =
nullptr,
531 std::optional<ConstantRange>
InRange = std::nullopt)
532 : Opcode(Opcode),
Flags(
Flags), SrcElemTy(SrcElemTy),
535 ExtraInfo(uint8_t Opcode, uint8_t Flags,
unsigned BlockAddressBB)
536 : Opcode(Opcode),
Flags(
Flags), BlockAddressBB(BlockAddressBB) {}
541 unsigned NumOperands;
542 unsigned BlockAddressBB;
544 std::optional<ConstantRange>
InRange;
547 BitcodeConstant(
Type *Ty,
const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
549 NumOperands(OpIDs.
size()), BlockAddressBB(
Info.BlockAddressBB),
554 BitcodeConstant &operator=(
const BitcodeConstant &) =
delete;
558 const ExtraInfo &Info,
559 ArrayRef<unsigned> OpIDs) {
560 void *Mem =
A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.
size()),
561 alignof(BitcodeConstant));
562 return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
565 static bool classof(
const Value *
V) {
return V->getValueID() == SubclassID; }
567 ArrayRef<unsigned> getOperandIDs()
const {
568 return ArrayRef(getTrailingObjects(), NumOperands);
571 std::optional<ConstantRange> getInRange()
const {
572 assert(Opcode == Instruction::GetElementPtr);
581class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
582 const BitReaderOptions &Opts;
584 Module *TheModule =
nullptr;
585 std::optional<Triple> TargetTriple;
590 bool SeenValueSymbolTable =
false;
593 std::vector<std::string> SectionTable;
594 std::vector<std::string> GCTable;
596 std::vector<Type *> TypeList;
600 DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
607 DenseMap<std::pair<Type *, unsigned>,
unsigned> VirtualTypeIDs;
608 DenseMap<Function *, unsigned> FunctionTypeIDs;
613 BitcodeReaderValueList ValueList;
614 std::optional<MetadataLoader> MDLoader;
615 std::vector<Comdat *> ComdatList;
616 DenseSet<GlobalObject *> ImplicitComdatObjects;
619 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
620 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
622 struct FunctionOperandInfo {
624 unsigned PersonalityFn;
628 std::vector<FunctionOperandInfo> FunctionOperands;
632 std::vector<AttributeList> MAttributes;
635 std::map<unsigned, AttributeList> MAttributeGroups;
639 std::vector<BasicBlock*> FunctionBBs;
643 std::vector<Function*> FunctionsWithBodies;
647 DenseMap<Function *, Function *> UpgradedIntrinsics;
652 bool SeenFirstFunctionBody =
false;
656 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
661 std::vector<uint64_t> DeferredMetadataInfo;
666 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
667 std::deque<Function *> BasicBlockFwdRefQueue;
674 std::vector<Function *> BackwardRefFunctions;
682 bool UseRelativeIDs =
false;
686 bool WillMaterializeAllForwardRefs =
false;
690 bool SeenDebugIntrinsic =
false;
691 bool SeenDebugRecord =
false;
694 TBAAVerifier TBAAVerifyHelper;
696 std::vector<std::string> BundleTags;
699 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
702 std::vector<GlobalValue::GUID> GUIDList;
708 bool SeenGUIDList =
false;
711 bool UpgradedGUIDs =
false;
717 bool SkipDebugIntrinsicUpgrade =
false;
720 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
721 StringRef ProducerIdentification, LLVMContext &
Context);
723 Error materializeForwardReferencedFunctions();
725 Error materialize(GlobalValue *GV)
override;
726 Error materializeModule()
override;
727 std::vector<StructType *> getIdentifiedStructTypes()
const override;
731 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
732 bool IsImporting, ParserCallbacks Callbacks = {});
737 Error materializeMetadata()
override;
739 void setStripDebugInfo()
override;
742 std::vector<StructType *> IdentifiedStructTypes;
743 StructType *createIdentifiedStructType(LLVMContext &
Context, StringRef Name);
744 StructType *createIdentifiedStructType(LLVMContext &
Context);
746 static constexpr unsigned InvalidTypeID = ~0
u;
748 Type *getTypeByID(
unsigned ID);
749 Type *getPtrElementTypeByID(
unsigned ID);
750 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
751 unsigned getVirtualTypeID(
Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
754 Expected<Value *> materializeValue(
unsigned ValID, BasicBlock *InsertBB);
755 Expected<Constant *> getValueForInitializer(
unsigned ID);
757 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
758 BasicBlock *ConstExprInsertBB) {
764 Metadata *getFnMetadataByID(
unsigned ID) {
765 return MDLoader->getMetadataFwdRefOrLoad(ID);
768 BasicBlock *getBasicBlock(
unsigned ID)
const {
769 if (ID >= FunctionBBs.size())
return nullptr;
770 return FunctionBBs[
ID];
774 if (i-1 < MAttributes.size())
775 return MAttributes[i-1];
776 return AttributeList();
782 bool getValueTypePair(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
783 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
784 BasicBlock *ConstExprInsertBB) {
785 if (Slot ==
Record.size())
return true;
786 unsigned ValNo = (unsigned)Record[Slot++];
789 ValNo = InstNum - ValNo;
790 if (ValNo < InstNum) {
794 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
796 "Incorrect type ID stored for value");
797 return ResVal ==
nullptr;
799 if (Slot ==
Record.size())
802 TypeID = (unsigned)Record[Slot++];
803 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
805 return ResVal ==
nullptr;
808 bool getValueOrMetadata(
const SmallVectorImpl<uint64_t> &Record,
809 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
810 BasicBlock *ConstExprInsertBB) {
811 if (Slot ==
Record.size())
816 return getValueTypePair(Record, --Slot, InstNum, ResVal, TypeId,
819 if (Slot ==
Record.size())
821 unsigned ValNo = InstNum - (unsigned)Record[Slot++];
829 bool popValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned &Slot,
830 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
831 BasicBlock *ConstExprInsertBB) {
832 if (
getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
840 bool getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
841 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
842 BasicBlock *ConstExprInsertBB) {
843 ResVal =
getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
844 return ResVal ==
nullptr;
849 Value *
getValue(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
850 unsigned InstNum,
Type *Ty,
unsigned TyID,
851 BasicBlock *ConstExprInsertBB) {
852 if (Slot ==
Record.size())
return nullptr;
853 unsigned ValNo = (unsigned)Record[Slot];
856 ValNo = InstNum - ValNo;
857 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
861 Value *getValueSigned(
const SmallVectorImpl<uint64_t> &Record,
unsigned Slot,
862 unsigned InstNum,
Type *Ty,
unsigned TyID,
863 BasicBlock *ConstExprInsertBB) {
864 if (Slot ==
Record.size())
return nullptr;
865 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
868 ValNo = InstNum - ValNo;
869 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
872 Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
875 if (
Record.size() - OpNum < 2)
876 return error(
"Too few records for range");
878 unsigned LowerActiveWords =
Record[OpNum];
879 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
880 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
881 return error(
"Too few records for range");
884 OpNum += LowerActiveWords;
887 OpNum += UpperActiveWords;
890 int64_t
Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
891 int64_t
End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
892 return ConstantRange(APInt(
BitWidth, Start,
true),
897 Expected<ConstantRange>
898 readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,
unsigned &OpNum) {
899 if (
Record.size() - OpNum < 1)
900 return error(
"Too few records for range");
902 return readConstantRange(Record, OpNum,
BitWidth);
906 const Triple &getTargetTriple() {
908 BitstreamCursor TripleStream(Stream.getBitcodeBytes());
909 if (Expected<std::string> TripleStr =
readTriple(TripleStream))
910 TargetTriple.emplace(std::move(*TripleStr));
913 TargetTriple.emplace();
916 return *TargetTriple;
922 Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
928 Error parseAttrKind(
uint64_t Code, Attribute::AttrKind *Kind);
930 ParserCallbacks Callbacks = {});
932 Error parseComdatRecord(ArrayRef<uint64_t> Record);
933 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
934 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
935 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
936 ArrayRef<uint64_t> Record);
938 Error parseAttributeBlock();
939 Error parseAttributeGroupBlock();
940 Error parseTypeTable();
941 Error parseTypeTableBody();
942 Error parseOperandBundleTags();
943 Error parseSyncScopeNames();
945 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
946 unsigned NameIndex, Triple &TT);
947 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
Function *
F,
948 ArrayRef<uint64_t> Record);
950 Error parseGlobalValueSymbolTable();
951 Error parseConstants();
952 Error rememberAndSkipFunctionBodies();
953 Error rememberAndSkipFunctionBody();
955 Error rememberAndSkipMetadata();
958 Error globalCleanup();
960 void attachUpgradedGUIDMetadata(GlobalObject &GO);
961 Error resolveGlobalAndIndirectSymbolInits();
962 Error parseUseLists();
963 Error findFunctionInStream(
965 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
972class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
974 ModuleSummaryIndex &TheIndex;
978 bool SeenGlobalValSummary =
false;
981 bool SeenValueSymbolTable =
false;
995 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
996 ValueIdToValueInfoMap;
1002 DenseMap<uint64_t, StringRef> ModuleIdMap;
1005 std::string SourceFileName;
1009 StringRef ModulePath;
1013 std::function<bool(StringRef)> IsPrevailing =
nullptr;
1016 std::function<void(ValueInfo)> OnValueInfo =
nullptr;
1020 std::vector<uint64_t> StackIds;
1024 std::vector<uint64_t> RadixArray;
1029 std::vector<unsigned> StackIdToIndex;
1032 std::vector<uint64_t> DefinedGUIDs;
1035 ModuleSummaryIndexBitcodeReader(
1036 BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
1037 StringRef ModulePath,
1038 std::function<
bool(StringRef)> IsPrevailing =
nullptr,
1039 std::function<
void(ValueInfo)> OnValueInfo =
nullptr);
1046 StringRef SourceFileName);
1047 Error parseValueSymbolTable(
1049 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
1052 makeCallList(ArrayRef<uint64_t> Record,
bool IsOldProfileFormat,
1053 bool HasProfile,
bool HasRelBF);
1054 Error parseEntireSummary(
unsigned ID);
1055 Error parseModuleStringTable();
1056 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
1057 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,
size_t &Slot,
1059 std::vector<FunctionSummary::ParamAccess>
1060 parseParamAccesses(ArrayRef<uint64_t> Record);
1061 SmallVector<unsigned> parseAllocInfoContext(ArrayRef<uint64_t> Record,
1065 static constexpr unsigned UninitializedStackIdIndex =
1066 std::numeric_limits<unsigned>::max();
1068 unsigned getStackIdIndex(
unsigned LocalIndex) {
1069 unsigned &
Index = StackIdToIndex[LocalIndex];
1072 if (Index == UninitializedStackIdIndex)
1077 template <
bool AllowNullValueInfo = false>
1078 std::pair<ValueInfo, GlobalValue::GUID>
1079 getValueInfoFromValueId(
unsigned ValueId);
1081 void addThisModule();
1097 return std::error_code();
1103 : BitcodeReaderBase(
std::
move(Stream), Strtab),
1105 ValueList(this->Stream.SizeInBytes(),
1107 return materializeValue(
ValID, InsertBB);
1109 this->ProducerIdentification = std::string(ProducerIdentification);
1112Error BitcodeReader::materializeForwardReferencedFunctions() {
1113 if (WillMaterializeAllForwardRefs)
1117 WillMaterializeAllForwardRefs =
true;
1119 while (!BasicBlockFwdRefQueue.empty()) {
1120 Function *
F = BasicBlockFwdRefQueue.front();
1121 BasicBlockFwdRefQueue.pop_front();
1122 assert(
F &&
"Expected valid function");
1123 if (!BasicBlockFwdRefs.
count(
F))
1131 if (!
F->isMaterializable())
1132 return error(
"Never resolved function from blockaddress");
1135 if (
Error Err = materialize(
F))
1138 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1140 for (
Function *
F : BackwardRefFunctions)
1141 if (
Error Err = materialize(
F))
1143 BackwardRefFunctions.clear();
1146 WillMaterializeAllForwardRefs =
false;
1211 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1212 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1213 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1214 Flags.NoInline = (RawFlags >> 4) & 0x1;
1215 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1216 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1217 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1218 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1219 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1235 bool NoRenameOnPromotion = ((RawFlags >> 11) & 1);
1236 RawFlags = RawFlags >> 4;
1237 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1241 bool Live = (RawFlags & 0x2) || Version < 3;
1242 bool Local = (RawFlags & 0x4);
1243 bool AutoHide = (RawFlags & 0x8);
1246 Live,
Local, AutoHide, IK,
1247 NoRenameOnPromotion);
1253 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1254 (RawFlags & 0x4) ?
true :
false,
1261 bool HasTailCall = (RawFlags & 0x8);
1262 bool HasIndirectCall = (RawFlags & 0x10);
1263 return CalleeInfo(Hotness, HasTailCall, HasIndirectCall);
1268 bool &HasTailCall) {
1269 static constexpr unsigned RelBlockFreqBits = 28;
1270 static constexpr uint64_t RelBlockFreqMask = (1 << RelBlockFreqBits) - 1;
1271 RelBF = RawFlags & RelBlockFreqMask;
1272 HasTailCall = (RawFlags & (1 << RelBlockFreqBits));
1297 case 0:
return false;
1298 case 1:
return true;
1360 bool IsFP = Ty->isFPOrFPVectorTy();
1362 if (!IsFP && !Ty->isIntOrIntVectorTy())
1369 return IsFP ? Instruction::FNeg : -1;
1374 bool IsFP = Ty->isFPOrFPVectorTy();
1376 if (!IsFP && !Ty->isIntOrIntVectorTy())
1383 return IsFP ? Instruction::FAdd : Instruction::Add;
1385 return IsFP ? Instruction::FSub : Instruction::Sub;
1387 return IsFP ? Instruction::FMul : Instruction::Mul;
1389 return IsFP ? -1 : Instruction::UDiv;
1391 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1393 return IsFP ? -1 : Instruction::URem;
1395 return IsFP ? Instruction::FRem : Instruction::SRem;
1397 return IsFP ? -1 : Instruction::Shl;
1399 return IsFP ? -1 : Instruction::LShr;
1401 return IsFP ? -1 : Instruction::AShr;
1403 return IsFP ? -1 : Instruction::And;
1405 return IsFP ? -1 : Instruction::Or;
1407 return IsFP ? -1 : Instruction::Xor;
1412 bool &IsElementwise) {
1510Type *BitcodeReader::getTypeByID(
unsigned ID) {
1512 if (ID >= TypeList.size())
1515 if (
Type *Ty = TypeList[ID])
1520 return TypeList[
ID] = createIdentifiedStructType(
Context);
1523unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1524 auto It = ContainedTypeIDs.
find(ID);
1525 if (It == ContainedTypeIDs.
end())
1526 return InvalidTypeID;
1528 if (Idx >= It->second.size())
1529 return InvalidTypeID;
1531 return It->second[
Idx];
1534Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1535 if (ID >= TypeList.size())
1542 return getTypeByID(getContainedTypeID(ID, 0));
1545unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1546 ArrayRef<unsigned> ChildTypeIDs) {
1547 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1548 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1549 auto It = VirtualTypeIDs.
find(CacheKey);
1550 if (It != VirtualTypeIDs.
end()) {
1556 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1557 "Incorrect cached contained type IDs");
1561 unsigned TypeID = TypeList.size();
1562 TypeList.push_back(Ty);
1563 if (!ChildTypeIDs.
empty())
1581 const BitcodeConstant *BC) {
1585 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1590 if (Opts.expand_constant_exprs)
1599 if (Opcode == Instruction::GetElementPtr)
1603 case Instruction::FNeg:
1604 case Instruction::Select:
1605 case Instruction::ICmp:
1606 case Instruction::FCmp:
1613Expected<Value *> BitcodeReader::materializeValue(
unsigned StartValID,
1614 BasicBlock *InsertBB) {
1616 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1618 return ValueList[StartValID];
1620 SmallDenseMap<unsigned, Value *> MaterializedValues;
1621 SmallVector<unsigned> Worklist;
1623 while (!Worklist.
empty()) {
1624 unsigned ValID = Worklist.
back();
1625 if (MaterializedValues.
count(ValID)) {
1631 if (ValID >= ValueList.
size() || !ValueList[ValID])
1632 return error(
"Invalid value ID");
1634 Value *
V = ValueList[ValID];
1637 MaterializedValues.
insert({ValID,
V});
1645 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1646 auto It = MaterializedValues.
find(OpID);
1647 if (It != MaterializedValues.
end())
1648 Ops.push_back(It->second);
1655 if (
Ops.size() != BC->getOperandIDs().size())
1657 std::reverse(
Ops.begin(),
Ops.end());
1674 switch (BC->Opcode) {
1675 case BitcodeConstant::ConstantPtrAuthOpcode: {
1678 return error(
"ptrauth key operand must be ConstantInt");
1682 return error(
"ptrauth disc operand must be ConstantInt");
1685 ConstOps.
size() > 4 ? ConstOps[4]
1690 "ptrauth deactivation symbol operand must be a pointer");
1693 DeactivationSymbol);
1696 case BitcodeConstant::NoCFIOpcode: {
1699 return error(
"no_cfi operand must be GlobalValue");
1703 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1706 return error(
"dso_local operand must be GlobalValue");
1710 case BitcodeConstant::BlockAddressOpcode: {
1713 return error(
"blockaddress operand must be a function");
1718 unsigned BBID = BC->BlockAddressBB;
1721 return error(
"Invalid ID");
1724 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
1726 return error(
"Invalid ID");
1733 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1735 BasicBlockFwdRefQueue.push_back(Fn);
1736 if (FwdBBs.size() < BBID + 1)
1737 FwdBBs.resize(BBID + 1);
1745 case BitcodeConstant::ConstantStructOpcode: {
1747 if (
ST->getNumElements() != ConstOps.
size())
1748 return error(
"Invalid number of elements in struct initializer");
1750 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1751 if (
Op->getType() != Ty)
1752 return error(
"Incorrect type in struct initializer");
1757 case BitcodeConstant::ConstantArrayOpcode: {
1759 if (AT->getNumElements() != ConstOps.
size())
1760 return error(
"Invalid number of elements in array initializer");
1762 for (Constant *
Op : ConstOps)
1763 if (
Op->getType() != AT->getElementType())
1764 return error(
"Incorrect type in array initializer");
1769 case BitcodeConstant::ConstantVectorOpcode: {
1771 if (VT->getNumElements() != ConstOps.size())
1772 return error(
"Invalid number of elements in vector initializer");
1774 for (Constant *
Op : ConstOps)
1775 if (
Op->getType() != VT->getElementType())
1776 return error(
"Incorrect type in vector initializer");
1781 case Instruction::GetElementPtr:
1784 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1788 case Instruction::ExtractElement:
1791 case Instruction::InsertElement:
1795 case Instruction::ShuffleVector: {
1796 SmallVector<int, 16>
Mask;
1808 MaterializedValues.
insert({ValID,
C});
1814 return error(Twine(
"Value referenced by initializer is an unsupported "
1815 "constant expression of type ") +
1816 BC->getOpcodeName());
1822 BC->getType(),
"constexpr", InsertBB);
1825 "constexpr", InsertBB);
1828 Ops[1],
"constexpr", InsertBB);
1831 I->setHasNoSignedWrap();
1833 I->setHasNoUnsignedWrap();
1839 switch (BC->Opcode) {
1840 case BitcodeConstant::ConstantVectorOpcode: {
1841 Type *IdxTy = Type::getInt32Ty(BC->getContext());
1844 Value *
Idx = ConstantInt::get(IdxTy, Pair.index());
1851 case BitcodeConstant::ConstantStructOpcode:
1852 case BitcodeConstant::ConstantArrayOpcode: {
1856 "constexpr.ins", InsertBB);
1860 case Instruction::ICmp:
1861 case Instruction::FCmp:
1864 "constexpr", InsertBB);
1866 case Instruction::GetElementPtr:
1872 case Instruction::Select:
1875 case Instruction::ExtractElement:
1878 case Instruction::InsertElement:
1882 case Instruction::ShuffleVector:
1883 I =
new ShuffleVectorInst(
Ops[0],
Ops[1],
Ops[2],
"constexpr",
1891 MaterializedValues.
insert({ValID,
I});
1895 return MaterializedValues[StartValID];
1898Expected<Constant *> BitcodeReader::getValueForInitializer(
unsigned ID) {
1899 Expected<Value *> MaybeV = materializeValue(ID,
nullptr);
1907StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context,
1910 IdentifiedStructTypes.push_back(Ret);
1914StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &
Context) {
1916 IdentifiedStructTypes.push_back(Ret);
1932 case Attribute::ZExt:
return 1 << 0;
1933 case Attribute::SExt:
return 1 << 1;
1934 case Attribute::NoReturn:
return 1 << 2;
1935 case Attribute::InReg:
return 1 << 3;
1936 case Attribute::StructRet:
return 1 << 4;
1937 case Attribute::NoUnwind:
return 1 << 5;
1938 case Attribute::NoAlias:
return 1 << 6;
1939 case Attribute::ByVal:
return 1 << 7;
1940 case Attribute::Nest:
return 1 << 8;
1941 case Attribute::ReadNone:
return 1 << 9;
1942 case Attribute::ReadOnly:
return 1 << 10;
1943 case Attribute::NoInline:
return 1 << 11;
1944 case Attribute::AlwaysInline:
return 1 << 12;
1945 case Attribute::OptimizeForSize:
return 1 << 13;
1946 case Attribute::StackProtect:
return 1 << 14;
1947 case Attribute::StackProtectReq:
return 1 << 15;
1948 case Attribute::Alignment:
return 31 << 16;
1950 case Attribute::NoRedZone:
return 1 << 22;
1951 case Attribute::NoImplicitFloat:
return 1 << 23;
1952 case Attribute::Naked:
return 1 << 24;
1953 case Attribute::InlineHint:
return 1 << 25;
1954 case Attribute::StackAlignment:
return 7 << 26;
1955 case Attribute::ReturnsTwice:
return 1 << 29;
1956 case Attribute::UWTable:
return 1 << 30;
1957 case Attribute::NonLazyBind:
return 1U << 31;
1958 case Attribute::SanitizeAddress:
return 1ULL << 32;
1959 case Attribute::MinSize:
return 1ULL << 33;
1960 case Attribute::NoDuplicate:
return 1ULL << 34;
1961 case Attribute::StackProtectStrong:
return 1ULL << 35;
1962 case Attribute::SanitizeThread:
return 1ULL << 36;
1963 case Attribute::SanitizeMemory:
return 1ULL << 37;
1964 case Attribute::NoBuiltin:
return 1ULL << 38;
1965 case Attribute::Returned:
return 1ULL << 39;
1966 case Attribute::Cold:
return 1ULL << 40;
1967 case Attribute::Builtin:
return 1ULL << 41;
1968 case Attribute::OptimizeNone:
return 1ULL << 42;
1969 case Attribute::InAlloca:
return 1ULL << 43;
1970 case Attribute::NonNull:
return 1ULL << 44;
1971 case Attribute::JumpTable:
return 1ULL << 45;
1972 case Attribute::Convergent:
return 1ULL << 46;
1973 case Attribute::SafeStack:
return 1ULL << 47;
1974 case Attribute::NoRecurse:
return 1ULL << 48;
1977 case Attribute::SwiftSelf:
return 1ULL << 51;
1978 case Attribute::SwiftError:
return 1ULL << 52;
1979 case Attribute::WriteOnly:
return 1ULL << 53;
1980 case Attribute::Speculatable:
return 1ULL << 54;
1981 case Attribute::StrictFP:
return 1ULL << 55;
1982 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1983 case Attribute::NoCfCheck:
return 1ULL << 57;
1984 case Attribute::OptForFuzzing:
return 1ULL << 58;
1985 case Attribute::ShadowCallStack:
return 1ULL << 59;
1986 case Attribute::SpeculativeLoadHardening:
1988 case Attribute::ImmArg:
1990 case Attribute::WillReturn:
1992 case Attribute::NoFree:
2008 if (
I == Attribute::Alignment)
2009 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
2010 else if (
I == Attribute::StackAlignment)
2011 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
2013 B.addTypeAttr(
I,
nullptr);
2027 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
2029 "Alignment must be a power of two.");
2032 B.addAlignmentAttr(Alignment);
2034 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
2035 (EncodedAttrs & 0xffff);
2037 if (AttrIdx == AttributeList::FunctionIndex) {
2040 if (Attrs & (1ULL << 9)) {
2042 Attrs &= ~(1ULL << 9);
2045 if (Attrs & (1ULL << 10)) {
2047 Attrs &= ~(1ULL << 10);
2050 if (Attrs & (1ULL << 49)) {
2052 Attrs &= ~(1ULL << 49);
2055 if (Attrs & (1ULL << 50)) {
2057 Attrs &= ~(1ULL << 50);
2060 if (Attrs & (1ULL << 53)) {
2062 Attrs &= ~(1ULL << 53);
2066 B.addMemoryAttr(ME);
2070 if (Attrs & (1ULL << 21)) {
2071 Attrs &= ~(1ULL << 21);
2078Error BitcodeReader::parseAttributeBlock() {
2082 if (!MAttributes.empty())
2083 return error(
"Invalid multiple blocks");
2085 SmallVector<uint64_t, 64>
Record;
2094 BitstreamEntry
Entry = MaybeEntry.
get();
2096 switch (
Entry.Kind) {
2099 return error(
"Malformed block");
2112 switch (MaybeRecord.
get()) {
2118 return error(
"Invalid parameter attribute record");
2120 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2126 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2131 Attrs.push_back(MAttributeGroups[Val]);
2133 MAttributes.push_back(AttributeList::get(
Context, Attrs));
2146 return Attribute::Alignment;
2148 return Attribute::AlwaysInline;
2150 return Attribute::Builtin;
2152 return Attribute::ByVal;
2154 return Attribute::InAlloca;
2156 return Attribute::Cold;
2158 return Attribute::Convergent;
2160 return Attribute::DisableSanitizerInstrumentation;
2162 return Attribute::ElementType;
2164 return Attribute::FnRetThunkExtern;
2166 return Attribute::Flatten;
2168 return Attribute::HybridPatchable;
2170 return Attribute::InlineHint;
2172 return Attribute::InReg;
2174 return Attribute::JumpTable;
2176 return Attribute::Memory;
2178 return Attribute::NoFPClass;
2180 return Attribute::MinSize;
2182 return Attribute::Naked;
2184 return Attribute::Nest;
2186 return Attribute::NoAlias;
2188 return Attribute::NoBuiltin;
2190 return Attribute::NoCallback;
2192 return Attribute::NoDivergenceSource;
2194 return Attribute::NoDuplicate;
2196 return Attribute::NoFree;
2198 return Attribute::NoFreeObj;
2200 return Attribute::NoImplicitFloat;
2202 return Attribute::NoInline;
2204 return Attribute::NoRecurse;
2206 return Attribute::NoMerge;
2208 return Attribute::NonLazyBind;
2210 return Attribute::NonNull;
2212 return Attribute::Dereferenceable;
2214 return Attribute::DereferenceableOrNull;
2216 return Attribute::AllocAlign;
2218 return Attribute::AllocKind;
2220 return Attribute::AllocSize;
2222 return Attribute::AllocatedPointer;
2224 return Attribute::NoRedZone;
2226 return Attribute::NoReturn;
2228 return Attribute::NoSync;
2230 return Attribute::NoCfCheck;
2232 return Attribute::NoProfile;
2234 return Attribute::SkipProfile;
2236 return Attribute::NoUnwind;
2238 return Attribute::NoSanitizeBounds;
2240 return Attribute::NoSanitizeCoverage;
2242 return Attribute::NullPointerIsValid;
2244 return Attribute::OptimizeForDebugging;
2246 return Attribute::OptForFuzzing;
2248 return Attribute::OptimizeForSize;
2250 return Attribute::OptimizeNone;
2252 return Attribute::ReadNone;
2254 return Attribute::ReadOnly;
2256 return Attribute::Returned;
2258 return Attribute::ReturnsTwice;
2260 return Attribute::SExt;
2262 return Attribute::Speculatable;
2264 return Attribute::StackAlignment;
2266 return Attribute::StackProtect;
2268 return Attribute::StackProtectReq;
2270 return Attribute::StackProtectStrong;
2272 return Attribute::SafeStack;
2274 return Attribute::ShadowCallStack;
2276 return Attribute::StrictFP;
2278 return Attribute::StructRet;
2280 return Attribute::SanitizeAddress;
2282 return Attribute::SanitizeHWAddress;
2284 return Attribute::SanitizeThread;
2286 return Attribute::SanitizeConcurrency;
2288 return Attribute::SanitizeType;
2290 return Attribute::SanitizeMemory;
2292 return Attribute::SanitizeNumericalStability;
2294 return Attribute::SanitizeRealtime;
2296 return Attribute::SanitizeRealtimeBlocking;
2298 return Attribute::SanitizeAllocToken;
2300 return Attribute::SpeculativeLoadHardening;
2302 return Attribute::SwiftError;
2304 return Attribute::SwiftSelf;
2306 return Attribute::SwiftAsync;
2308 return Attribute::UWTable;
2310 return Attribute::VScaleRange;
2312 return Attribute::WillReturn;
2314 return Attribute::WriteOnly;
2316 return Attribute::ZExt;
2318 return Attribute::ImmArg;
2320 return Attribute::SanitizeMemTag;
2322 return Attribute::Preallocated;
2324 return Attribute::NoUndef;
2326 return Attribute::ByRef;
2328 return Attribute::MustProgress;
2330 return Attribute::Hot;
2332 return Attribute::PresplitCoroutine;
2334 return Attribute::Writable;
2336 return Attribute::CoroDestroyOnlyWhenComplete;
2338 return Attribute::DeadOnUnwind;
2340 return Attribute::Range;
2342 return Attribute::Initializes;
2344 return Attribute::CoroElideSafe;
2346 return Attribute::NoExt;
2348 return Attribute::Captures;
2350 return Attribute::DeadOnReturn;
2352 return Attribute::NoCreateUndefOrPoison;
2354 return Attribute::DenormalFPEnv;
2356 return Attribute::NoOutline;
2358 return Attribute::NoIPA;
2360 return Attribute::LikelyModuleLocal;
2365 MaybeAlign &Alignment) {
2368 if (
Exponent > Value::MaxAlignmentExponent + 1)
2369 return error(
"Invalid alignment value");
2374Error BitcodeReader::parseAttrKind(
uint64_t Code, Attribute::AttrKind *Kind) {
2376 if (*Kind == Attribute::None)
2377 return error(
"Unknown attribute kind (" + Twine(Code) +
")");
2382 switch (EncodedKind) {
2406Error BitcodeReader::parseAttributeGroupBlock() {
2410 if (!MAttributeGroups.empty())
2411 return error(
"Invalid multiple blocks");
2413 SmallVector<uint64_t, 64>
Record;
2420 BitstreamEntry
Entry = MaybeEntry.
get();
2422 switch (
Entry.Kind) {
2425 return error(
"Malformed block");
2438 switch (MaybeRecord.
get()) {
2443 return error(
"Invalid grp record");
2450 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2451 if (Record[i] == 0) {
2452 Attribute::AttrKind
Kind;
2454 if (Idx == AttributeList::FunctionIndex &&
2463 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2469 if (Kind == Attribute::ByVal)
2470 B.addByValAttr(
nullptr);
2471 else if (Kind == Attribute::StructRet)
2472 B.addStructRetAttr(
nullptr);
2473 else if (Kind == Attribute::InAlloca)
2474 B.addInAllocaAttr(
nullptr);
2475 else if (Kind == Attribute::UWTable)
2476 B.addUWTableAttr(UWTableKind::Default);
2477 else if (Kind == Attribute::DeadOnReturn)
2478 B.addDeadOnReturnAttr(DeadOnReturnInfo());
2479 else if (Attribute::isEnumAttrKind(Kind))
2480 B.addAttribute(Kind);
2482 return error(
"Not an enum attribute");
2483 }
else if (Record[i] == 1) {
2484 Attribute::AttrKind
Kind;
2485 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2487 if (!Attribute::isIntAttrKind(Kind))
2488 return error(
"Not an int attribute");
2489 if (Kind == Attribute::Alignment)
2490 B.addAlignmentAttr(Record[++i]);
2491 else if (Kind == Attribute::StackAlignment)
2492 B.addStackAlignmentAttr(Record[++i]);
2493 else if (Kind == Attribute::Dereferenceable)
2494 B.addDereferenceableAttr(Record[++i]);
2495 else if (Kind == Attribute::DereferenceableOrNull)
2496 B.addDereferenceableOrNullAttr(Record[++i]);
2497 else if (Kind == Attribute::DeadOnReturn)
2498 B.addDeadOnReturnAttr(
2500 else if (Kind == Attribute::AllocSize)
2501 B.addAllocSizeAttrFromRawRepr(Record[++i]);
2502 else if (Kind == Attribute::VScaleRange)
2503 B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2504 else if (Kind == Attribute::UWTable)
2506 else if (Kind == Attribute::AllocKind)
2507 B.addAllocKindAttr(
static_cast<AllocFnKind>(Record[++i]));
2508 else if (Kind == Attribute::Memory) {
2510 const uint8_t
Version = (EncodedME >> 56);
2524 if (getTargetTriple().isAArch64())
2529 B.addMemoryAttr(ME);
2534 EncodedME & 0x00FFFFFFFFFFFFFFULL);
2537 if (
Version == 1 && getTargetTriple().isAArch64())
2539 IRMemLocation::TargetMem0,
2540 ME.
getModRef(IRMemLocation::InaccessibleMem)) |
2542 IRMemLocation::TargetMem1,
2543 ME.
getModRef(IRMemLocation::InaccessibleMem));
2544 B.addMemoryAttr(ME);
2546 }
else if (Kind == Attribute::Captures)
2548 else if (Kind == Attribute::NoFPClass)
2551 else if (Kind == Attribute::DenormalFPEnv) {
2552 B.addDenormalFPEnvAttr(
2555 }
else if (Record[i] == 3 || Record[i] == 4) {
2557 SmallString<64> KindStr;
2558 SmallString<64> ValStr;
2560 while (Record[i] != 0 && i != e)
2562 assert(Record[i] == 0 &&
"Kind string not null terminated");
2567 while (Record[i] != 0 && i != e)
2569 assert(Record[i] == 0 &&
"Value string not null terminated");
2572 B.addAttribute(KindStr.
str(), ValStr.
str());
2573 }
else if (Record[i] == 5 || Record[i] == 6) {
2574 bool HasType =
Record[i] == 6;
2575 Attribute::AttrKind
Kind;
2576 if (
Error Err = parseAttrKind(Record[++i], &Kind))
2578 if (!Attribute::isTypeAttrKind(Kind))
2579 return error(
"Not a type attribute");
2581 B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) :
nullptr);
2582 }
else if (Record[i] == 7) {
2583 Attribute::AttrKind
Kind;
2586 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2588 if (!Attribute::isConstantRangeAttrKind(Kind))
2589 return error(
"Not a ConstantRange attribute");
2591 Expected<ConstantRange> MaybeCR =
2592 readBitWidthAndConstantRange(Record, i);
2597 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2598 }
else if (Record[i] == 8) {
2599 Attribute::AttrKind
Kind;
2602 if (
Error Err = parseAttrKind(Record[i++], &Kind))
2604 if (!Attribute::isConstantRangeListAttrKind(Kind))
2605 return error(
"Not a constant range list attribute");
2609 return error(
"Too few records for constant range list");
2610 unsigned RangeSize =
Record[i++];
2612 for (
unsigned Idx = 0;
Idx < RangeSize; ++
Idx) {
2613 Expected<ConstantRange> MaybeCR =
2614 readConstantRange(Record, i,
BitWidth);
2622 return error(
"Invalid (unordered or overlapping) range list");
2623 B.addConstantRangeListAttr(Kind, Val);
2625 return error(
"Invalid attribute group entry");
2630 B.addMemoryAttr(ME);
2633 MAttributeGroups[GrpID] = AttributeList::get(
Context, Idx,
B);
2640Error BitcodeReader::parseTypeTable() {
2644 return parseTypeTableBody();
2647Error BitcodeReader::parseTypeTableBody() {
2648 if (!TypeList.empty())
2649 return error(
"Invalid multiple blocks");
2651 SmallVector<uint64_t, 64>
Record;
2652 unsigned NumRecords = 0;
2661 BitstreamEntry
Entry = MaybeEntry.
get();
2663 switch (
Entry.Kind) {
2666 return error(
"Malformed block");
2668 if (NumRecords != TypeList.size())
2669 return error(
"Malformed block");
2678 Type *ResultTy =
nullptr;
2679 SmallVector<unsigned> ContainedIDs;
2683 switch (MaybeRecord.
get()) {
2685 return error(
"Invalid value");
2690 return error(
"Invalid numentry record");
2691 TypeList.resize(Record[0]);
2694 ResultTy = Type::getVoidTy(
Context);
2697 ResultTy = Type::getHalfTy(
Context);
2700 ResultTy = Type::getBFloatTy(
Context);
2703 ResultTy = Type::getFloatTy(
Context);
2706 ResultTy = Type::getDoubleTy(
Context);
2709 ResultTy = Type::getX86_FP80Ty(
Context);
2712 ResultTy = Type::getFP128Ty(
Context);
2715 ResultTy = Type::getPPC_FP128Ty(
Context);
2718 ResultTy = Type::getLabelTy(
Context);
2721 ResultTy = Type::getMetadataTy(
Context);
2729 ResultTy = Type::getX86_AMXTy(
Context);
2732 ResultTy = Type::getTokenTy(
Context);
2736 return error(
"Invalid record");
2741 return error(
"Bitwidth for byte type out of range");
2747 return error(
"Invalid integer record");
2752 return error(
"Bitwidth for integer type out of range");
2759 return error(
"Invalid pointer record");
2763 ResultTy = getTypeByID(Record[0]);
2765 !PointerType::isValidElementType(ResultTy))
2766 return error(
"Invalid type");
2773 return error(
"Invalid opaque pointer record");
2782 return error(
"Invalid function record");
2784 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2785 if (
Type *
T = getTypeByID(Record[i]))
2791 ResultTy = getTypeByID(Record[2]);
2792 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2793 return error(
"Invalid type");
2796 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2802 return error(
"Invalid function record");
2804 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2805 if (
Type *
T = getTypeByID(Record[i])) {
2806 if (!FunctionType::isValidArgumentType(
T))
2807 return error(
"Invalid function argument type");
2814 ResultTy = getTypeByID(Record[1]);
2815 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2816 return error(
"Invalid type");
2819 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2824 return error(
"Invalid anon struct record");
2826 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2827 if (
Type *
T = getTypeByID(Record[i]))
2833 return error(
"Invalid type");
2840 return error(
"Invalid struct name record");
2845 return error(
"Invalid named struct record");
2847 if (NumRecords >= TypeList.size())
2848 return error(
"Invalid TYPE table");
2854 TypeList[NumRecords] =
nullptr;
2856 Res = createIdentifiedStructType(
Context, TypeName);
2860 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2861 if (
Type *
T = getTypeByID(Record[i]))
2867 return error(
"Invalid named struct record");
2876 return error(
"Invalid opaque type record");
2878 if (NumRecords >= TypeList.size())
2879 return error(
"Invalid TYPE table");
2885 TypeList[NumRecords] =
nullptr;
2887 Res = createIdentifiedStructType(
Context, TypeName);
2894 return error(
"Invalid target extension type record");
2896 if (NumRecords >= TypeList.size())
2897 return error(
"Invalid TYPE table");
2899 if (Record[0] >=
Record.size())
2900 return error(
"Too many type parameters");
2902 unsigned NumTys =
Record[0];
2904 SmallVector<unsigned, 8> IntParams;
2905 for (
unsigned i = 0; i < NumTys; i++) {
2906 if (
Type *
T = getTypeByID(Record[i + 1]))
2909 return error(
"Invalid type");
2912 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2913 if (Record[i] > UINT_MAX)
2914 return error(
"Integer parameter too large");
2919 if (
auto E = TTy.takeError())
2927 return error(
"Invalid array type record");
2928 ResultTy = getTypeByID(Record[1]);
2929 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2930 return error(
"Invalid type");
2932 ResultTy = ArrayType::get(ResultTy, Record[0]);
2937 return error(
"Invalid vector type record");
2939 return error(
"Invalid vector length");
2940 ResultTy = getTypeByID(Record[1]);
2941 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2942 return error(
"Invalid type");
2945 ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2949 if (NumRecords >= TypeList.size())
2950 return error(
"Invalid TYPE table");
2951 if (TypeList[NumRecords])
2953 "Invalid TYPE table: Only named structs can be forward referenced");
2954 assert(ResultTy &&
"Didn't read a type?");
2955 TypeList[NumRecords] = ResultTy;
2956 if (!ContainedIDs.
empty())
2957 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2962Error BitcodeReader::parseOperandBundleTags() {
2966 if (!BundleTags.empty())
2967 return error(
"Invalid multiple blocks");
2969 SmallVector<uint64_t, 64>
Record;
2975 BitstreamEntry
Entry = MaybeEntry.
get();
2977 switch (
Entry.Kind) {
2980 return error(
"Malformed block");
2994 return error(
"Invalid operand bundle record");
2997 BundleTags.emplace_back();
2999 return error(
"Invalid operand bundle record");
3004Error BitcodeReader::parseSyncScopeNames() {
3009 return error(
"Invalid multiple synchronization scope names blocks");
3011 SmallVector<uint64_t, 64>
Record;
3016 BitstreamEntry
Entry = MaybeEntry.
get();
3018 switch (
Entry.Kind) {
3021 return error(
"Malformed block");
3024 return error(
"Invalid empty synchronization scope names block");
3038 return error(
"Invalid sync scope record");
3040 SmallString<16> SSN;
3042 return error(
"Invalid sync scope record");
3050Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
3051 unsigned NameIndex, Triple &TT) {
3054 return error(
"Invalid record");
3055 unsigned ValueID =
Record[0];
3056 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3057 return error(
"Invalid record");
3058 Value *
V = ValueList[ValueID];
3061 if (NameStr.contains(0))
3062 return error(
"Invalid value name");
3063 V->setName(NameStr);
3065 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
3078 return std::move(JumpFailed);
3084 return error(
"Expected value symbol table subblock");
3088void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
3090 ArrayRef<uint64_t> Record) {
3095 uint64_t FuncBitOffset = FuncWordOffset * 32;
3096 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
3100 if (FuncBitOffset > LastFunctionBlockBit)
3101 LastFunctionBlockBit = FuncBitOffset;
3105Error BitcodeReader::parseGlobalValueSymbolTable() {
3106 unsigned FuncBitcodeOffsetDelta =
3112 SmallVector<uint64_t, 64>
Record;
3117 BitstreamEntry
Entry = MaybeEntry.
get();
3119 switch (
Entry.Kind) {
3122 return error(
"Malformed block");
3133 switch (MaybeRecord.
get()) {
3135 unsigned ValueID =
Record[0];
3136 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
3137 return error(
"Invalid value reference in symbol table");
3138 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
3155 if (!MaybeCurrentBit)
3157 CurrentBit = MaybeCurrentBit.
get();
3160 if (
Error Err = parseGlobalValueSymbolTable())
3181 unsigned FuncBitcodeOffsetDelta =
3187 SmallVector<uint64_t, 64>
Record;
3198 BitstreamEntry
Entry = MaybeEntry.
get();
3200 switch (
Entry.Kind) {
3203 return error(
"Malformed block");
3219 switch (MaybeRecord.
get()) {
3223 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
3231 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
3239 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F, Record);
3244 return error(
"Invalid bbentry record");
3247 return error(
"Invalid bbentry record");
3269Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3270 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3271 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3272 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3274 GlobalInitWorklist.swap(GlobalInits);
3275 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3276 FunctionOperandWorklist.swap(FunctionOperands);
3278 while (!GlobalInitWorklist.empty()) {
3279 unsigned ValID = GlobalInitWorklist.back().second;
3280 if (ValID >= ValueList.
size()) {
3282 GlobalInits.push_back(GlobalInitWorklist.back());
3284 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3287 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3289 GlobalInitWorklist.pop_back();
3292 while (!IndirectSymbolInitWorklist.empty()) {
3293 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3294 if (ValID >= ValueList.
size()) {
3295 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3297 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3301 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3304 return error(
"Alias and aliasee types don't match");
3309 return error(
"Expected an alias or an ifunc");
3312 IndirectSymbolInitWorklist.pop_back();
3315 while (!FunctionOperandWorklist.empty()) {
3316 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3317 if (
Info.PersonalityFn) {
3318 unsigned ValID =
Info.PersonalityFn - 1;
3319 if (ValID < ValueList.
size()) {
3320 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3323 Info.F->setPersonalityFn(MaybeC.
get());
3324 Info.PersonalityFn = 0;
3328 unsigned ValID =
Info.Prefix - 1;
3329 if (ValID < ValueList.
size()) {
3330 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3333 Info.F->setPrefixData(MaybeC.
get());
3337 if (
Info.Prologue) {
3338 unsigned ValID =
Info.Prologue - 1;
3339 if (ValID < ValueList.
size()) {
3340 Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3343 Info.F->setPrologueData(MaybeC.
get());
3347 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3348 FunctionOperands.push_back(Info);
3349 FunctionOperandWorklist.pop_back();
3358 BitcodeReader::decodeSignRotatedValue);
3360 return APInt(TypeBits, Words);
3363Error BitcodeReader::parseConstants() {
3371 unsigned Int32TyID = getVirtualTypeID(CurTy);
3372 unsigned CurTyID = Int32TyID;
3373 Type *CurElemTy =
nullptr;
3374 unsigned NextCstNo = ValueList.
size();
3382 switch (Entry.Kind) {
3385 return error(
"Malformed block");
3387 if (NextCstNo != ValueList.
size())
3388 return error(
"Invalid constant reference");
3399 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
3402 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3412 return error(
"Invalid settype record");
3413 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3414 return error(
"Invalid settype record");
3415 if (TypeList[Record[0]] == VoidType)
3416 return error(
"Invalid constant type");
3418 CurTy = TypeList[CurTyID];
3419 CurElemTy = getPtrElementTypeByID(CurTyID);
3423 return error(
"Invalid type for a constant null value");
3426 return error(
"Invalid type for a constant null value");
3431 return error(
"Invalid integer const record");
3436 return error(
"Invalid wide integer const record");
3439 APInt VInt =
readWideAPInt(Record, ScalarTy->getBitWidth());
3440 V = ConstantInt::get(CurTy, VInt);
3445 return error(
"Invalid byte const record");
3446 V = ConstantByte::get(CurTy, decodeSignRotatedValue(Record[0]),
3451 return error(
"Invalid wide byte const record");
3454 APInt VByte =
readWideAPInt(Record, ScalarTy->getBitWidth());
3455 V = ConstantByte::get(CurTy, VByte);
3460 return error(
"Invalid float const record");
3463 if (ScalarTy->isHalfTy())
3464 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3465 APInt(16, (uint16_t)Record[0])));
3466 else if (ScalarTy->isBFloatTy())
3467 V = ConstantFP::get(
3468 CurTy,
APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3469 else if (ScalarTy->isFloatTy())
3470 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3471 APInt(32, (uint32_t)Record[0])));
3472 else if (ScalarTy->isDoubleTy())
3473 V = ConstantFP::get(
3474 CurTy,
APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3475 else if (ScalarTy->isX86_FP80Ty()) {
3478 Rearrange[0] = (
Record[1] & 0xffffLL) | (Record[0] << 16);
3479 Rearrange[1] =
Record[0] >> 48;
3480 V = ConstantFP::get(
3481 CurTy,
APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3482 }
else if (ScalarTy->isFP128Ty())
3483 V = ConstantFP::get(CurTy,
3484 APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3485 else if (ScalarTy->isPPC_FP128Ty())
3486 V = ConstantFP::get(
3487 CurTy,
APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3495 return error(
"Invalid aggregate record");
3497 SmallVector<unsigned, 16> Elts;
3501 V = BitcodeConstant::create(
3502 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3504 V = BitcodeConstant::create(
Alloc, CurTy,
3505 BitcodeConstant::ConstantArrayOpcode, Elts);
3507 V = BitcodeConstant::create(
3508 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3517 return error(
"Invalid string record");
3527 return error(
"Invalid data record");
3531 return error(
"Invalid type for value");
3534 SmallString<128> RawData;
3537 const char *Src =
reinterpret_cast<const char *
>(&Val);
3539 Src +=
sizeof(
uint64_t) - EltBytes;
3540 RawData.
append(Src, Src + EltBytes);
3545 : ConstantDataArray::getRaw(RawData.str(),
Record.
size(), EltTy);
3550 return error(
"Invalid unary op constexpr record");
3555 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[1]);
3561 return error(
"Invalid binary op constexpr record");
3567 if (
Record.size() >= 4) {
3568 if (
Opc == Instruction::Add ||
3569 Opc == Instruction::Sub ||
3570 Opc == Instruction::Mul ||
3571 Opc == Instruction::Shl) {
3576 }
else if (
Opc == Instruction::SDiv ||
3577 Opc == Instruction::UDiv ||
3578 Opc == Instruction::LShr ||
3579 Opc == Instruction::AShr) {
3584 V = BitcodeConstant::create(
Alloc, CurTy, {(uint8_t)
Opc, Flags},
3585 {(unsigned)Record[1], (
unsigned)
Record[2]});
3591 return error(
"Invalid cast constexpr record");
3596 unsigned OpTyID =
Record[1];
3597 Type *OpTy = getTypeByID(OpTyID);
3599 return error(
"Invalid cast constexpr record");
3600 V = BitcodeConstant::create(
Alloc, CurTy,
Opc, (
unsigned)Record[2]);
3612 return error(
"Constant GEP record must have at least two elements");
3614 Type *PointeeType =
nullptr;
3618 PointeeType = getTypeByID(Record[OpNum++]);
3621 std::optional<ConstantRange>
InRange;
3625 unsigned InRangeIndex =
Op >> 1;
3631 Expected<ConstantRange> MaybeInRange =
3632 readBitWidthAndConstantRange(Record, OpNum);
3641 SmallVector<unsigned, 16> Elts;
3642 unsigned BaseTypeID =
Record[OpNum];
3643 while (OpNum !=
Record.size()) {
3644 unsigned ElTyID =
Record[OpNum++];
3645 Type *ElTy = getTypeByID(ElTyID);
3647 return error(
"Invalid getelementptr constexpr record");
3651 if (Elts.
size() < 1)
3652 return error(
"Invalid gep with no operands");
3656 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3657 BaseType = getTypeByID(BaseTypeID);
3662 return error(
"GEP base operand must be pointer or vector of pointer");
3665 PointeeType = getPtrElementTypeByID(BaseTypeID);
3667 return error(
"Missing element type for old-style constant GEP");
3670 V = BitcodeConstant::create(
3672 {Instruction::GetElementPtr, uint8_t(Flags), PointeeType,
InRange},
3678 return error(
"Invalid select constexpr record");
3680 V = BitcodeConstant::create(
3681 Alloc, CurTy, Instruction::Select,
3682 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3688 return error(
"Invalid extractelement constexpr record");
3689 unsigned OpTyID =
Record[0];
3693 return error(
"Invalid extractelement constexpr record");
3695 if (
Record.size() == 4) {
3696 unsigned IdxTyID =
Record[2];
3697 Type *IdxTy = getTypeByID(IdxTyID);
3699 return error(
"Invalid extractelement constexpr record");
3705 V = BitcodeConstant::create(
Alloc, CurTy, Instruction::ExtractElement,
3706 {(unsigned)Record[1], IdxRecord});
3712 if (
Record.size() < 3 || !OpTy)
3713 return error(
"Invalid insertelement constexpr record");
3715 if (
Record.size() == 4) {
3716 unsigned IdxTyID =
Record[2];
3717 Type *IdxTy = getTypeByID(IdxTyID);
3719 return error(
"Invalid insertelement constexpr record");
3725 V = BitcodeConstant::create(
3726 Alloc, CurTy, Instruction::InsertElement,
3727 {(unsigned)Record[0], (
unsigned)
Record[1], IdxRecord});
3732 if (
Record.size() < 3 || !OpTy)
3733 return error(
"Invalid shufflevector constexpr record");
3734 V = BitcodeConstant::create(
3735 Alloc, CurTy, Instruction::ShuffleVector,
3736 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2]});
3743 if (
Record.size() < 4 || !RTy || !OpTy)
3744 return error(
"Invalid shufflevector constexpr record");
3745 V = BitcodeConstant::create(
3746 Alloc, CurTy, Instruction::ShuffleVector,
3747 {(unsigned)Record[1], (
unsigned)
Record[2], (unsigned)Record[3]});
3752 return error(
"Invalid cmp constexpt record");
3753 unsigned OpTyID =
Record[0];
3754 Type *OpTy = getTypeByID(OpTyID);
3756 return error(
"Invalid cmp constexpr record");
3757 V = BitcodeConstant::create(
3760 : Instruction::ICmp),
3761 (uint8_t)Record[3]},
3762 {(unsigned)Record[1], (
unsigned)
Record[2]});
3769 return error(
"Invalid inlineasm record");
3770 std::string AsmStr, ConstrStr;
3771 bool HasSideEffects =
Record[0] & 1;
3772 bool IsAlignStack =
Record[0] >> 1;
3773 unsigned AsmStrSize =
Record[1];
3774 if (2+AsmStrSize >=
Record.size())
3775 return error(
"Invalid inlineasm record");
3776 unsigned ConstStrSize =
Record[2+AsmStrSize];
3777 if (3+AsmStrSize+ConstStrSize >
Record.size())
3778 return error(
"Invalid inlineasm record");
3780 for (
unsigned i = 0; i != AsmStrSize; ++i)
3781 AsmStr += (
char)
Record[2+i];
3782 for (
unsigned i = 0; i != ConstStrSize; ++i)
3783 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3786 return error(
"Missing element type for old-style inlineasm");
3788 HasSideEffects, IsAlignStack);
3795 return error(
"Invalid inlineasm record");
3796 std::string AsmStr, ConstrStr;
3797 bool HasSideEffects =
Record[0] & 1;
3798 bool IsAlignStack = (
Record[0] >> 1) & 1;
3799 unsigned AsmDialect =
Record[0] >> 2;
3800 unsigned AsmStrSize =
Record[1];
3801 if (2+AsmStrSize >=
Record.size())
3802 return error(
"Invalid inlineasm record");
3803 unsigned ConstStrSize =
Record[2+AsmStrSize];
3804 if (3+AsmStrSize+ConstStrSize >
Record.size())
3805 return error(
"Invalid inlineasm record");
3807 for (
unsigned i = 0; i != AsmStrSize; ++i)
3808 AsmStr += (
char)
Record[2+i];
3809 for (
unsigned i = 0; i != ConstStrSize; ++i)
3810 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3813 return error(
"Missing element type for old-style inlineasm");
3815 HasSideEffects, IsAlignStack,
3822 return error(
"Invalid inlineasm record");
3824 std::string AsmStr, ConstrStr;
3825 bool HasSideEffects =
Record[OpNum] & 1;
3826 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3827 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3828 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3830 unsigned AsmStrSize =
Record[OpNum];
3832 if (OpNum + AsmStrSize >=
Record.size())
3833 return error(
"Invalid inlineasm record");
3834 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3835 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3836 return error(
"Invalid inlineasm record");
3838 for (
unsigned i = 0; i != AsmStrSize; ++i)
3839 AsmStr += (
char)
Record[OpNum + i];
3841 for (
unsigned i = 0; i != ConstStrSize; ++i)
3842 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3845 return error(
"Missing element type for old-style inlineasm");
3847 HasSideEffects, IsAlignStack,
3854 return error(
"Invalid inlineasm record");
3859 return error(
"Invalid inlineasm record");
3860 std::string AsmStr, ConstrStr;
3861 bool HasSideEffects =
Record[OpNum] & 1;
3862 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3863 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3864 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3866 unsigned AsmStrSize =
Record[OpNum];
3868 if (OpNum + AsmStrSize >=
Record.size())
3869 return error(
"Invalid inlineasm record");
3870 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3871 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3872 return error(
"Invalid inlineasm record");
3874 for (
unsigned i = 0; i != AsmStrSize; ++i)
3875 AsmStr += (
char)
Record[OpNum + i];
3877 for (
unsigned i = 0; i != ConstStrSize; ++i)
3878 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3880 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3886 return error(
"Invalid blockaddress record");
3887 unsigned FnTyID =
Record[0];
3888 Type *FnTy = getTypeByID(FnTyID);
3890 return error(
"Invalid blockaddress record");
3891 V = BitcodeConstant::create(
3893 {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3899 return error(
"Invalid dso_local record");
3900 unsigned GVTyID =
Record[0];
3901 Type *GVTy = getTypeByID(GVTyID);
3903 return error(
"Invalid dso_local record");
3904 V = BitcodeConstant::create(
3905 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3910 return error(
"Invalid no_cfi record");
3911 unsigned GVTyID =
Record[0];
3912 Type *GVTy = getTypeByID(GVTyID);
3914 return error(
"Invalid no_cfi record");
3915 V = BitcodeConstant::create(
Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3921 return error(
"Invalid ptrauth record");
3923 V = BitcodeConstant::create(
Alloc, CurTy,
3924 BitcodeConstant::ConstantPtrAuthOpcode,
3925 {(unsigned)Record[0], (
unsigned)
Record[1],
3926 (unsigned)Record[2], (
unsigned)
Record[3]});
3931 return error(
"Invalid ptrauth record");
3933 V = BitcodeConstant::create(
3934 Alloc, CurTy, BitcodeConstant::ConstantPtrAuthOpcode,
3935 {(unsigned)Record[0], (
unsigned)
Record[1], (unsigned)Record[2],
3936 (
unsigned)
Record[3], (unsigned)Record[4]});
3941 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3948Error BitcodeReader::parseUseLists() {
3953 SmallVector<uint64_t, 64>
Record;
3959 BitstreamEntry
Entry = MaybeEntry.
get();
3961 switch (
Entry.Kind) {
3964 return error(
"Malformed block");
3978 switch (MaybeRecord.
get()) {
3986 if (RecordLength < 3)
3988 return error(
"Invalid uselist record");
3989 unsigned ID =
Record.pop_back_val();
3993 assert(ID < FunctionBBs.size() &&
"Basic block not found");
3994 V = FunctionBBs[
ID];
3998 if (!
V->hasUseList())
4001 unsigned NumUses = 0;
4002 SmallDenseMap<const Use *, unsigned, 16> Order;
4003 for (
const Use &U :
V->materialized_uses()) {
4004 if (++NumUses >
Record.size())
4006 Order[&
U] =
Record[NumUses - 1];
4013 V->sortUseList([&](
const Use &L,
const Use &R) {
4024Error BitcodeReader::rememberAndSkipMetadata() {
4027 DeferredMetadataInfo.push_back(CurBit);
4035Error BitcodeReader::materializeMetadata() {
4036 for (
uint64_t BitPos : DeferredMetadataInfo) {
4040 if (
Error Err = MDLoader->parseModuleMetadata())
4049 NamedMDNode *LinkerOpts =
4051 for (
const MDOperand &MDOptions :
cast<MDNode>(Val)->operands())
4062 for (GlobalVariable &GV : TheModule->
globals())
4063 attachUpgradedGUIDMetadata(GV);
4065 DeferredMetadataInfo.clear();
4069void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
4073Error BitcodeReader::rememberAndSkipFunctionBody() {
4075 if (FunctionsWithBodies.empty())
4076 return error(
"Insufficient function protos");
4078 Function *Fn = FunctionsWithBodies.back();
4079 FunctionsWithBodies.pop_back();
4084 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
4085 "Mismatch between VST and scanned function offsets");
4086 DeferredFunctionInfo[Fn] = CurBit;
4094Error BitcodeReader::globalCleanup() {
4096 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4098 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
4099 return error(
"Malformed global initializer set");
4104 MDLoader->upgradeDebugIntrinsics(
F);
4108 !SkipDebugIntrinsicUpgrade))
4109 UpgradedIntrinsics[&
F] = NewFn;
4115 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
4116 for (GlobalVariable &GV : TheModule->globals())
4118 UpgradedVariables.emplace_back(&GV, Upgraded);
4119 for (
auto &Pair : UpgradedVariables) {
4120 Pair.first->eraseFromParent();
4121 TheModule->insertGlobalVariable(Pair.second);
4124 for (
size_t ValueID = 0; ValueID < GUIDList.size(); ValueID++) {
4125 const auto GUID = GUIDList[ValueID];
4129 const auto *
Value = ValueList[ValueID];
4130 TheModule->insertGUID(
Value, GUID);
4139 if (!SeenGUIDList && !UpgradedGUIDs && (UseStrtab || SeenValueSymbolTable))
4144 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
4145 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
4155void BitcodeReader::upgradeGUIDs() {
4156 assert(!SeenGUIDList && !UpgradedGUIDs);
4157 UpgradedGUIDs =
true;
4158 for (GlobalVariable &GV : TheModule->globals()) {
4163 for (
Function &
F : TheModule->functions()) {
4164 if (
F.isDeclaration())
4166 TheModule->insertGUID(&
F,
F.getGUIDOrFallback());
4175void BitcodeReader::attachUpgradedGUIDMetadata(GlobalObject &GO) {
4179 if (
auto GUID = TheModule->getGUID(&GO))
4181 LLVMContext::MD_guid,
4183 Type::getInt64Ty(
Context), *GUID))}));
4190Error BitcodeReader::rememberAndSkipFunctionBodies() {
4195 return error(
"Could not find function in stream");
4197 if (!SeenFirstFunctionBody)
4198 return error(
"Trying to materialize functions before seeing function blocks");
4202 assert(SeenValueSymbolTable);
4205 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4208 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4210 switch (
Entry.Kind) {
4212 return error(
"Expect SubBlock");
4216 return error(
"Expect function block");
4218 if (
Error Err = rememberAndSkipFunctionBody())
4227Error BitcodeReaderBase::readBlockInfo() {
4228 Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
4230 if (!MaybeNewBlockInfo)
4232 std::optional<BitstreamBlockInfo> NewBlockInfo =
4233 std::move(MaybeNewBlockInfo.
get());
4235 return error(
"Malformed block");
4236 BlockInfo = std::move(*NewBlockInfo);
4240Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
4244 std::tie(Name, Record) = readNameFromStrtab(Record);
4247 return error(
"Invalid comdat record");
4249 std::string OldFormatName;
4252 return error(
"Invalid comdat record");
4253 unsigned ComdatNameSize =
Record[1];
4254 if (ComdatNameSize >
Record.size() - 2)
4255 return error(
"Comdat name size too large");
4256 OldFormatName.reserve(ComdatNameSize);
4257 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4258 OldFormatName += (
char)
Record[2 + i];
4259 Name = OldFormatName;
4261 Comdat *
C = TheModule->getOrInsertComdat(Name);
4262 C->setSelectionKind(SK);
4263 ComdatList.push_back(
C);
4277 Meta.NoAddress =
true;
4279 Meta.NoHWAddress =
true;
4283 Meta.IsDynInit =
true;
4287Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
4295 std::tie(Name, Record) = readNameFromStrtab(Record);
4298 return error(
"Invalid global variable record");
4299 unsigned TyID =
Record[0];
4300 Type *Ty = getTypeByID(TyID);
4302 return error(
"Invalid global variable record");
4304 bool explicitType =
Record[1] & 2;
4310 return error(
"Invalid type for value");
4312 TyID = getContainedTypeID(TyID);
4313 Ty = getTypeByID(TyID);
4315 return error(
"Missing element type for old-style global");
4321 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
4325 if (Record[5] - 1 >= SectionTable.size())
4326 return error(
"Invalid ID");
4335 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
4343 bool ExternallyInitialized =
false;
4345 ExternallyInitialized =
Record[9];
4347 GlobalVariable *NewGV =
4357 if (
Record.size() > 10) {
4369 if (
unsigned InitID = Record[2])
4370 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4372 if (
Record.size() > 11) {
4373 if (
unsigned ComdatID = Record[11]) {
4374 if (ComdatID > ComdatList.size())
4375 return error(
"Invalid global variable comdat ID");
4376 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4379 ImplicitComdatObjects.
insert(NewGV);
4382 if (
Record.size() > 12) {
4387 if (
Record.size() > 13) {
4396 if (
Record.size() > 16 && Record[16]) {
4397 llvm::GlobalValue::SanitizerMetadata
Meta =
4402 if (
Record.size() > 17 && Record[17]) {
4406 return error(
"Invalid global variable code model");
4412void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4413 if (ValueTypeCallback) {
4414 (*ValueTypeCallback)(
4415 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4416 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4420Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4426 std::tie(Name, Record) = readNameFromStrtab(Record);
4429 return error(
"Invalid function record");
4430 unsigned FTyID =
Record[0];
4431 Type *FTy = getTypeByID(FTyID);
4433 return error(
"Invalid function record");
4435 FTyID = getContainedTypeID(FTyID, 0);
4436 FTy = getTypeByID(FTyID);
4438 return error(
"Missing element type for old-style function");
4442 return error(
"Invalid type for value");
4443 auto CC =
static_cast<CallingConv::ID
>(
Record[1]);
4444 if (
CC & ~CallingConv::MaxID)
4445 return error(
"Invalid calling convention ID");
4447 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4453 AddrSpace, Name, TheModule);
4456 "Incorrect fully specified type provided for function");
4457 FunctionTypeIDs[
Func] = FTyID;
4459 Func->setCallingConv(
CC);
4460 bool isProto =
Record[2];
4464 callValueTypeCallback(Func, FTyID);
4469 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4470 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4471 Attribute::InAlloca}) {
4472 if (!
Func->hasParamAttribute(i, Kind))
4475 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4478 Func->removeParamAttr(i, Kind);
4480 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4481 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4483 return error(
"Missing param element type for attribute upgrade");
4487 case Attribute::ByVal:
4488 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
4490 case Attribute::StructRet:
4491 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
4493 case Attribute::InAlloca:
4494 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
4500 Func->addParamAttr(i, NewAttr);
4504 if (
Func->getCallingConv() == CallingConv::X86_INTR &&
4505 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4506 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4507 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4509 return error(
"Missing param element type for x86_intrcc upgrade");
4511 Func->addParamAttr(0, NewAttr);
4515 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
4518 Func->setAlignment(*Alignment);
4520 if (Record[6] - 1 >= SectionTable.size())
4521 return error(
"Invalid ID");
4522 Func->setSection(SectionTable[Record[6] - 1]);
4526 if (!
Func->hasLocalLinkage())
4528 if (
Record.size() > 8 && Record[8]) {
4529 if (Record[8] - 1 >= GCTable.size())
4530 return error(
"Invalid ID");
4531 Func->setGC(GCTable[Record[8] - 1]);
4536 Func->setUnnamedAddr(UnnamedAddr);
4538 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4540 OperandInfo.Prologue =
Record[10];
4542 if (
Record.size() > 11) {
4544 if (!
Func->hasLocalLinkage()) {
4551 if (
Record.size() > 12) {
4552 if (
unsigned ComdatID = Record[12]) {
4553 if (ComdatID > ComdatList.size())
4554 return error(
"Invalid function comdat ID");
4555 Func->setComdat(ComdatList[ComdatID - 1]);
4558 ImplicitComdatObjects.
insert(Func);
4562 OperandInfo.Prefix =
Record[13];
4565 OperandInfo.PersonalityFn =
Record[14];
4567 if (
Record.size() > 15) {
4577 Record[17] + Record[18] <= Strtab.
size()) {
4578 Func->setPartition(StringRef(Strtab.
data() + Record[17], Record[18]));
4581 if (
Record.size() > 19) {
4582 MaybeAlign PrefAlignment;
4583 if (
Error Err = parseAlignmentValue(Record[19], PrefAlignment))
4585 Func->setPreferredAlignment(PrefAlignment);
4588 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4590 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4591 FunctionOperands.push_back(OperandInfo);
4596 Func->setIsMaterializable(
true);
4597 FunctionsWithBodies.push_back(Func);
4598 DeferredFunctionInfo[
Func] = 0;
4603Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4604 unsigned BitCode, ArrayRef<uint64_t> Record) {
4614 std::tie(Name, Record) = readNameFromStrtab(Record);
4617 if (
Record.size() < (3 + (
unsigned)NewRecord))
4618 return error(
"Invalid global indirect symbol record");
4623 return error(
"Invalid global indirect symbol record");
4629 return error(
"Invalid type for value");
4630 AddrSpace = PTy->getAddressSpace();
4632 Ty = getTypeByID(
TypeID);
4634 return error(
"Missing element type for old-style indirect symbol");
4636 AddrSpace =
Record[OpNum++];
4639 auto Val =
Record[OpNum++];
4648 nullptr, TheModule);
4652 if (OpNum !=
Record.size()) {
4653 auto VisInd = OpNum++;
4659 if (OpNum !=
Record.size()) {
4660 auto S =
Record[OpNum++];
4667 if (OpNum !=
Record.size())
4669 if (OpNum !=
Record.size())
4672 if (OpNum !=
Record.size())
4677 if (OpNum + 1 <
Record.size()) {
4679 if (Record[OpNum] + Record[OpNum + 1] > Strtab.
size())
4680 return error(
"Malformed partition, too large.");
4682 StringRef(Strtab.
data() + Record[OpNum], Record[OpNum + 1]));
4686 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4691 bool ShouldLazyLoadMetadata,
4692 ParserCallbacks Callbacks) {
4693 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4700 SmallVector<uint64_t, 64>
Record;
4704 bool ResolvedDataLayout =
false;
4709 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4712 Module::GlobalAsmProperties Props;
4714 auto ResolveDataLayout = [&]() ->
Error {
4715 if (ResolvedDataLayout)
4719 ResolvedDataLayout =
true;
4723 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4727 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4728 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4729 TentativeDataLayoutStr = *LayoutOverride;
4737 TheModule->setDataLayout(MaybeDL.
get());
4743 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
4746 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
4748 switch (
Entry.Kind) {
4750 return error(
"Malformed block");
4752 if (
Error Err = ResolveDataLayout())
4754 return globalCleanup();
4763 if (
Error Err = readBlockInfo())
4767 if (
Error Err = parseAttributeBlock())
4771 if (
Error Err = parseAttributeGroupBlock())
4775 if (
Error Err = parseTypeTable())
4779 if (!SeenValueSymbolTable) {
4785 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4786 if (
Error Err = parseValueSymbolTable())
4788 SeenValueSymbolTable =
true;
4798 if (
Error Err = parseConstants())
4800 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4804 if (ShouldLazyLoadMetadata) {
4805 if (
Error Err = rememberAndSkipMetadata())
4809 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4810 if (
Error Err = MDLoader->parseModuleMetadata())
4814 if (
Error Err = MDLoader->parseMetadataKinds())
4818 if (
Error Err = ResolveDataLayout())
4823 if (!SeenFirstFunctionBody) {
4824 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4825 if (
Error Err = globalCleanup())
4827 SeenFirstFunctionBody =
true;
4830 if (VSTOffset > 0) {
4834 if (!SeenValueSymbolTable) {
4835 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4837 SeenValueSymbolTable =
true;
4859 if (
Error Err = rememberAndSkipFunctionBody())
4866 if (SeenValueSymbolTable) {
4870 return globalCleanup();
4874 if (
Error Err = parseUseLists())
4878 if (
Error Err = parseOperandBundleTags())
4882 if (
Error Err = parseSyncScopeNames())
4894 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
4897 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4900 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4903 UseRelativeIDs = *VersionOrErr >= 1;
4907 if (ResolvedDataLayout)
4908 return error(
"target triple too late in module");
4911 return error(
"Invalid triple record");
4912 TheModule->setTargetTriple(Triple(std::move(S)));
4916 if (ResolvedDataLayout)
4917 return error(
"datalayout too late in module");
4919 return error(
"Invalid data layout record");
4925 return error(
"Invalid module asm record");
4926 size_t SepPos = Str.find(
'\0');
4927 if (SepPos == std::string::npos)
4928 return error(
"Invalid module asm record");
4929 if (!Props.
set(StringRef(Str.data(), SepPos), Str.substr(SepPos + 1)))
4930 return error(
"Unknown module asm property");
4936 return error(
"Invalid asm record");
4937 TheModule->appendModuleInlineAsm(Module::GlobalAsmFragment(S, Props));
4945 return error(
"Invalid deplib record");
4952 return error(
"Invalid section name record");
4953 SectionTable.push_back(S);
4959 return error(
"Invalid gcname record");
4960 GCTable.push_back(S);
4964 if (
Error Err = parseComdatRecord(Record))
4973 if (
Error Err = parseGlobalVarRecord(Record))
4977 if (
Error Err = ResolveDataLayout())
4979 if (
Error Err = parseFunctionRecord(Record))
4985 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4991 return error(
"Invalid vstoffset record");
4995 VSTOffset =
Record[0] - 1;
5000 SeenGUIDList =
true;
5001 GUIDList.reserve(GUIDList.size() +
Record.size() / 2);
5002 for (
size_t i = 0; i <
Record.size(); i += 2)
5003 GUIDList.push_back(Record[i] << 32 | Record[i + 1]);
5009 return error(
"Invalid source filename record");
5010 TheModule->setSourceFileName(
ValueName);
5016 this->ValueTypeCallback = std::nullopt;
5020Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
5022 ParserCallbacks Callbacks) {
5024 MetadataLoaderCallbacks MDCallbacks;
5025 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(ID); };
5027 return getContainedTypeID(
I, J);
5030 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
5032 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
5035Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
5037 return error(
"Load/Store operand is not a pointer type");
5038 if (!PointerType::isLoadableOrStorableType(ValType))
5039 return error(
"Cannot load/store from pointer");
5043Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
5044 ArrayRef<unsigned> ArgTyIDs) {
5046 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
5047 for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
5048 Attribute::InAlloca}) {
5049 if (!
Attrs.hasParamAttr(i, Kind) ||
5050 Attrs.getParamAttr(i, Kind).getValueAsType())
5053 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
5055 return error(
"Missing element type for typed attribute upgrade");
5059 case Attribute::ByVal:
5060 NewAttr = Attribute::getWithByValType(
Context, PtrEltTy);
5062 case Attribute::StructRet:
5063 NewAttr = Attribute::getWithStructRetType(
Context, PtrEltTy);
5065 case Attribute::InAlloca:
5066 NewAttr = Attribute::getWithInAllocaType(
Context, PtrEltTy);
5079 for (
const InlineAsm::ConstraintInfo &CI :
IA->ParseConstraints()) {
5083 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
5084 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5086 return error(
"Missing element type for inline asm upgrade");
5089 Attribute::get(
Context, Attribute::ElementType, ElemTy));
5097 case Intrinsic::preserve_array_access_index:
5098 case Intrinsic::preserve_struct_access_index:
5099 case Intrinsic::aarch64_ldaxr:
5100 case Intrinsic::aarch64_ldxr:
5101 case Intrinsic::aarch64_stlxr:
5102 case Intrinsic::aarch64_stxr:
5103 case Intrinsic::arm_ldaex:
5104 case Intrinsic::arm_ldrex:
5105 case Intrinsic::arm_stlex:
5106 case Intrinsic::arm_strex: {
5109 case Intrinsic::aarch64_stlxr:
5110 case Intrinsic::aarch64_stxr:
5111 case Intrinsic::arm_stlex:
5112 case Intrinsic::arm_strex:
5119 if (!
Attrs.getParamElementType(ArgNo)) {
5120 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
5122 return error(
"Missing element type for elementtype upgrade");
5142 if (MDLoader->hasFwdRefs())
5143 return error(
"Invalid function metadata: incoming forward references");
5145 InstructionList.
clear();
5146 unsigned ModuleValueListSize = ValueList.
size();
5147 unsigned ModuleMDLoaderSize = MDLoader->size();
5151 unsigned FTyID = FunctionTypeIDs[
F];
5152 for (Argument &
I :
F->args()) {
5153 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
5154 assert(
I.getType() == getTypeByID(ArgTyID) &&
5155 "Incorrect fully specified type for Function Argument");
5159 unsigned NextValueNo = ValueList.
size();
5161 unsigned CurBBNo = 0;
5166 SmallMapVector<std::pair<BasicBlock *, BasicBlock *>,
BasicBlock *, 4>
5170 auto getLastInstruction = [&]() -> Instruction * {
5171 if (CurBB && !CurBB->
empty())
5172 return &CurBB->
back();
5173 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
5174 !FunctionBBs[CurBBNo - 1]->
empty())
5175 return &FunctionBBs[CurBBNo - 1]->back();
5179 std::vector<OperandBundleDef> OperandBundles;
5182 SmallVector<uint64_t, 64>
Record;
5185 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
5188 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
5190 switch (
Entry.Kind) {
5192 return error(
"Malformed block");
5194 goto OutOfRecordLoop;
5203 if (
Error Err = parseConstants())
5205 NextValueNo = ValueList.
size();
5208 if (
Error Err = parseValueSymbolTable())
5212 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
5216 assert(DeferredMetadataInfo.empty() &&
5217 "Must read all module-level metadata before function-level");
5218 if (
Error Err = MDLoader->parseFunctionMetadata())
5222 if (
Error Err = parseUseLists())
5236 unsigned ResTypeID = InvalidTypeID;
5237 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
5240 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5242 return error(
"Invalid value");
5244 if (
Record.empty() || Record[0] == 0)
5245 return error(
"Invalid declareblocks record");
5247 FunctionBBs.resize(Record[0]);
5250 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5251 if (BBFRI == BasicBlockFwdRefs.
end()) {
5252 for (BasicBlock *&BB : FunctionBBs)
5255 auto &BBRefs = BBFRI->second;
5257 if (BBRefs.size() > FunctionBBs.size())
5258 return error(
"Invalid ID");
5259 assert(!BBRefs.empty() &&
"Unexpected empty array");
5260 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5261 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size();
I !=
E;
5263 if (
I < RE && BBRefs[
I]) {
5264 BBRefs[
I]->insertInto(
F);
5265 FunctionBBs[
I] = BBRefs[
I];
5271 BasicBlockFwdRefs.
erase(BBFRI);
5274 CurBB = FunctionBBs[0];
5281 return error(
"Invalid blockaddr users record");
5297 BackwardRefFunctions.push_back(
F);
5299 return error(
"Invalid blockaddr users record");
5306 I = getLastInstruction();
5309 return error(
"Invalid debug_loc_again record");
5310 I->setDebugLoc(LastLoc);
5315 I = getLastInstruction();
5317 return error(
"Invalid debug loc record");
5325 MDNode *
Scope =
nullptr, *
IA =
nullptr;
5328 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5330 return error(
"Invalid debug loc record");
5334 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5336 return error(
"Invalid debug loc record");
5339 if (
Record.size() >= 8 && Record[7])
5340 IRLayers = MDLoader->getMetadataFwdRefOrLoad(Record[7] - 1);
5342 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5343 isImplicitCode, AtomGroup, AtomRank, IRLayers);
5344 I->setDebugLoc(LastLoc);
5352 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5354 return error(
"Invalid unary operator record");
5358 return error(
"Invalid unary operator record");
5362 if (OpNum <
Record.size()) {
5366 I->setFastMathFlags(FMF);
5375 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS,
TypeID, CurBB) ||
5379 return error(
"Invalid binary operator record");
5383 return error(
"Invalid binary operator record");
5387 if (OpNum <
Record.size()) {
5388 if (
Opc == Instruction::Add ||
5389 Opc == Instruction::Sub ||
5390 Opc == Instruction::Mul ||
5391 Opc == Instruction::Shl) {
5396 }
else if (
Opc == Instruction::SDiv ||
5397 Opc == Instruction::UDiv ||
5398 Opc == Instruction::LShr ||
5399 Opc == Instruction::AShr) {
5402 }
else if (
Opc == Instruction::Or) {
5408 I->setFastMathFlags(FMF);
5417 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5418 OpNum + 1 >
Record.size())
5419 return error(
"Invalid cast record");
5421 ResTypeID =
Record[OpNum++];
5422 Type *ResTy = getTypeByID(ResTypeID);
5425 if (
Opc == -1 || !ResTy)
5426 return error(
"Invalid cast record");
5431 assert(CurBB &&
"No current BB?");
5437 return error(
"Invalid cast");
5441 if (OpNum <
Record.size()) {
5442 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5445 }
else if (
Opc == Instruction::Trunc) {
5450 }
else if (
Opc == Instruction::AddrSpaceCast) {
5460 I->setFastMathFlags(FMF);
5479 Ty = getTypeByID(TyID);
5483 TyID = InvalidTypeID;
5488 unsigned BasePtrTypeID;
5489 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5491 return error(
"Invalid gep record");
5494 TyID = getContainedTypeID(BasePtrTypeID);
5495 if (
BasePtr->getType()->isVectorTy())
5496 TyID = getContainedTypeID(TyID);
5497 Ty = getTypeByID(TyID);
5500 SmallVector<Value*, 16> GEPIdx;
5501 while (OpNum !=
Record.size()) {
5504 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5505 return error(
"Invalid gep record");
5516 unsigned SubType = 0;
5517 if (GTI.isStruct()) {
5519 Idx->getType()->isVectorTy()
5524 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5531 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5532 if (
I->getType()->isVectorTy())
5533 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5536 GEP->setNoWrapFlags(NW);
5545 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5546 return error(
"Invalid extractvalue record");
5549 unsigned RecSize =
Record.size();
5550 if (OpNum == RecSize)
5551 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5553 SmallVector<unsigned, 4> EXTRACTVALIdx;
5554 ResTypeID = AggTypeID;
5555 for (; OpNum != RecSize; ++OpNum) {
5560 if (!IsStruct && !IsArray)
5561 return error(
"EXTRACTVAL: Invalid type");
5562 if ((
unsigned)Index != Index)
5563 return error(
"Invalid value");
5565 return error(
"EXTRACTVAL: Invalid struct index");
5567 return error(
"EXTRACTVAL: Invalid array index");
5568 EXTRACTVALIdx.
push_back((
unsigned)Index);
5572 ResTypeID = getContainedTypeID(ResTypeID, Index);
5575 ResTypeID = getContainedTypeID(ResTypeID);
5589 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5590 return error(
"Invalid insertvalue record");
5593 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5594 return error(
"Invalid insertvalue record");
5596 unsigned RecSize =
Record.size();
5597 if (OpNum == RecSize)
5598 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5600 SmallVector<unsigned, 4> INSERTVALIdx;
5602 for (; OpNum != RecSize; ++OpNum) {
5607 if (!IsStruct && !IsArray)
5608 return error(
"INSERTVAL: Invalid type");
5609 if ((
unsigned)Index != Index)
5610 return error(
"Invalid value");
5612 return error(
"INSERTVAL: Invalid struct index");
5614 return error(
"INSERTVAL: Invalid array index");
5616 INSERTVALIdx.
push_back((
unsigned)Index);
5624 return error(
"Inserted value type doesn't match aggregate type");
5627 ResTypeID = AggTypeID;
5639 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal,
TypeID,
5641 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(),
TypeID,
5643 popValue(Record, OpNum, NextValueNo, CondType,
5644 getVirtualTypeID(CondType),
Cond, CurBB))
5645 return error(
"Invalid select record");
5658 unsigned ValTypeID, CondTypeID;
5659 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5661 popValue(Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5663 getValueTypePair(Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5664 return error(
"Invalid vector select record");
5667 if (VectorType* vector_type =
5670 if (vector_type->getElementType() != Type::getInt1Ty(
Context))
5671 return error(
"Invalid type for value");
5675 return error(
"Invalid type for value");
5679 ResTypeID = ValTypeID;
5684 I->setFastMathFlags(FMF);
5692 unsigned VecTypeID, IdxTypeID;
5693 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5694 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5695 return error(
"Invalid extractelement record");
5697 return error(
"Invalid type for value");
5699 ResTypeID = getContainedTypeID(VecTypeID);
5707 unsigned VecTypeID, IdxTypeID;
5708 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5709 return error(
"Invalid insertelement record");
5711 return error(
"Invalid type for value");
5712 if (popValue(Record, OpNum, NextValueNo,
5714 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5715 getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5716 return error(
"Invalid insert element record");
5718 ResTypeID = VecTypeID;
5726 unsigned BaseTypeID, ValTypeID, OffsetTypeID;
5727 if (getValueTypePair(Record, OpNum, NextValueNo,
Base, BaseTypeID,
5729 getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB) ||
5730 getValueTypePair(Record, OpNum, NextValueNo,
Offset, OffsetTypeID,
5732 return error(
"Invalid bitinsert record");
5733 if (
const char *Reason =
5735 return error(Reason);
5737 ResTypeID = BaseTypeID;
5745 return error(
"Record is empty for bitextract");
5749 return error(
"Invalid bitextract result type");
5751 unsigned SrcTypeID, OffsetTypeID;
5752 if (getValueTypePair(Record, OpNum, NextValueNo, Src, SrcTypeID, CurBB) ||
5753 getValueTypePair(Record, OpNum, NextValueNo,
Offset, OffsetTypeID,
5755 return error(
"Invalid bitextract record");
5756 if (
const char *Reason =
5758 return error(Reason);
5768 unsigned Vec1TypeID;
5769 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5771 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5773 return error(
"Invalid shufflevector record");
5775 unsigned MaskTypeID;
5776 if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5777 return error(
"Invalid shufflevector record");
5779 return error(
"Invalid type for value");
5781 I =
new ShuffleVectorInst(Vec1, Vec2, Mask);
5783 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5798 if (getValueTypePair(Record, OpNum, NextValueNo,
LHS, LHSTypeID, CurBB) ||
5799 popValue(Record, OpNum, NextValueNo,
LHS->
getType(), LHSTypeID,
RHS,
5801 return error(
"Invalid comparison record");
5803 if (OpNum >=
Record.size())
5805 "Invalid record: operand number exceeded available operands");
5810 if (IsFP &&
Record.size() > OpNum+1)
5815 return error(
"Invalid fcmp predicate");
5816 I =
new FCmpInst(PredVal,
LHS,
RHS);
5819 return error(
"Invalid icmp predicate");
5820 I =
new ICmpInst(PredVal,
LHS,
RHS);
5821 if (
Record.size() > OpNum + 1 &&
5826 if (OpNum + 1 !=
Record.size())
5827 return error(
"Invalid comparison record");
5829 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5831 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5834 I->setFastMathFlags(FMF);
5851 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5852 return error(
"Invalid ret record");
5853 if (OpNum !=
Record.size())
5854 return error(
"Invalid ret record");
5862 return error(
"Invalid br record");
5863 BasicBlock *TrueDest = getBasicBlock(Record[0]);
5865 return error(
"Invalid br record");
5867 if (
Record.size() == 1) {
5872 BasicBlock *FalseDest = getBasicBlock(Record[1]);
5875 getVirtualTypeID(CondType), CurBB);
5876 if (!FalseDest || !
Cond)
5877 return error(
"Invalid br record");
5885 return error(
"Invalid cleanupret record");
5888 Value *CleanupPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5889 getVirtualTypeID(TokenTy), CurBB);
5891 return error(
"Invalid cleanupret record");
5893 if (
Record.size() == 2) {
5894 UnwindDest = getBasicBlock(Record[Idx++]);
5896 return error(
"Invalid cleanupret record");
5905 return error(
"Invalid catchret record");
5908 Value *CatchPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5909 getVirtualTypeID(TokenTy), CurBB);
5911 return error(
"Invalid catchret record");
5912 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5914 return error(
"Invalid catchret record");
5923 return error(
"Invalid catchswitch record");
5928 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5929 getVirtualTypeID(TokenTy), CurBB);
5931 return error(
"Invalid catchswitch record");
5936 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5937 BasicBlock *BB = getBasicBlock(Record[Idx++]);
5939 return error(
"Invalid catchswitch record");
5944 if (Idx + 1 ==
Record.size()) {
5945 UnwindDest = getBasicBlock(Record[Idx++]);
5947 return error(
"Invalid catchswitch record");
5950 if (
Record.size() != Idx)
5951 return error(
"Invalid catchswitch record");
5955 for (BasicBlock *Handler : Handlers)
5956 CatchSwitch->addHandler(Handler);
5958 ResTypeID = getVirtualTypeID(
I->getType());
5966 return error(
"Invalid catchpad/cleanuppad record");
5971 Value *ParentPad =
getValue(Record, Idx++, NextValueNo, TokenTy,
5972 getVirtualTypeID(TokenTy), CurBB);
5974 return error(
"Invalid catchpad/cleanuppad record");
5976 unsigned NumArgOperands =
Record[
Idx++];
5978 SmallVector<Value *, 2>
Args;
5979 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5982 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
nullptr))
5983 return error(
"Invalid catchpad/cleanuppad record");
5984 Args.push_back(Val);
5987 if (
Record.size() != Idx)
5988 return error(
"Invalid catchpad/cleanuppad record");
5994 ResTypeID = getVirtualTypeID(
I->getType());
6000 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
6006 unsigned OpTyID =
Record[1];
6007 Type *OpTy = getTypeByID(OpTyID);
6013 return error(
"Invalid switch record");
6015 unsigned NumCases =
Record[4];
6020 unsigned CurIdx = 5;
6021 for (
unsigned i = 0; i != NumCases; ++i) {
6023 unsigned NumItems =
Record[CurIdx++];
6024 for (
unsigned ci = 0; ci != NumItems; ++ci) {
6025 bool isSingleNumber =
Record[CurIdx++];
6028 unsigned ActiveWords = 1;
6029 if (ValueBitWidth > 64)
6030 ActiveWords =
Record[CurIdx++];
6033 CurIdx += ActiveWords;
6035 if (!isSingleNumber) {
6037 if (ValueBitWidth > 64)
6038 ActiveWords =
Record[CurIdx++];
6041 CurIdx += ActiveWords;
6052 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
6053 for (ConstantInt *Cst : CaseVals)
6054 SI->addCase(Cst, DestBB);
6063 return error(
"Invalid switch record");
6064 unsigned OpTyID =
Record[0];
6065 Type *OpTy = getTypeByID(OpTyID);
6069 return error(
"Invalid switch record");
6070 unsigned NumCases = (
Record.size()-3)/2;
6073 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
6075 getFnValueByID(Record[3+i*2], OpTy, OpTyID,
nullptr));
6076 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
6077 if (!CaseVal || !DestBB) {
6079 return error(
"Invalid switch record");
6081 SI->addCase(CaseVal, DestBB);
6088 return error(
"Invalid indirectbr record");
6089 unsigned OpTyID =
Record[0];
6090 Type *OpTy = getTypeByID(OpTyID);
6093 return error(
"Invalid indirectbr record");
6094 unsigned NumDests =
Record.size()-2;
6097 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
6098 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
6102 return error(
"Invalid indirectbr record");
6112 return error(
"Invalid invoke record");
6115 unsigned CCInfo =
Record[OpNum++];
6116 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
6117 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
6119 unsigned FTyID = InvalidTypeID;
6120 FunctionType *FTy =
nullptr;
6121 if ((CCInfo >> 13) & 1) {
6125 return error(
"Explicit invoke type is not a function type");
6129 unsigned CalleeTypeID;
6130 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6132 return error(
"Invalid invoke record");
6136 return error(
"Callee is not a pointer");
6138 FTyID = getContainedTypeID(CalleeTypeID);
6141 return error(
"Callee is not of pointer to function type");
6143 if (
Record.size() < FTy->getNumParams() + OpNum)
6144 return error(
"Insufficient operands to call");
6146 SmallVector<Value*, 16>
Ops;
6147 SmallVector<unsigned, 16> ArgTyIDs;
6148 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6149 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6150 Ops.push_back(
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6154 return error(
"Invalid invoke record");
6157 if (!FTy->isVarArg()) {
6158 if (
Record.size() != OpNum)
6159 return error(
"Invalid invoke record");
6162 while (OpNum !=
Record.size()) {
6165 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6166 return error(
"Invalid invoke record");
6173 if (!OperandBundles.empty())
6178 ResTypeID = getContainedTypeID(FTyID);
6179 OperandBundles.clear();
6182 static_cast<CallingConv::ID
>(CallingConv::MaxID & CCInfo));
6193 Value *Val =
nullptr;
6195 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
6196 return error(
"Invalid resume record");
6205 unsigned CCInfo =
Record[OpNum++];
6207 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
6208 unsigned NumIndirectDests =
Record[OpNum++];
6209 SmallVector<BasicBlock *, 16> IndirectDests;
6210 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
6211 IndirectDests.
push_back(getBasicBlock(Record[OpNum++]));
6213 unsigned FTyID = InvalidTypeID;
6214 FunctionType *FTy =
nullptr;
6219 return error(
"Explicit call type is not a function type");
6223 unsigned CalleeTypeID;
6224 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6226 return error(
"Invalid callbr record");
6230 return error(
"Callee is not a pointer type");
6232 FTyID = getContainedTypeID(CalleeTypeID);
6235 return error(
"Callee is not of pointer to function type");
6237 if (
Record.size() < FTy->getNumParams() + OpNum)
6238 return error(
"Insufficient operands to call");
6240 SmallVector<Value*, 16>
Args;
6241 SmallVector<unsigned, 16> ArgTyIDs;
6243 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6245 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6246 if (FTy->getParamType(i)->isLabelTy())
6247 Arg = getBasicBlock(Record[OpNum]);
6249 Arg =
getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
6252 return error(
"Invalid callbr record");
6253 Args.push_back(Arg);
6258 if (!FTy->isVarArg()) {
6259 if (OpNum !=
Record.size())
6260 return error(
"Invalid callbr record");
6262 while (OpNum !=
Record.size()) {
6265 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6266 return error(
"Invalid callbr record");
6273 if (!OperandBundles.empty())
6278 auto IsLabelConstraint = [](
const InlineAsm::ConstraintInfo &CI) {
6281 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6286 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6287 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6288 unsigned LabelNo = ArgNo - FirstBlockArg;
6290 if (!BA || BA->getFunction() !=
F ||
6291 LabelNo > IndirectDests.
size() ||
6292 BA->getBasicBlock() != IndirectDests[LabelNo])
6293 return error(
"callbr argument does not match indirect dest");
6298 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6302 for (
Value *Arg : Args)
6305 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6308 std::string Constraints =
IA->getConstraintString().str();
6311 for (
const auto &CI : ConstraintInfo) {
6313 if (ArgNo >= FirstBlockArg)
6314 Constraints.insert(Pos,
"!");
6319 Pos = Constraints.find(
',', Pos);
6320 if (Pos == std::string::npos)
6326 IA->hasSideEffects(),
IA->isAlignStack(),
6327 IA->getDialect(),
IA->canThrow());
6333 ResTypeID = getContainedTypeID(FTyID);
6334 OperandBundles.clear();
6351 return error(
"Invalid phi record");
6353 unsigned TyID =
Record[0];
6354 Type *Ty = getTypeByID(TyID);
6356 return error(
"Invalid phi record");
6361 size_t NumArgs = (
Record.size() - 1) / 2;
6365 return error(
"Invalid phi record");
6369 SmallDenseMap<BasicBlock *, Value *>
Args;
6370 for (
unsigned i = 0; i != NumArgs; i++) {
6371 BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6374 return error(
"Invalid phi BB");
6381 auto It =
Args.find(BB);
6383 if (It !=
Args.end()) {
6397 if (!PhiConstExprBB)
6399 EdgeBB = PhiConstExprBB;
6407 V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6409 V =
getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6413 return error(
"Invalid phi record");
6416 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6417 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6418 PhiConstExprBB =
nullptr;
6421 Args.insert({BB,
V});
6427 if (
Record.size() % 2 == 0) {
6431 I->setFastMathFlags(FMF);
6443 return error(
"Invalid landingpad record");
6447 return error(
"Invalid landingpad record");
6450 Type *Ty = getTypeByID(ResTypeID);
6452 return error(
"Invalid landingpad record");
6454 Value *PersFn =
nullptr;
6455 unsigned PersFnTypeID;
6456 if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6458 return error(
"Invalid landingpad record");
6460 if (!
F->hasPersonalityFn())
6463 return error(
"Personality function mismatch");
6470 for (
unsigned J = 0; J != NumClauses; ++J) {
6476 if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6479 return error(
"Invalid landingpad record");
6484 "Catch clause has a invalid type!");
6487 "Filter clause has invalid type!");
6498 return error(
"Invalid alloca record");
6499 using APV = AllocaPackedValues;
6503 unsigned TyID =
Record[0];
6504 Type *Ty = getTypeByID(TyID);
6506 TyID = getContainedTypeID(TyID);
6507 Ty = getTypeByID(TyID);
6509 return error(
"Missing element type for old-style alloca");
6511 unsigned OpTyID =
Record[1];
6512 Type *OpTy = getTypeByID(OpTyID);
6513 Value *
Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6518 if (
Error Err = parseAlignmentValue(AlignExp, Align)) {
6522 return error(
"Invalid alloca record");
6524 const DataLayout &
DL = TheModule->getDataLayout();
6525 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6528 return error(
"alloca of unsized type");
6530 Align =
DL.getPrefTypeAlign(Ty);
6532 if (!
Size->getType()->isIntegerTy())
6533 return error(
"alloca element count must have integer type");
6535 AllocaInst *AI =
new AllocaInst(Ty, AS,
Size, *Align);
6539 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6547 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6548 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6549 return error(
"Invalid load record");
6552 return error(
"Load operand is not a pointer type");
6555 if (OpNum + 3 ==
Record.size()) {
6556 ResTypeID =
Record[OpNum++];
6557 Ty = getTypeByID(ResTypeID);
6559 ResTypeID = getContainedTypeID(OpTypeID);
6560 Ty = getTypeByID(ResTypeID);
6564 return error(
"Missing load type");
6566 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6570 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6573 return error(
"load of unsized type");
6575 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6576 I =
new LoadInst(Ty,
Op,
"", Record[OpNum + 1], *Align);
6585 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6586 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size() &&
6587 OpNum + 6 !=
Record.size()))
6588 return error(
"Invalid load atomic record");
6591 return error(
"Load operand is not a pointer type");
6594 if (
Record.size() >= OpNum + 5) {
6595 ResTypeID =
Record[OpNum++];
6596 Ty = getTypeByID(ResTypeID);
6598 ResTypeID = getContainedTypeID(OpTypeID);
6599 Ty = getTypeByID(ResTypeID);
6603 return error(
"Missing atomic load type");
6605 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6609 if (Ordering == AtomicOrdering::NotAtomic ||
6610 Ordering == AtomicOrdering::Release ||
6611 Ordering == AtomicOrdering::AcquireRelease)
6612 return error(
"Invalid load atomic record");
6613 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6614 return error(
"Invalid load atomic record");
6615 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6616 bool IsElementwise =
Record.size() > OpNum + 4 &&
Record[OpNum + 4];
6619 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6622 return error(
"Alignment missing from atomic load");
6625 LoadStoreInstProperties{
Record[OpNum + 1] != 0, *
Align,
6635 unsigned PtrTypeID, ValTypeID;
6636 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6637 return error(
"Invalid store record");
6640 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6641 return error(
"Invalid store record");
6643 ValTypeID = getContainedTypeID(PtrTypeID);
6644 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6645 ValTypeID, Val, CurBB))
6646 return error(
"Invalid store record");
6649 if (OpNum + 2 !=
Record.size())
6650 return error(
"Invalid store record");
6655 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6658 return error(
"store of unsized type");
6660 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6661 I =
new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6671 unsigned PtrTypeID, ValTypeID;
6672 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6674 return error(
"Invalid store atomic record");
6676 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6677 return error(
"Invalid store atomic record");
6679 ValTypeID = getContainedTypeID(PtrTypeID);
6680 if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6681 ValTypeID, Val, CurBB))
6682 return error(
"Invalid store atomic record");
6685 if (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size())
6686 return error(
"Invalid store atomic record");
6691 if (Ordering == AtomicOrdering::NotAtomic ||
6692 Ordering == AtomicOrdering::Acquire ||
6693 Ordering == AtomicOrdering::AcquireRelease)
6694 return error(
"Invalid store atomic record");
6695 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6696 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6697 return error(
"Invalid store atomic record");
6700 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
6703 return error(
"Alignment missing from atomic store");
6705 bool IsElementwise =
Record.size() > OpNum + 4 &&
Record[OpNum + 4];
6709 LoadStoreInstProperties{
Record[OpNum + 1] != 0, *
Align,
6718 const size_t NumRecords =
Record.size();
6720 Value *Ptr =
nullptr;
6722 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6723 return error(
"Invalid cmpxchg record");
6726 return error(
"Cmpxchg operand is not a pointer type");
6729 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6730 if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6731 CmpTypeID, Cmp, CurBB))
6732 return error(
"Invalid cmpxchg record");
6735 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6737 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6738 return error(
"Invalid cmpxchg record");
6742 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6743 SuccessOrdering == AtomicOrdering::Unordered)
6744 return error(
"Invalid cmpxchg record");
6746 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6748 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6756 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6757 FailureOrdering == AtomicOrdering::Unordered)
6758 return error(
"Invalid cmpxchg record");
6761 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6763 I =
new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6764 FailureOrdering, SSID);
6767 if (NumRecords < 8) {
6771 I->insertInto(CurBB, CurBB->
end());
6773 ResTypeID = CmpTypeID;
6776 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6777 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6786 const size_t NumRecords =
Record.size();
6788 Value *Ptr =
nullptr;
6790 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6791 return error(
"Invalid cmpxchg record");
6794 return error(
"Cmpxchg operand is not a pointer type");
6798 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6799 return error(
"Invalid cmpxchg record");
6801 Value *Val =
nullptr;
6802 if (popValue(Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6804 return error(
"Invalid cmpxchg record");
6806 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6807 return error(
"Invalid cmpxchg record");
6809 const bool IsVol =
Record[OpNum];
6814 return error(
"Invalid cmpxchg success ordering");
6816 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6818 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(), Ptr->
getType()))
6824 return error(
"Invalid cmpxchg failure ordering");
6826 const bool IsWeak =
Record[OpNum + 4];
6830 if (NumRecords == (OpNum + 6)) {
6831 if (
Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6836 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6838 I =
new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6839 FailureOrdering, SSID);
6843 unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(
Context));
6844 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6853 const size_t NumRecords =
Record.size();
6856 Value *Ptr =
nullptr;
6858 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6859 return error(
"Invalid atomicrmw record");
6862 return error(
"Invalid atomicrmw record");
6864 Value *Val =
nullptr;
6865 unsigned ValTypeID = InvalidTypeID;
6867 ValTypeID = getContainedTypeID(PtrTypeID);
6868 if (popValue(Record, OpNum, NextValueNo,
6869 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6870 return error(
"Invalid atomicrmw record");
6872 if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6873 return error(
"Invalid atomicrmw record");
6876 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6877 return error(
"Invalid atomicrmw record");
6879 bool IsElementwise =
false;
6884 return error(
"Invalid atomicrmw record");
6886 const bool IsVol =
Record[OpNum + 1];
6889 if (Ordering == AtomicOrdering::NotAtomic ||
6890 Ordering == AtomicOrdering::Unordered)
6891 return error(
"Invalid atomicrmw record");
6893 const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6897 if (NumRecords == (OpNum + 5)) {
6898 if (
Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6904 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6906 I =
new AtomicRMWInst(
Operation, Ptr, Val, *Alignment, Ordering, SSID,
6908 ResTypeID = ValTypeID;
6916 return error(
"Invalid fence record");
6918 if (Ordering == AtomicOrdering::NotAtomic ||
6919 Ordering == AtomicOrdering::Unordered ||
6920 Ordering == AtomicOrdering::Monotonic)
6921 return error(
"Invalid fence record");
6923 I =
new FenceInst(
Context, Ordering, SSID);
6930 SeenDebugRecord =
true;
6933 return error(
"Invalid dbg record: missing instruction");
6936 Inst->
getParent()->insertDbgRecordBefore(
6947 SeenDebugRecord =
true;
6950 return error(
"Invalid dbg record: missing instruction");
6967 DILocalVariable *Var =
6969 DIExpression *Expr =
6982 unsigned SlotBefore =
Slot;
6983 if (getValueTypePair(Record, Slot, NextValueNo,
V, TyID, CurBB))
6984 return error(
"Invalid dbg record: invalid value");
6986 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6989 RawLocation = getFnMetadataByID(Record[Slot++]);
6992 DbgVariableRecord *DVR =
nullptr;
6996 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6997 DbgVariableRecord::LocationType::Value);
7000 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, DIL,
7001 DbgVariableRecord::LocationType::Declare);
7004 DVR =
new DbgVariableRecord(
7005 RawLocation, Var, Expr, DIL,
7006 DbgVariableRecord::LocationType::DeclareValue);
7010 DIExpression *AddrExpr =
7012 Metadata *Addr = getFnMetadataByID(Record[Slot++]);
7013 DVR =
new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
7026 return error(
"Invalid call record");
7030 unsigned CCInfo =
Record[OpNum++];
7036 return error(
"Fast math flags indicator set for call with no FMF");
7039 unsigned FTyID = InvalidTypeID;
7040 FunctionType *FTy =
nullptr;
7045 return error(
"Explicit call type is not a function type");
7049 unsigned CalleeTypeID;
7050 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
7052 return error(
"Invalid call record");
7056 return error(
"Callee is not a pointer type");
7058 FTyID = getContainedTypeID(CalleeTypeID);
7061 return error(
"Callee is not of pointer to function type");
7063 if (
Record.size() < FTy->getNumParams() + OpNum)
7064 return error(
"Insufficient operands to call");
7066 SmallVector<Value*, 16>
Args;
7067 SmallVector<unsigned, 16> ArgTyIDs;
7069 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
7070 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
7071 if (FTy->getParamType(i)->isLabelTy())
7072 Args.push_back(getBasicBlock(Record[OpNum]));
7075 FTy->getParamType(i), ArgTyID, CurBB));
7078 return error(
"Invalid call record");
7082 if (!FTy->isVarArg()) {
7083 if (OpNum !=
Record.size())
7084 return error(
"Invalid call record");
7086 while (OpNum !=
Record.size()) {
7089 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
7090 return error(
"Invalid call record");
7097 if (!OperandBundles.empty())
7101 ResTypeID = getContainedTypeID(FTyID);
7102 OperandBundles.clear();
7116 SeenDebugIntrinsic =
true;
7119 if (
auto *ListAsValue =
7132 return error(
"Fast-math-flags specified for call without "
7133 "floating-point scalar or vector return type");
7134 I->setFastMathFlags(FMF);
7140 return error(
"Invalid va_arg record");
7141 unsigned OpTyID =
Record[0];
7142 Type *OpTy = getTypeByID(OpTyID);
7145 Type *ResTy = getTypeByID(ResTypeID);
7146 if (!OpTy || !
Op || !ResTy)
7147 return error(
"Invalid va_arg record");
7148 I =
new VAArgInst(
Op, ResTy);
7158 if (
Record.empty() || Record[0] >= BundleTags.size())
7159 return error(
"Invalid operand bundle record");
7161 std::vector<Value *> Inputs;
7164 while (OpNum !=
Record.size()) {
7166 if (getValueOrMetadata(Record, OpNum, NextValueNo,
Op, CurBB))
7167 return error(
"Invalid operand bundle record");
7168 Inputs.push_back(
Op);
7171 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
7179 if (getValueTypePair(Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
7180 return error(
"Invalid freeze record");
7181 if (OpNum !=
Record.size())
7182 return error(
"Invalid freeze record");
7184 I =
new FreezeInst(
Op);
7185 ResTypeID = OpTypeID;
7195 return error(
"Invalid instruction with no BB");
7197 if (!OperandBundles.empty()) {
7199 return error(
"Operand bundles found with no consumer");
7201 I->insertInto(CurBB, CurBB->
end());
7204 if (
I->isTerminator()) {
7206 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
7210 if (!
I->getType()->isVoidTy()) {
7211 assert(
I->getType() == getTypeByID(ResTypeID) &&
7212 "Incorrect result type ID");
7220 if (!OperandBundles.empty())
7221 return error(
"Operand bundles found with no consumer");
7225 if (!
A->getParent()) {
7227 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
7233 return error(
"Never resolved value found in function");
7238 if (MDLoader->hasFwdRefs())
7239 return error(
"Invalid function metadata: outgoing forward refs");
7244 for (
const auto &Pair : ConstExprEdgeBBs) {
7255 ValueList.
shrinkTo(ModuleValueListSize);
7256 MDLoader->shrinkTo(ModuleMDLoaderSize);
7257 std::vector<BasicBlock*>().swap(FunctionBBs);
7262Error BitcodeReader::findFunctionInStream(
7264 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
7265 while (DeferredFunctionInfoIterator->second == 0) {
7270 assert(VSTOffset == 0 || !
F->hasName());
7273 if (
Error Err = rememberAndSkipFunctionBodies())
7279SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
7282 if (Val >= SSIDs.
size())
7291Error BitcodeReader::materialize(GlobalValue *GV) {
7294 if (!
F || !
F->isMaterializable())
7297 auto DFII = DeferredFunctionInfo.
find(
F);
7298 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
7301 if (DFII->second == 0)
7302 if (
Error Err = findFunctionInStream(
F, DFII))
7306 if (
Error Err = materializeMetadata())
7313 if (
Error Err = parseFunctionBody(
F))
7315 F->setIsMaterializable(
false);
7319 if (SeenDebugIntrinsic && SeenDebugRecord)
7320 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7326 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7327 F->setSubprogram(SP);
7332 attachUpgradedGUIDMetadata(*
F);
7335 if (!MDLoader->isStrippingTBAA()) {
7337 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7340 MDLoader->setStripTBAA(
true);
7347 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7348 if (MD->getOperand(0) !=
nullptr &&
isa<MDString>(MD->getOperand(0))) {
7354 unsigned ExpectedNumOperands = 0;
7356 ExpectedNumOperands = 2;
7358 ExpectedNumOperands =
SI->getNumSuccessors();
7360 ExpectedNumOperands = 1;
7364 ExpectedNumOperands = 2;
7371 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7372 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7378 CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7379 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7381 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7382 CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7383 CI->getArgOperand(ArgNo)->getType(),
7384 CI->getParamAttributes(ArgNo)));
7387 if (
Function *OldFn = CI->getCalledFunction()) {
7388 auto It = UpgradedIntrinsics.
find(OldFn);
7389 if (It != UpgradedIntrinsics.
end())
7393 BC && BC->getSrcTy() == BC->getDestTy() &&
7399 CI && CI->isMustTailCall() && CI->getNextNode() == BC) {
7400 BC->replaceAllUsesWith(CI);
7401 BC->eraseFromParent();
7411 return materializeForwardReferencedFunctions();
7414Error BitcodeReader::materializeModule() {
7415 if (
Error Err = materializeMetadata())
7419 WillMaterializeAllForwardRefs =
true;
7424 if (
Error Err = materialize(&
F))
7430 if (LastFunctionBlockBit || NextUnreadBit)
7432 ? LastFunctionBlockBit
7438 if (!BasicBlockFwdRefs.
empty())
7439 return error(
"Never resolved function from blockaddress");
7445 for (
auto &[OldFn, NewFn] : UpgradedIntrinsics) {
7446 for (User *U : OldFn->users()) {
7450 if (OldFn != NewFn) {
7451 if (!OldFn->use_empty())
7452 OldFn->replaceAllUsesWith(NewFn);
7453 OldFn->eraseFromParent();
7456 UpgradedIntrinsics.clear();
7471std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7472 return IdentifiedStructTypes;
7475ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7476 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7477 StringRef ModulePath, std::function<
bool(StringRef)> IsPrevailing,
7478 std::function<
void(ValueInfo)> OnValueInfo)
7479 : BitcodeReaderBase(std::
move(Cursor), Strtab), TheIndex(TheIndex),
7480 ModulePath(ModulePath), IsPrevailing(IsPrevailing),
7481 OnValueInfo(OnValueInfo) {}
7483void ModuleSummaryIndexBitcodeReader::addThisModule() {
7488ModuleSummaryIndexBitcodeReader::getThisModule() {
7492template <
bool AllowNullValueInfo>
7493std::pair<ValueInfo, GlobalValue::GUID>
7494ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7495 auto VGI = ValueIdToValueInfoMap[ValueId];
7502 assert(AllowNullValueInfo || std::get<0>(VGI));
7506void ModuleSummaryIndexBitcodeReader::setValueGUID(
7508 StringRef SourceFileName) {
7510 if (ValueID < DefinedGUIDs.size())
7511 ValueGUID = DefinedGUIDs[ValueID];
7518 auto OriginalNameID = ValueGUID;
7522 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7530 ValueIdToValueInfoMap[ValueID] = std::make_pair(VI, OriginalNameID);
7538Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7540 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7547 if (!MaybeCurrentBit)
7554 SmallVector<uint64_t, 64>
Record;
7563 BitstreamEntry
Entry = MaybeEntry.
get();
7565 switch (
Entry.Kind) {
7568 return error(
"Malformed block");
7584 switch (MaybeRecord.
get()) {
7589 return error(
"Invalid vst_code_entry record");
7590 unsigned ValueID =
Record[0];
7592 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7593 assert(VLI != ValueIdToLinkageMap.
end() &&
7594 "No linkage found for VST entry?");
7603 return error(
"Invalid vst_code_fnentry record");
7604 unsigned ValueID =
Record[0];
7606 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7607 assert(VLI != ValueIdToLinkageMap.
end() &&
7608 "No linkage found for VST entry?");
7616 unsigned ValueID =
Record[0];
7620 ValueIdToValueInfoMap[ValueID] =
7631Error ModuleSummaryIndexBitcodeReader::parseModule() {
7635 SmallVector<uint64_t, 64>
Record;
7636 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7637 unsigned ValueId = 0;
7641 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.
advance();
7644 llvm::BitstreamEntry
Entry = MaybeEntry.
get();
7646 switch (
Entry.Kind) {
7648 return error(
"Malformed block");
7660 if (
Error Err = readBlockInfo())
7666 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7667 !SeenGlobalValSummary) &&
7668 "Expected early VST parse via VSTOffset record");
7675 if (!SourceFileName.
empty())
7677 assert(!SeenValueSymbolTable &&
7678 "Already read VST when parsing summary block?");
7683 if (VSTOffset > 0) {
7684 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7686 SeenValueSymbolTable =
true;
7688 SeenGlobalValSummary =
true;
7689 if (
Error Err = parseEntireSummary(
Entry.ID))
7693 if (
Error Err = parseModuleStringTable())
7701 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
7704 switch (MaybeBitCode.
get()) {
7708 if (
Error Err = parseVersionRecord(Record).takeError())
7716 return error(
"Invalid source filename record");
7723 return error(
"Invalid hash length " + Twine(
Record.size()));
7724 auto &Hash = getThisModule()->second;
7726 for (
auto &Val : Record) {
7727 assert(!(Val >> 32) &&
"Unexpected high bits set");
7735 return error(
"Invalid vstoffset record");
7739 VSTOffset =
Record[0] - 1;
7744 DefinedGUIDs.reserve(DefinedGUIDs.size() +
Record.size() / 2);
7745 for (
size_t i = 0; i <
Record.size(); i += 2)
7746 DefinedGUIDs.push_back(Record[i] << 32 | Record[i + 1]);
7756 ArrayRef<uint64_t> GVRecord;
7757 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7758 if (GVRecord.
size() <= 3)
7759 return error(
"Invalid global record");
7763 ValueIdToLinkageMap[ValueId++] =
Linkage;
7767 setValueGUID(ValueId++, Name,
Linkage, SourceFileName);
7778ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7782 Ret.
push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7787ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7788 bool IsOldProfileFormat,
7789 bool HasProfile,
bool HasRelBF) {
7793 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7798 for (
unsigned I = 0,
E =
Record.size();
I !=
E; ++
I) {
7800 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
7801 if (IsOldProfileFormat) {
7805 }
else if (HasProfile)
7808 else if (HasRelBF) {
7810 bool HasTailCall =
false;
7812 Info.setHasTailCall(HasTailCall);
7842 static_cast<size_t>(
Record[Slot + 1])};
7865 while (Slot <
Record.size())
7869std::vector<FunctionSummary::ParamAccess>
7870ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7871 auto ReadRange = [&]() {
7873 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7875 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7882 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7883 while (!
Record.empty()) {
7884 PendingParamAccesses.emplace_back();
7885 FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7887 ParamAccess.
Use = ReadRange();
7892 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7893 Call.Offsets = ReadRange();
7896 return PendingParamAccesses;
7899void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7900 ArrayRef<uint64_t> Record,
size_t &Slot,
7903 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7907void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7908 ArrayRef<uint64_t> Record) {
7916 while (Slot <
Record.size())
7917 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7920SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7921 ArrayRef<uint64_t> Record,
unsigned &
I) {
7922 SmallVector<unsigned> StackIdList;
7926 if (RadixArray.empty()) {
7927 unsigned NumStackEntries =
Record[
I++];
7929 StackIdList.
reserve(NumStackEntries);
7930 for (
unsigned J = 0; J < NumStackEntries; J++) {
7931 assert(Record[
I] < StackIds.size());
7932 StackIdList.
push_back(getStackIdIndex(Record[
I++]));
7935 unsigned RadixIndex =
Record[
I++];
7941 assert(RadixIndex < RadixArray.size());
7942 unsigned NumStackIds = RadixArray[RadixIndex++];
7943 StackIdList.
reserve(NumStackIds);
7944 while (NumStackIds--) {
7945 assert(RadixIndex < RadixArray.size());
7946 unsigned Elem = RadixArray[RadixIndex];
7947 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7948 RadixIndex = RadixIndex - Elem;
7949 assert(RadixIndex < RadixArray.size());
7950 Elem = RadixArray[RadixIndex];
7952 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7955 StackIdList.
push_back(getStackIdIndex(Elem));
7965 unsigned FirstWORef = Refs.
size() - WOCnt;
7966 unsigned RefNo = FirstWORef - ROCnt;
7967 for (; RefNo < FirstWORef; ++RefNo)
7968 Refs[RefNo].setReadOnly();
7969 for (; RefNo < Refs.
size(); ++RefNo)
7970 Refs[RefNo].setWriteOnly();
7975Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7978 SmallVector<uint64_t, 64>
Record;
7985 BitstreamEntry
Entry = MaybeEntry.
get();
7988 return error(
"Invalid Summary Block: record for version expected");
7993 return error(
"Invalid Summary Block: version expected");
7996 const bool IsOldProfileFormat =
Version == 1;
7999 const bool MemProfAfterFunctionSummary =
Version >= 13;
8001 return error(
"Invalid summary version " + Twine(
Version) +
" in module '" +
8002 ModulePath +
"'. Version should be in the range [1-" +
8008 GlobalValueSummary *LastSeenSummary =
nullptr;
8018 FunctionSummary *CurrentPrevailingFS =
nullptr;
8023 std::vector<GlobalValue::GUID> PendingTypeTests;
8024 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
8025 PendingTypeCheckedLoadVCalls;
8026 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
8027 PendingTypeCheckedLoadConstVCalls;
8028 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
8030 std::vector<CallsiteInfo> PendingCallsites;
8031 std::vector<AllocInfo> PendingAllocs;
8032 std::vector<uint64_t> PendingContextIds;
8038 BitstreamEntry
Entry = MaybeEntry.
get();
8040 switch (
Entry.Kind) {
8043 return error(
"Malformed block");
8059 Expected<unsigned> MaybeBitCode = Stream.
readRecord(
Entry.ID, Record);
8062 unsigned BitCode = MaybeBitCode.
get();
8079 ValueIdToValueInfoMap[ValueID] =
8097 unsigned ValueID =
Record[0];
8099 unsigned InstCount =
Record[2];
8101 unsigned NumRefs =
Record[3];
8102 unsigned NumRORefs = 0, NumWORefs = 0;
8103 int RefListStartIndex = 4;
8107 RefListStartIndex = 5;
8110 RefListStartIndex = 6;
8113 RefListStartIndex = 7;
8124 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8126 "Record size inconsistent with number of references");
8128 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8133 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8134 IsOldProfileFormat, HasProfile, HasRelBF);
8136 auto [
VI,
GUID] = getValueInfoFromValueId(ValueID);
8143 IsPrevailing(
VI.name());
8149 assert(!MemProfAfterFunctionSummary ||
8150 (PendingCallsites.empty() && PendingAllocs.empty()));
8151 if (!IsPrevailingSym && !MemProfAfterFunctionSummary) {
8152 PendingCallsites.clear();
8153 PendingAllocs.clear();
8156 auto FS = std::make_unique<FunctionSummary>(
8158 std::move(Calls), std::move(PendingTypeTests),
8159 std::move(PendingTypeTestAssumeVCalls),
8160 std::move(PendingTypeCheckedLoadVCalls),
8161 std::move(PendingTypeTestAssumeConstVCalls),
8162 std::move(PendingTypeCheckedLoadConstVCalls),
8163 std::move(PendingParamAccesses), std::move(PendingCallsites),
8164 std::move(PendingAllocs));
8165 FS->setModulePath(getThisModule()->first());
8166 FS->setOriginalName(GUID);
8169 if (MemProfAfterFunctionSummary) {
8170 if (IsPrevailingSym)
8171 CurrentPrevailingFS =
FS.get();
8173 CurrentPrevailingFS =
nullptr;
8182 unsigned ValueID =
Record[0];
8184 unsigned AliaseeID =
Record[2];
8186 auto AS = std::make_unique<AliasSummary>(Flags);
8192 AS->setModulePath(getThisModule()->first());
8194 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
8196 if (!AliaseeInModule)
8197 return error(
"Alias expects aliasee summary to be parsed");
8198 AS->setAliasee(AliaseeVI, AliaseeInModule);
8200 auto GUID = getValueInfoFromValueId(ValueID);
8201 AS->setOriginalName(std::get<1>(GUID));
8207 unsigned ValueID =
Record[0];
8209 unsigned RefArrayStart = 2;
8210 GlobalVarSummary::GVarFlags GVF(
false,
8220 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8222 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8223 FS->setModulePath(getThisModule()->first());
8224 auto GUID = getValueInfoFromValueId(ValueID);
8225 FS->setOriginalName(std::get<1>(GUID));
8233 unsigned ValueID =
Record[0];
8236 unsigned NumRefs =
Record[3];
8237 unsigned RefListStartIndex = 4;
8238 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
8241 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8243 for (
unsigned I = VTableListStartIndex,
E =
Record.size();
I !=
E; ++
I) {
8244 ValueInfo
Callee = std::get<0>(getValueInfoFromValueId(Record[
I]));
8249 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8250 VS->setModulePath(getThisModule()->first());
8251 VS->setVTableFuncs(VTableFuncs);
8252 auto GUID = getValueInfoFromValueId(ValueID);
8253 VS->setOriginalName(std::get<1>(GUID));
8265 unsigned ValueID =
Record[0];
8268 unsigned InstCount =
Record[3];
8270 unsigned NumRefs =
Record[4];
8271 unsigned NumRORefs = 0, NumWORefs = 0;
8272 int RefListStartIndex = 5;
8276 RefListStartIndex = 6;
8277 size_t NumRefsIndex = 5;
8279 unsigned NumRORefsOffset = 1;
8280 RefListStartIndex = 7;
8283 RefListStartIndex = 8;
8285 RefListStartIndex = 9;
8287 NumRORefsOffset = 2;
8290 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
8292 NumRefs =
Record[NumRefsIndex];
8296 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
8298 "Record size inconsistent with number of references");
8300 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
8303 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
8304 IsOldProfileFormat, HasProfile,
false);
8305 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8307 auto FS = std::make_unique<FunctionSummary>(
8309 std::move(Edges), std::move(PendingTypeTests),
8310 std::move(PendingTypeTestAssumeVCalls),
8311 std::move(PendingTypeCheckedLoadVCalls),
8312 std::move(PendingTypeTestAssumeConstVCalls),
8313 std::move(PendingTypeCheckedLoadConstVCalls),
8314 std::move(PendingParamAccesses), std::move(PendingCallsites),
8315 std::move(PendingAllocs));
8316 LastSeenSummary =
FS.get();
8317 if (MemProfAfterFunctionSummary)
8318 CurrentPrevailingFS =
FS.get();
8319 LastSeenGUID =
VI.getGUID();
8320 FS->setModulePath(ModuleIdMap[ModuleId]);
8328 unsigned ValueID =
Record[0];
8331 unsigned AliaseeValueId =
Record[3];
8333 auto AS = std::make_unique<AliasSummary>(Flags);
8334 LastSeenSummary = AS.get();
8335 AS->setModulePath(ModuleIdMap[ModuleId]);
8337 auto AliaseeVI = std::get<0>(
8338 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(AliaseeValueId));
8340 auto AliaseeInModule =
8342 AS->setAliasee(AliaseeVI, AliaseeInModule);
8344 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8345 LastSeenGUID =
VI.getGUID();
8351 unsigned ValueID =
Record[0];
8354 unsigned RefArrayStart = 3;
8355 GlobalVarSummary::GVarFlags GVF(
false,
8365 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
8367 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
8368 LastSeenSummary =
FS.get();
8369 FS->setModulePath(ModuleIdMap[ModuleId]);
8370 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8371 LastSeenGUID =
VI.getGUID();
8378 if (!LastSeenSummary)
8379 return error(
"Name attachment that does not follow a combined record");
8383 LastSeenSummary =
nullptr;
8388 assert(PendingTypeTests.empty());
8393 assert(PendingTypeTestAssumeVCalls.empty());
8394 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8395 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8399 assert(PendingTypeCheckedLoadVCalls.empty());
8400 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8401 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8405 PendingTypeTestAssumeConstVCalls.push_back(
8410 PendingTypeCheckedLoadConstVCalls.push_back(
8417 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8418 StringRef
Name(Strtab.
data() + Record[
I],
8419 static_cast<size_t>(Record[
I + 1]));
8422 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, GUID);
8425 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8427 StringRef
Name(Strtab.
data() + Record[
I + 1],
8428 static_cast<size_t>(Record[
I + 2]));
8429 CfiFunctionDefs.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8438 for (
unsigned I = 0;
I !=
Record.size();
I += 2) {
8439 StringRef
Name(Strtab.
data() + Record[
I],
8440 static_cast<size_t>(Record[
I + 1]));
8443 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, GUID);
8446 for (
unsigned I = 0;
I !=
Record.size();
I += 3) {
8448 StringRef
Name(Strtab.
data() + Record[
I + 1],
8449 static_cast<size_t>(Record[
I + 2]));
8450 CfiFunctionDecls.addSymbolWithThinLTOGUID(Name, ThinLTOGUID);
8461 parseTypeIdCompatibleVtableSummaryRecord(Record);
8469 PendingParamAccesses = parseParamAccesses(Record);
8476 assert(StackIds.empty());
8478 StackIds = ArrayRef<uint64_t>(Record);
8484 StackIds.reserve(
Record.size() / 2);
8485 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8486 StackIds.push_back(*R << 32 | *(R + 1));
8488 assert(StackIdToIndex.empty());
8490 StackIdToIndex.resize(StackIds.size(), UninitializedStackIdIndex);
8495 RadixArray = ArrayRef<uint64_t>(Record);
8502 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8504 unsigned ValueID =
Record[0];
8505 SmallVector<unsigned> StackIdList;
8507 assert(R < StackIds.size());
8508 StackIdList.
push_back(getStackIdIndex(R));
8510 ValueInfo
VI = std::get<0>(getValueInfoFromValueId(ValueID));
8511 if (MemProfAfterFunctionSummary)
8513 CallsiteInfo({
VI, std::move(StackIdList)}));
8515 PendingCallsites.push_back(CallsiteInfo({
VI, std::move(StackIdList)}));
8522 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8523 auto RecordIter =
Record.begin();
8524 unsigned ValueID = *RecordIter++;
8525 unsigned NumStackIds = *RecordIter++;
8526 unsigned NumVersions = *RecordIter++;
8527 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8528 SmallVector<unsigned> StackIdList;
8529 for (
unsigned J = 0; J < NumStackIds; J++) {
8530 assert(*RecordIter < StackIds.size());
8531 StackIdList.
push_back(getStackIdIndex(*RecordIter++));
8533 SmallVector<unsigned> Versions;
8534 for (
unsigned J = 0; J < NumVersions; J++)
8536 ValueInfo
VI = std::get<0>(
8537 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8538 if (MemProfAfterFunctionSummary)
8540 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8542 PendingCallsites.push_back(
8543 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8550 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS)
8555 PendingContextIds.reserve(
Record.size() / 2);
8556 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8557 PendingContextIds.push_back(*R << 32 | *(R + 1));
8564 if (MemProfAfterFunctionSummary && !CurrentPrevailingFS) {
8565 PendingContextIds.clear();
8569 std::vector<MIBInfo> MIBs;
8570 unsigned NumMIBs = 0;
8573 unsigned MIBsRead = 0;
8574 while ((
Version >= 10 && MIBsRead++ < NumMIBs) ||
8578 auto StackIdList = parseAllocInfoContext(Record,
I);
8579 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8585 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8587 assert(!PendingContextIds.empty() &&
8588 "Missing context ids for alloc sizes");
8589 unsigned ContextIdIndex = 0;
8595 while (MIBsRead++ < NumMIBs) {
8597 unsigned NumContextSizeInfoEntries =
Record[
I++];
8599 std::vector<ContextTotalSize> ContextSizes;
8600 ContextSizes.reserve(NumContextSizeInfoEntries);
8601 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8602 assert(ContextIdIndex < PendingContextIds.size());
8604 if (PendingContextIds[ContextIdIndex] == 0) {
8613 ContextSizes.push_back(
8614 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8616 AllContextSizes.push_back(std::move(ContextSizes));
8618 PendingContextIds.clear();
8620 AllocInfo AI(std::move(MIBs));
8621 if (!AllContextSizes.empty()) {
8622 assert(AI.MIBs.size() == AllContextSizes.size());
8623 AI.ContextSizeInfos = std::move(AllContextSizes);
8626 if (MemProfAfterFunctionSummary)
8627 CurrentPrevailingFS->
addAlloc(std::move(AI));
8629 PendingAllocs.push_back(std::move(AI));
8637 assert(!MemProfAfterFunctionSummary || CurrentPrevailingFS);
8639 std::vector<MIBInfo> MIBs;
8640 unsigned NumMIBs =
Record[
I++];
8641 unsigned NumVersions =
Record[
I++];
8642 unsigned MIBsRead = 0;
8643 while (MIBsRead++ < NumMIBs) {
8646 SmallVector<unsigned> StackIdList;
8648 StackIdList = parseAllocInfoContext(Record,
I);
8649 MIBs.push_back(MIBInfo(
AllocType, std::move(StackIdList)));
8652 SmallVector<uint8_t> Versions;
8653 for (
unsigned J = 0; J < NumVersions; J++)
8656 AllocInfo AI(std::move(Versions), std::move(MIBs));
8657 if (MemProfAfterFunctionSummary)
8658 CurrentPrevailingFS->
addAlloc(std::move(AI));
8660 PendingAllocs.push_back(std::move(AI));
8670Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8674 SmallVector<uint64_t, 64>
Record;
8676 SmallString<128> ModulePath;
8683 BitstreamEntry
Entry = MaybeEntry.
get();
8685 switch (
Entry.Kind) {
8688 return error(
"Malformed block");
8700 switch (MaybeRecord.
get()) {
8708 return error(
"Invalid code_entry record");
8710 LastSeenModule = TheIndex.
addModule(ModulePath);
8711 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8719 return error(
"Invalid hash length " + Twine(
Record.size()));
8720 if (!LastSeenModule)
8721 return error(
"Invalid hash that does not follow a module path");
8723 for (
auto &Val : Record) {
8724 assert(!(Val >> 32) &&
"Unexpected high bits set");
8725 LastSeenModule->
second[Pos++] = Val;
8728 LastSeenModule =
nullptr;
8741class BitcodeErrorCategoryType :
public std::error_category {
8742 const char *
name()
const noexcept
override {
8743 return "llvm.bitcode";
8746 std::string message(
int IE)
const override {
8749 case BitcodeError::CorruptedBitcode:
8750 return "Corrupted bitcode";
8759 static BitcodeErrorCategoryType ErrorCategory;
8760 return ErrorCategory;
8764 unsigned Block,
unsigned RecordID) {
8766 return std::move(Err);
8775 switch (Entry.Kind) {
8780 return error(
"Malformed block");
8784 return std::move(Err);
8794 if (MaybeRecord.
get() == RecordID)
8805Expected<std::vector<BitcodeModule>>
8809 return FOrErr.takeError();
8810 return std::move(FOrErr->Mods);
8835 switch (Entry.Kind) {
8838 return error(
"Malformed block");
8841 uint64_t IdentificationBit = -1ull;
8845 return std::move(Err);
8851 Entry = MaybeEntry.
get();
8856 return error(
"Malformed block");
8862 return std::move(Err);
8881 if (!
I.Strtab.empty())
8888 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8889 F.StrtabForSymtab = *Strtab;
8905 if (
F.Symtab.empty())
8906 F.Symtab = *SymtabOrErr;
8911 return std::move(Err);
8916 return std::move(E);
8931BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8932 bool ShouldLazyLoadMetadata,
bool IsImporting,
8936 std::string ProducerIdentification;
8937 if (IdentificationBit != -1ull) {
8939 return std::move(JumpFailed);
8942 return std::move(
E);
8946 return std::move(JumpFailed);
8947 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8950 std::unique_ptr<Module>
M =
8951 std::make_unique<Module>(ModuleIdentifier,
Context);
8952 M->setMaterializer(R);
8955 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8956 IsImporting, Callbacks))
8957 return std::move(Err);
8959 if (MaterializeAll) {
8961 if (
Error Err =
M->materializeAll())
8962 return std::move(Err);
8965 if (
Error Err =
R->materializeForwardReferencedFunctions())
8966 return std::move(Err);
8969 return std::move(M);
8972Expected<std::unique_ptr<Module>>
8975 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8985 std::function<
bool(
StringRef)> IsPrevailing,
8986 std::function<
void(
ValueInfo)> OnValueInfo) {
8991 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8992 ModulePath, IsPrevailing, OnValueInfo);
8993 return R.parseModule();
9000 return std::move(JumpFailed);
9002 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
9003 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
9004 ModuleIdentifier, 0);
9006 if (
Error Err = R.parseModule())
9007 return std::move(Err);
9009 return std::move(Index);
9015 return std::move(Err);
9021 return std::move(
E);
9023 switch (Entry.Kind) {
9026 return error(
"Malformed block");
9029 return std::make_pair(
false,
false);
9041 switch (MaybeBitCode.
get()) {
9047 assert(Flags <= 0x7ff &&
"Unexpected bits in flag");
9049 bool EnableSplitLTOUnit = Flags & 0x8;
9050 bool UnifiedLTO = Flags & 0x200;
9051 return std::make_pair(EnableSplitLTOUnit, UnifiedLTO);
9062 return std::move(JumpFailed);
9065 return std::move(Err);
9070 return std::move(E);
9072 switch (Entry.Kind) {
9074 return error(
"Malformed block");
9085 return Flags.takeError();
9095 return std::move(Err);
9102 return StreamFailed.takeError();
9112 if (MsOrErr->size() != 1)
9113 return error(
"Expected a single module");
9115 return (*MsOrErr)[0];
9118Expected<std::unique_ptr<Module>>
9120 bool ShouldLazyLoadMetadata,
bool IsImporting,
9126 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
9131 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
9132 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
9134 IsImporting, Callbacks);
9136 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
9142 return getModuleImpl(Context,
true,
false,
false, Callbacks);
9154 return BM->parseModule(Context, Callbacks);
9187 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
9196 return BM->getSummary();
9204 return BM->getLTOInfo();
9209 bool IgnoreEmptyThinLTOIndexFile) {
9214 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
bpf unwind BPF Unwind Lower
static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF, bool &HasTailCall)
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
static cl::opt< bool > PrintSummaryGUIDs("print-summary-global-ids", cl::init(false), cl::Hidden, cl::desc("Print the global id for each value when reading the module summary"))
static AtomicOrdering getDecodedOrdering(unsigned Val)
static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags)
static std::optional< CodeModel::Model > getDecodedCodeModel(unsigned Val)
static void setSpecialRefs(SmallVectorImpl< ValueInfo > &Refs, unsigned ROCnt, unsigned WOCnt)
static bool getDecodedDSOLocal(unsigned Val)
static bool convertToString(ArrayRef< uint64_t > Record, unsigned Idx, StrTy &Result)
Convert a string from a record into an std::string, return true on failure.
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
static void stripTBAA(Module *M)
static int getDecodedUnaryOpcode(unsigned Val, Type *Ty)
static Expected< std::string > readTriple(BitstreamCursor &Stream)
static void parseWholeProgramDevirtResolutionByArg(ArrayRef< uint64_t > Record, size_t &Slot, WholeProgramDevirtResolution &Wpd)
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
static CalleeInfo getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)
static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags)
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
static Expected< uint64_t > jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
static Expected< bool > hasObjCCategoryInModule(BitstreamCursor &Stream)
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags)
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs, uint64_t AttrIdx)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val, bool &IsElementwise)
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
static bool hasImplicitComdat(size_t Val)
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream)
static bool isConstExprSupported(const BitReaderOptions &Opts, const BitcodeConstant *BC)
static Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
static void parseWholeProgramDevirtResolution(ArrayRef< uint64_t > Record, StringRef Strtab, size_t &Slot, TypeIdSummary &TypeId)
static void inferDSOLocal(GlobalValue *GV)
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V)
static Expected< BitstreamCursor > initStream(MemoryBufferRef Buffer)
static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind)
static Expected< StringRef > readBlobInRecord(BitstreamCursor &Stream, unsigned Block, unsigned RecordID)
static Expected< std::string > readIdentificationBlock(BitstreamCursor &Stream)
Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the "epoch" encoded in the bit...
static Expected< std::pair< bool, bool > > getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, unsigned ID)
static int getDecodedCastOpcode(unsigned Val)
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH
#define LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_POP
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase)
This file defines the DenseMap class.
Provides ErrorOr<T> smart pointer.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Module.h This file contains the declarations for the Module class.
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
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.
SmallVector< MachineOperand, 4 > Cond
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the SmallString class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Class for arbitrary precision integers.
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
PointerType * getType() const
Overload to return most specific pointer type.
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
bool empty() const
Check if the array is empty.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
static bool isValidFailureOrdering(AtomicOrdering Ordering)
static AtomicOrdering getStrongestFailureOrdering(AtomicOrdering SuccessOrdering)
Returns the strongest permitted ordering on failure, given the desired ordering on success.
static bool isValidSuccessOrdering(AtomicOrdering Ordering)
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMaximumNum
*p = maximumnum(old, v) maximumnum matches the behavior of llvm.maximumnum.
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
@ FMinimumNum
*p = minimumnum(old, v) minimumnum matches the behavior of llvm.minimumnum.
static bool isTypeAttrKind(AttrKind Kind)
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
@ TombstoneKey
Use as Tombstone key for DenseMap of AttrKind.
@ None
No attributes have been set.
@ EmptyKey
Use as Empty key for DenseMap of AttrKind.
@ EndAttrKinds
Sentinel value useful for loops.
LLVM Basic Block Representation.
const Instruction & back() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static LLVM_ABI const char * areInvalidOperands(Value *Base, Value *Val, Value *Offset)
Return a string if the specified operands are invalid for a bitinsert operation, otherwise return nul...
static BitInsertInst * Create(Value *Base, Value *Val, Value *Offset, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Represents a module in a bitcode file.
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(StringRef)> IsPrevailing=nullptr, std::function< void(ValueInfo)> OnValueInfo=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
void push_back(Value *V, unsigned TypeID)
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
void shrinkTo(unsigned N)
unsigned getTypeID(unsigned ValNo) const
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
Error JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
ArrayRef< uint8_t > getBitcodeBytes() const
Expected< word_t > Read(unsigned NumBits)
Expected< BitstreamEntry > advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Expected< BitstreamEntry > advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
LLVM_ABI Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
LLVM_ABI Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
Error SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block.
LLVM_ABI Expected< unsigned > skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
uint64_t getCurrentByteNo() const
LLVM_ABI Expected< std::optional< BitstreamBlockInfo > > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
unsigned getAbbrevIDWidth() const
Return the number of bits used to encode an abbrev #.
bool canSkipToPos(size_t pos) const
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
@ MIN_BYTE_BITS
Minimum number of bits that can be specified.
@ MAX_BYTE_BITS
Maximum number of bits that can be specified Note that bit width is stored in the Type classes Subcla...
static LLVM_ABI ByteType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing a ByteType.
bool isInlineAsm() const
Check if this call is an inline asm statement.
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
static CallBrInst * Create(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest, ArrayRef< BasicBlock * > IndirectDests, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo createFromIntValue(uint32_t Data)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
bool isFPPredicate() const
bool isIntPredicate() const
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI bool isElementTypeCompatible(Type *Ty)
Return true if a ConstantDataSequential can be formed with a vector or array of the specified element...
static Constant * getRaw(StringRef Data, uint64_t NumElements, Type *ElementTy)
getRaw() constructor - Return a constant with vector type with an element count and element type matc...
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_SUPPRESS_DEPRECATED_DECLARATIONS_PUSH Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static LLVM_ABI bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
static LLVM_ABI bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
LLVM_ABI bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
static DeadOnReturnInfo createFromIntValue(uint64_t Data)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Base class for error info classes.
virtual std::string message() const
Return the error message as a string.
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
Tagged union holding either a T or a Error.
Error takeError()
Take ownership of the stored error.
reference get()
Returns a reference to the stored T value.
Convenience struct for specifying and reasoning about fast-math flags.
void setFast(bool B=true)
void setAllowContract(bool B=true)
void setAllowReciprocal(bool B=true)
void setNoSignedZeros(bool B=true)
void setNoNaNs(bool B=true)
void setAllowReassoc(bool B=true)
Flag setters.
void setApproxFunc(bool B=true)
void setNoInfs(bool B=true)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
void addCallsite(CallsiteInfo &&Callsite)
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
void addAlloc(AllocInfo &&Alloc)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
BasicBlockListType::iterator iterator
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
void setUnnamedAddr(UnnamedAddr Val)
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
LLVM_ABI GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
bool hasDefaultVisibility() const
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
bool hasExternalWeakLinkage() const
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
void setVisibility(VisibilityTypes V)
LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta)
LinkageTypes
An enumeration for the kinds of linkage for global values.
@ PrivateLinkage
Like Internal, but omit from symbol table.
@ CommonLinkage
Tentative definitions.
@ InternalLinkage
Rename collisions when linking (static functions).
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
@ AppendingLinkage
Special purpose, only applies to global arrays.
@ AvailableExternallyLinkage
Available for inspection, not emission.
@ ExternalWeakLinkage
ExternalWeak linkage description.
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
LLVM_ABI void setPartition(StringRef Part)
void setAttributes(AttributeSet A)
Set attribute list for this global.
LLVM_ABI void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
LLVM_ABI void addDestination(BasicBlock *Dest)
Add a destination.
static IndirectBrInst * Create(Value *Address, unsigned NumDests, InsertPosition InsertBefore=nullptr)
unsigned getNumDestinations() const
return the number of possible destinations in this indirectbr instruction.
static LLVM_ABI InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
std::vector< ConstraintInfo > ConstraintInfoVector
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
const char * getOpcodeName() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
@ MIN_INT_BITS
Minimum number of bits that can be specified.
@ MAX_INT_BITS
Maximum number of bits that can be specified.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
static LLVM_ABI LandingPadInst * Create(Type *RetTy, unsigned NumReservedClauses, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedClauses is a hint for the number of incoming clauses that this landingpad w...
LLVM_ABI void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
LLVM_ABI StringRef getString() const
ValueT lookup(const KeyT &Key) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
size_t getBufferSize() const
StringRef getBufferIdentifier() const
const char * getBufferStart() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static MemoryEffectsBase readOnly()
MemoryEffectsBase getWithModRef(Location Loc, ModRefInfo MR) const
Get new MemoryEffectsBase with modified ModRefInfo for Loc.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
ModRefInfo getModRef(Location Loc) const
Get ModRefInfo for the given Location.
static MemoryEffectsBase errnoMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase createFromIntValue(uint32_t Data)
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
static MemoryEffectsBase unknown()
Class to hold module path string table and global value map, and encapsulate methods for operating on...
TypeIdSummary & getOrInsertTypeIdSummary(StringRef TypeId)
Return an existing or new TypeIdSummary entry for TypeId.
ModulePathStringTableTy::value_type ModuleInfo
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
static constexpr uint64_t BitcodeSummaryVersion
StringRef saveString(StringRef String)
LLVM_ABI void setFlags(uint64_t Flags)
CfiFunctionIndex & cfiFunctionDecls()
void addBlockCount(uint64_t C)
ModuleInfo * addModule(StringRef ModPath, ModuleHash Hash=ModuleHash{{0}})
Add a new module with the given Hash, mapped to the given ModID, and return a reference to the module...
void addGlobalValueSummary(const GlobalValue &GV, std::unique_ptr< GlobalValueSummary > Summary)
Add a global value summary for a value.
CfiFunctionIndex & cfiFunctionDefs()
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
unsigned addOrGetStackIdIndex(uint64_t StackId)
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
iterator_range< global_iterator > globals()
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
ArrayRef< int > getShuffleMask() const
void append(StringRef RHS)
Append from a StringRef.
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
constexpr bool empty() const
Check if the string is empty.
constexpr size_t size() const
Get the string size.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
LLVM_ABI void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
LLVM_ABI Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
static SwitchInst * Create(Value *Value, BasicBlock *Default, unsigned NumCases, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool visitTBAAMetadata(const Instruction *I, const MDNode *MD)
Visit an instruction, or a TBAA node itself as part of a metadata, and return true if it is valid,...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
static LLVM_ABI Expected< TargetExtType * > getOrError(LLVMContext &Context, StringRef Name, ArrayRef< Type * > Types={}, ArrayRef< unsigned > Ints={})
Return a target extension type having the specified name and optional type and integer parameters,...
Triple - Helper class for working with autoconf configuration names.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI Type * getStructElementType(unsigned N) const
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
bool isLabelTy() const
Return true if this is 'label'.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
Type * getArrayElementType() const
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
bool isSized() const
Return true if it makes sense to take the size of this type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isStructTy() const
True if this is an instance of StructType.
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
bool isVoidTy() const
Return true if this is 'void'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
LLVM_ABI void deleteValue()
Delete a pointer to a generic Value.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
const ParentTy * getParent() const
self_iterator getIterator()
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
@ BasicBlock
Various leaf nodes.
static const int NoAliasScopeDeclScopeArg
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
@ System
Synchronized with respect to all concurrently executing threads.
@ TYPE_CODE_OPAQUE_POINTER
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_CE_INBOUNDS_GEP
@ CST_CODE_INLINEASM_OLD3
@ CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_INLINEASM_OLD2
@ CST_CODE_CE_GEP_WITH_INRANGE
@ VST_CODE_COMBINED_ENTRY
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_INACCESSIBLEMEM_ONLY
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_DENORMAL_FPENV
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_SANITIZE_CONCURRENCY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_LIKELY_MODULE_LOCAL
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_HYBRID_PATCHABLE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_SANITIZE_ALLOC_TOKEN
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_NO_CREATE_UNDEF_OR_POISON
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ MODULE_CODE_ASM_PROPERTY
@ FUNC_CODE_INST_ATOMICRMW_OLD
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_INBOUNDS_GEP_OLD
@ FUNC_CODE_INST_STOREATOMIC_OLD
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_INST_LANDINGPAD_OLD
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_BITEXTRACT
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_RECORD_DECLARE_VALUE
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_STORE_OLD
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_BITINSERT
@ FUNC_CODE_INST_CMPXCHG_OLD
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ PARAMATTR_CODE_ENTRY_OLD
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
constexpr bool IsBigEndianHost
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
LLVM_ABI void UpgradeIntrinsicCall(CallBase *CB, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
StringMapEntry< Value * > ValueName
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
LLVM_ABI const std::error_category & BitcodeErrorCategory()
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
LLVM_ABI unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
LLVM_ABI void UpgradeInlineAsmString(std::string *AsmStr)
Upgrade comment in call to inline asm that represents an objc retain release marker.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
std::error_code make_error_code(BitcodeError E)
LLVM_ABI bool stripDebugInfo(Function &F)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
LLVM_ABI bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
LLVM_ABI void UpgradeAttributes(AttrBuilder &B)
Upgrade attributes that changed format or kind.
LLVM_ABI Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
LLVM_ABI std::unique_ptr< Module > parseModule(const uint8_t *Data, size_t Size, LLVMContext &Context)
Fuzzer friendly interface for the llvm bitcode parser.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
LLVM_ABI void UpgradeNVVMAnnotations(Module &M)
Convert legacy nvvm.annotations metadata to appropriate function attributes.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto cast_or_null(const Y &Val)
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
LLVM_ABI bool UpgradeCFIFunctionsMetadata(Module &M)
Upgrade the cfi.functions metadata node by calculating and inserting the GUID for each function entry...
LLVM_ABI void copyModuleAttrToFunctions(Module &M)
Copies module attributes to the functions in the module.
auto uninitialized_copy(R &&Src, IterTy Dst)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
bool isa_and_nonnull(const Y &Val)
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
LLVM_ABI void UpgradeOperandBundles(std::vector< OperandBundleDef > &OperandBundles)
Upgrade operand bundles (without knowing about their user instruction).
LLVM_ABI Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
const BitReaderOptions & getBitReaderOptions(const LLVMContext &C)
LLVM_ABI Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information.
auto reverse(ContainerTy &&C)
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
detail::ValueMatchesPoly< M > HasValue(M Matcher)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI std::string UpgradeDataLayoutString(StringRef DL, StringRef Triple)
Upgrade the datalayout string by adding a section for address space pointers.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
LLVM_ABI Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
@ ArgMem
Access to memory via argument pointers.
@ InaccessibleMem
Memory that is inaccessible via LLVM IR.
LLVM_ABI Instruction * UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, Instruction *&Temp)
This is an auto-upgrade for bitcast between pointers with different address spaces: the instruction i...
MaybeAlign decodeMaybeAlign(unsigned Value)
Dual operation of the encode function above.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
LLVM_ABI bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
LLVM_ABI void UpgradeFunctionAttributes(Function &F)
Correct any IR that is relying on old function attribute behavior.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
void consumeError(Error Err)
Consume a Error without doing anything.
LLVM_ABI void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found,...
LLVM_ABI Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false, ParserCallbacks Callbacks={})
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful.
LLVM_ABI std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Basic information extracted from a bitcode module to be used for LTO.
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
Class to accumulate and hold information about a callee.
static constexpr DenormalFPEnv createFromIntValue(uint32_t Data)
Flags specific to function summaries.
static constexpr uint32_t RangeWidth
std::vector< Call > Calls
In the per-module summary, it summarizes the byte offset applied to each pointer parameter before pas...
ConstantRange Use
The range contains byte offsets from the parameter pointer which accessed by the function.
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const char * BranchWeights
LLVM_ABI bool set(StringRef Name, std::string Value)
Set a property using a string name.
std::optional< ValueTypeCallbackTy > ValueType
The ValueType callback is called for every function definition or declaration and allows accessing th...
std::optional< DataLayoutCallbackFuncTy > DataLayout
std::optional< MDTypeCallbackTy > MDType
The MDType callback is called for every value in metadata.
bool SkipDebugIntrinsicUpgrade
If true, do not auto-upgrade debug intrinsic calls (llvm.dbg.
std::map< uint64_t, WholeProgramDevirtResolution > WPDRes
Mapping from byte offset to whole-program devirt resolution for that (typeid, byte offset) pair.
Kind
Specifies which kind of type check we should emit for this byte array.
unsigned SizeM1BitWidth
Range of size-1 expressed as a bit width.
enum llvm::TypeTestResolution::Kind TheKind
ValID - Represents a reference of a definition of some sort with no type.
Struct that holds a reference to a particular GUID in a global value summary.
enum llvm::WholeProgramDevirtResolution::Kind TheKind
std::map< std::vector< uint64_t >, ByArg > ResByArg
Resolutions for calls with all constant integer arguments (excluding the first argument,...
std::string SingleImplName