24#include "llvm/Config/llvm-config.h"
54#include "llvm/IR/IntrinsicsAArch64.h"
55#include "llvm/IR/IntrinsicsARM.h"
87#include <system_error>
97 "Print the global id for each value when reading the module summary"));
102 "Expand constant expressions to instructions for testing purposes"));
107 SWITCH_INST_MAGIC = 0x4B5
113 return make_error<StringError>(
120 "file too small to contain bitcode header");
121 for (
unsigned C : {
'B',
'C'})
125 "file doesn't start with bitcode header");
127 return Res.takeError();
128 for (
unsigned C : {0x0, 0xC, 0xE, 0xD})
132 "file doesn't start with bitcode header");
134 return Res.takeError();
139 const unsigned char *BufPtr = (
const unsigned char *)Buffer.
getBufferStart();
140 const unsigned char *BufEnd = BufPtr + Buffer.
getBufferSize();
143 return error(
"Invalid bitcode signature");
149 return error(
"Invalid bitcode wrapper header");
153 return std::move(Err);
155 return std::move(Stream);
159template <
typename StrTy>
172 if (
F.isMaterializable())
175 I.setMetadata(LLVMContext::MD_tbaa,
nullptr);
183 return std::move(Err);
188 std::string ProducerIdentification;
195 switch (Entry.Kind) {
198 return error(
"Malformed block");
200 return ProducerIdentification;
211 switch (MaybeBitCode.
get()) {
213 return error(
"Invalid value");
221 Twine(
"Incompatible epoch: Bitcode '") +
Twine(epoch) +
240 switch (Entry.Kind) {
243 return error(
"Malformed block");
251 return std::move(Err);
263 return std::move(Err);
274 switch (Entry.Kind) {
277 return error(
"Malformed block");
289 switch (MaybeRecord.
get()) {
295 return error(
"Invalid section name record");
300 Segment = Segment.trim();
301 Section = Section.trim();
303 if (Segment ==
"__DATA" && Section.starts_with(
"__objc_catlist"))
305 if (Segment ==
"__OBJC" && Section.starts_with(
"__category"))
307 if (Segment ==
"__TEXT" && Section.starts_with(
"__swift"))
325 switch (Entry.Kind) {
327 return error(
"Malformed block");
337 return std::move(Err);
350 return std::move(Err);
363 switch (Entry.Kind) {
366 return error(
"Malformed block");
378 switch (MaybeRecord.
get()) {
383 return error(
"Invalid triple record");
402 switch (Entry.Kind) {
404 return error(
"Malformed block");
414 return std::move(Err);
421 return Skipped.takeError();
428class BitcodeReaderBase {
431 : Stream(
std::
move(Stream)), Strtab(Strtab) {
441 bool UseStrtab =
false;
448 std::pair<StringRef, ArrayRef<uint64_t>>
451 Error readBlockInfo();
454 std::string ProducerIdentification;
461Error BitcodeReaderBase::error(
const Twine &Message) {
462 std::string FullMsg = Message.
str();
463 if (!ProducerIdentification.empty())
464 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
465 LLVM_VERSION_STRING
"')";
466 return ::error(FullMsg);
472 return error(
"Invalid version record");
473 unsigned ModuleVersion =
Record[0];
474 if (ModuleVersion > 2)
475 return error(
"Invalid value");
476 UseStrtab = ModuleVersion >= 2;
477 return ModuleVersion;
480std::pair<StringRef, ArrayRef<uint64_t>>
498class BitcodeConstant final :
public Value,
503 static constexpr uint8_t SubclassID = 255;
511 static constexpr uint8_t ConstantStructOpcode = 255;
512 static constexpr uint8_t ConstantArrayOpcode = 254;
513 static constexpr uint8_t ConstantVectorOpcode = 253;
514 static constexpr uint8_t NoCFIOpcode = 252;
515 static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
516 static constexpr uint8_t BlockAddressOpcode = 250;
517 static constexpr uint8_t ConstantPtrAuthOpcode = 249;
518 static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
525 unsigned BlockAddressBB = 0;
526 Type *SrcElemTy =
nullptr;
527 std::optional<ConstantRange> InRange;
530 std::optional<ConstantRange> InRange = std::nullopt)
531 : Opcode(Opcode),
Flags(
Flags), SrcElemTy(SrcElemTy),
535 : Opcode(Opcode),
Flags(
Flags), BlockAddressBB(BlockAddressBB) {}
540 unsigned NumOperands;
541 unsigned BlockAddressBB;
543 std::optional<ConstantRange>
InRange;
548 NumOperands(OpIDs.
size()), BlockAddressBB(
Info.BlockAddressBB),
549 SrcElemTy(
Info.SrcElemTy), InRange(
Info.InRange) {
553 BitcodeConstant &
operator=(
const BitcodeConstant &) =
delete;
557 const ExtraInfo &Info,
559 void *Mem =
A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.
size()),
560 alignof(BitcodeConstant));
561 return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
564 static bool classof(
const Value *V) {
return V->getValueID() == SubclassID; }
570 std::optional<ConstantRange> getInRange()
const {
571 assert(Opcode == Instruction::GetElementPtr);
580class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
582 Module *TheModule =
nullptr;
587 bool SeenValueSymbolTable =
false;
590 std::vector<std::string> SectionTable;
591 std::vector<std::string> GCTable;
593 std::vector<Type *> TypeList;
611 std::optional<MetadataLoader> MDLoader;
612 std::vector<Comdat *> ComdatList;
616 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
617 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
619 struct FunctionOperandInfo {
621 unsigned PersonalityFn;
625 std::vector<FunctionOperandInfo> FunctionOperands;
629 std::vector<AttributeList> MAttributes;
632 std::map<unsigned, AttributeList> MAttributeGroups;
636 std::vector<BasicBlock*> FunctionBBs;
640 std::vector<Function*> FunctionsWithBodies;
645 UpdatedIntrinsicMap UpgradedIntrinsics;
650 bool SeenFirstFunctionBody =
false;
659 std::vector<uint64_t> DeferredMetadataInfo;
665 std::deque<Function *> BasicBlockFwdRefQueue;
672 std::vector<Function *> BackwardRefFunctions;
680 bool UseRelativeIDs =
false;
684 bool WillMaterializeAllForwardRefs =
false;
688 bool SeenDebugIntrinsic =
false;
689 bool SeenDebugRecord =
false;
694 std::vector<std::string> BundleTags;
697 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
703 Error materializeForwardReferencedFunctions();
711 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
722 std::vector<StructType *> IdentifiedStructTypes;
726 static constexpr unsigned InvalidTypeID = ~0
u;
728 Type *getTypeByID(
unsigned ID);
729 Type *getPtrElementTypeByID(
unsigned ID);
730 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
737 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
745 return MDLoader->getMetadataFwdRefOrLoad(
ID);
749 if (
ID >= FunctionBBs.size())
return nullptr;
750 return FunctionBBs[
ID];
754 if (i-1 < MAttributes.size())
755 return MAttributes[i-1];
763 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
765 if (Slot ==
Record.size())
return true;
769 ValNo = InstNum - ValNo;
770 if (ValNo < InstNum) {
774 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
776 "Incorrect type ID stored for value");
777 return ResVal ==
nullptr;
779 if (Slot ==
Record.size())
783 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
785 return ResVal ==
nullptr;
789 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
791 if (Slot ==
Record.size())
796 return getValueTypePair(
Record, --Slot, InstNum, ResVal, TypeId,
799 if (Slot ==
Record.size())
810 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
812 if (getValue(
Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
821 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
823 ResVal = getValue(
Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
824 return ResVal ==
nullptr;
830 unsigned InstNum,
Type *Ty,
unsigned TyID,
832 if (Slot ==
Record.size())
return nullptr;
836 ValNo = InstNum - ValNo;
837 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
842 unsigned InstNum,
Type *Ty,
unsigned TyID,
844 if (Slot ==
Record.size())
return nullptr;
848 ValNo = InstNum - ValNo;
849 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
855 if (
Record.size() - OpNum < 2)
856 return error(
"Too few records for range");
858 unsigned LowerActiveWords =
Record[OpNum];
859 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
860 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
861 return error(
"Too few records for range");
864 OpNum += LowerActiveWords;
867 OpNum += UpperActiveWords;
870 int64_t Start = BitcodeReader::decodeSignRotatedValue(
Record[OpNum++]);
871 int64_t
End = BitcodeReader::decodeSignRotatedValue(
Record[OpNum++]);
879 if (
Record.size() - OpNum < 1)
880 return error(
"Too few records for range");
901 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
904 Error parseAttributeBlock();
905 Error parseAttributeGroupBlock();
906 Error parseTypeTable();
907 Error parseTypeTableBody();
908 Error parseOperandBundleTags();
909 Error parseSyncScopeNames();
912 unsigned NameIndex,
Triple &TT);
913 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
Function *
F,
916 Error parseGlobalValueSymbolTable();
917 Error parseConstants();
918 Error rememberAndSkipFunctionBodies();
919 Error rememberAndSkipFunctionBody();
921 Error rememberAndSkipMetadata();
924 Error globalCleanup();
925 Error resolveGlobalAndIndirectSymbolInits();
926 Error parseUseLists();
927 Error findFunctionInStream(
936class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
942 bool SeenGlobalValSummary =
false;
945 bool SeenValueSymbolTable =
false;
960 ValueIdToValueInfoMap;
969 std::string SourceFileName;
981 std::vector<uint64_t> StackIds;
985 std::vector<uint64_t> RadixArray;
988 ModuleSummaryIndexBitcodeReader(
999 Error parseValueSymbolTable(
1005 bool HasProfile,
bool HasRelBF);
1006 Error parseEntireSummary(
unsigned ID);
1007 Error parseModuleStringTable();
1011 std::vector<FunctionSummary::ParamAccess>
1016 template <
bool AllowNullValueInfo = false>
1017 std::pair<ValueInfo, GlobalValue::GUID>
1018 getValueInfoFromValueId(
unsigned ValueId);
1020 void addThisModule();
1036 return std::error_code();
1043 ValueList(this->Stream.SizeInBytes(),
1045 return materializeValue(
ValID, InsertBB);
1047 this->ProducerIdentification = std::string(ProducerIdentification);
1050Error BitcodeReader::materializeForwardReferencedFunctions() {
1051 if (WillMaterializeAllForwardRefs)
1055 WillMaterializeAllForwardRefs =
true;
1057 while (!BasicBlockFwdRefQueue.empty()) {
1058 Function *
F = BasicBlockFwdRefQueue.front();
1059 BasicBlockFwdRefQueue.pop_front();
1060 assert(
F &&
"Expected valid function");
1061 if (!BasicBlockFwdRefs.
count(
F))
1069 if (!
F->isMaterializable())
1070 return error(
"Never resolved function from blockaddress");
1073 if (
Error Err = materialize(
F))
1076 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1078 for (
Function *
F : BackwardRefFunctions)
1079 if (
Error Err = materialize(
F))
1081 BackwardRefFunctions.clear();
1084 WillMaterializeAllForwardRefs =
false;
1148 Flags.ReadNone = RawFlags & 0x1;
1149 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1150 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1151 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1152 Flags.NoInline = (RawFlags >> 4) & 0x1;
1153 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1154 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1155 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1156 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1157 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1173 RawFlags = RawFlags >> 4;
1174 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1178 bool Live = (RawFlags & 0x2) || Version < 3;
1179 bool Local = (RawFlags & 0x4);
1180 bool AutoHide = (RawFlags & 0x8);
1189 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1190 (RawFlags & 0x4) ?
true :
false,
1194static std::pair<CalleeInfo::HotnessType, bool>
1198 bool HasTailCall = (RawFlags & 0x8);
1199 return {Hotness, HasTailCall};
1203 bool &HasTailCall) {
1204 static constexpr uint64_t RelBlockFreqMask =
1206 RelBF = RawFlags & RelBlockFreqMask;
1232 case 0:
return false;
1233 case 1:
return true;
1256 case 0:
return GlobalVariable::NotThreadLocal;
1258 case 1:
return GlobalVariable::GeneralDynamicTLSModel;
1259 case 2:
return GlobalVariable::LocalDynamicTLSModel;
1260 case 3:
return GlobalVariable::InitialExecTLSModel;
1261 case 4:
return GlobalVariable::LocalExecTLSModel;
1268 case 0:
return GlobalVariable::UnnamedAddr::None;
1269 case 1:
return GlobalVariable::UnnamedAddr::Global;
1270 case 2:
return GlobalVariable::UnnamedAddr::Local;
1304 return IsFP ? Instruction::FNeg : -1;
1318 return IsFP ? Instruction::FAdd : Instruction::Add;
1320 return IsFP ? Instruction::FSub : Instruction::Sub;
1322 return IsFP ? Instruction::FMul : Instruction::Mul;
1324 return IsFP ? -1 : Instruction::UDiv;
1326 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1328 return IsFP ? -1 : Instruction::URem;
1330 return IsFP ? Instruction::FRem : Instruction::SRem;
1332 return IsFP ? -1 : Instruction::Shl;
1334 return IsFP ? -1 : Instruction::LShr;
1336 return IsFP ? -1 : Instruction::AShr;
1338 return IsFP ? -1 : Instruction::And;
1340 return IsFP ? -1 : Instruction::Or;
1342 return IsFP ? -1 : Instruction::Xor;
1439Type *BitcodeReader::getTypeByID(
unsigned ID) {
1441 if (
ID >= TypeList.size())
1444 if (
Type *Ty = TypeList[
ID])
1449 return TypeList[
ID] = createIdentifiedStructType(Context);
1452unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1453 auto It = ContainedTypeIDs.
find(
ID);
1454 if (It == ContainedTypeIDs.
end())
1455 return InvalidTypeID;
1457 if (
Idx >= It->second.size())
1458 return InvalidTypeID;
1460 return It->second[
Idx];
1463Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1464 if (
ID >= TypeList.size())
1471 return getTypeByID(getContainedTypeID(
ID, 0));
1474unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1476 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1477 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1478 auto It = VirtualTypeIDs.
find(CacheKey);
1479 if (It != VirtualTypeIDs.
end()) {
1485 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1486 "Incorrect cached contained type IDs");
1490 unsigned TypeID = TypeList.size();
1491 TypeList.push_back(Ty);
1492 if (!ChildTypeIDs.
empty())
1513 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1527 if (Opcode == Instruction::GetElementPtr)
1531 case Instruction::FNeg:
1532 case Instruction::Select:
1533 case Instruction::ICmp:
1534 case Instruction::FCmp:
1544 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1545 !isa<BitcodeConstant>(ValueList[StartValID]))
1546 return ValueList[StartValID];
1551 while (!Worklist.
empty()) {
1560 return error(
"Invalid value ID");
1563 auto *BC = dyn_cast<BitcodeConstant>(V);
1573 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1574 auto It = MaterializedValues.
find(OpID);
1575 if (It != MaterializedValues.
end())
1583 if (Ops.
size() != BC->getOperandIDs().size())
1585 std::reverse(Ops.
begin(), Ops.
end());
1589 if (
auto *
C = dyn_cast<Constant>(
Op))
1602 switch (BC->Opcode) {
1603 case BitcodeConstant::ConstantPtrAuthOpcode: {
1604 auto *
Key = dyn_cast<ConstantInt>(ConstOps[1]);
1606 return error(
"ptrauth key operand must be ConstantInt");
1608 auto *Disc = dyn_cast<ConstantInt>(ConstOps[2]);
1610 return error(
"ptrauth disc operand must be ConstantInt");
1615 case BitcodeConstant::NoCFIOpcode: {
1616 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1618 return error(
"no_cfi operand must be GlobalValue");
1622 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1623 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1625 return error(
"dso_local operand must be GlobalValue");
1629 case BitcodeConstant::BlockAddressOpcode: {
1630 Function *Fn = dyn_cast<Function>(ConstOps[0]);
1632 return error(
"blockaddress operand must be a function");
1637 unsigned BBID = BC->BlockAddressBB;
1640 return error(
"Invalid ID");
1643 for (
size_t I = 0, E = BBID;
I != E; ++
I) {
1645 return error(
"Invalid ID");
1652 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1654 BasicBlockFwdRefQueue.push_back(Fn);
1655 if (FwdBBs.size() < BBID + 1)
1656 FwdBBs.resize(BBID + 1);
1664 case BitcodeConstant::ConstantStructOpcode: {
1665 auto *
ST = cast<StructType>(BC->getType());
1666 if (
ST->getNumElements() != ConstOps.
size())
1667 return error(
"Invalid number of elements in struct initializer");
1669 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1670 if (
Op->getType() != Ty)
1671 return error(
"Incorrect type in struct initializer");
1676 case BitcodeConstant::ConstantArrayOpcode: {
1677 auto *AT = cast<ArrayType>(BC->getType());
1678 if (AT->getNumElements() != ConstOps.
size())
1679 return error(
"Invalid number of elements in array initializer");
1682 if (
Op->getType() != AT->getElementType())
1683 return error(
"Incorrect type in array initializer");
1688 case BitcodeConstant::ConstantVectorOpcode: {
1689 auto *VT = cast<FixedVectorType>(BC->getType());
1690 if (VT->getNumElements() != ConstOps.size())
1691 return error(
"Invalid number of elements in vector initializer");
1694 if (
Op->getType() != VT->getElementType())
1695 return error(
"Incorrect type in vector initializer");
1700 case Instruction::GetElementPtr:
1702 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1705 case Instruction::ExtractElement:
1708 case Instruction::InsertElement:
1712 case Instruction::ShuffleVector: {
1731 return error(
Twine(
"Value referenced by initializer is an unsupported "
1732 "constant expression of type ") +
1733 BC->getOpcodeName());
1739 BC->getType(),
"constexpr", InsertBB);
1742 "constexpr", InsertBB);
1745 Ops[1],
"constexpr", InsertBB);
1746 if (isa<OverflowingBinaryOperator>(
I)) {
1748 I->setHasNoSignedWrap();
1750 I->setHasNoUnsignedWrap();
1752 if (isa<PossiblyExactOperator>(
I) &&
1756 switch (BC->Opcode) {
1757 case BitcodeConstant::ConstantVectorOpcode: {
1761 Value *
Idx = ConstantInt::get(IdxTy, Pair.index());
1765 I = cast<Instruction>(V);
1768 case BitcodeConstant::ConstantStructOpcode:
1769 case BitcodeConstant::ConstantArrayOpcode: {
1773 "constexpr.ins", InsertBB);
1774 I = cast<Instruction>(V);
1777 case Instruction::ICmp:
1778 case Instruction::FCmp:
1781 "constexpr", InsertBB);
1783 case Instruction::GetElementPtr:
1785 ArrayRef(Ops).drop_front(),
"constexpr",
1789 case Instruction::Select:
1792 case Instruction::ExtractElement:
1795 case Instruction::InsertElement:
1799 case Instruction::ShuffleVector:
1812 return MaterializedValues[StartValID];
1821 return cast<Constant>(MaybeV.
get());
1827 IdentifiedStructTypes.push_back(Ret);
1833 IdentifiedStructTypes.push_back(Ret);
1849 case Attribute::ZExt:
return 1 << 0;
1850 case Attribute::SExt:
return 1 << 1;
1851 case Attribute::NoReturn:
return 1 << 2;
1852 case Attribute::InReg:
return 1 << 3;
1853 case Attribute::StructRet:
return 1 << 4;
1854 case Attribute::NoUnwind:
return 1 << 5;
1855 case Attribute::NoAlias:
return 1 << 6;
1856 case Attribute::ByVal:
return 1 << 7;
1857 case Attribute::Nest:
return 1 << 8;
1858 case Attribute::ReadNone:
return 1 << 9;
1859 case Attribute::ReadOnly:
return 1 << 10;
1860 case Attribute::NoInline:
return 1 << 11;
1861 case Attribute::AlwaysInline:
return 1 << 12;
1862 case Attribute::OptimizeForSize:
return 1 << 13;
1863 case Attribute::StackProtect:
return 1 << 14;
1864 case Attribute::StackProtectReq:
return 1 << 15;
1865 case Attribute::Alignment:
return 31 << 16;
1867 case Attribute::NoRedZone:
return 1 << 22;
1868 case Attribute::NoImplicitFloat:
return 1 << 23;
1869 case Attribute::Naked:
return 1 << 24;
1870 case Attribute::InlineHint:
return 1 << 25;
1871 case Attribute::StackAlignment:
return 7 << 26;
1872 case Attribute::ReturnsTwice:
return 1 << 29;
1873 case Attribute::UWTable:
return 1 << 30;
1874 case Attribute::NonLazyBind:
return 1U << 31;
1875 case Attribute::SanitizeAddress:
return 1ULL << 32;
1876 case Attribute::MinSize:
return 1ULL << 33;
1877 case Attribute::NoDuplicate:
return 1ULL << 34;
1878 case Attribute::StackProtectStrong:
return 1ULL << 35;
1879 case Attribute::SanitizeThread:
return 1ULL << 36;
1880 case Attribute::SanitizeMemory:
return 1ULL << 37;
1881 case Attribute::NoBuiltin:
return 1ULL << 38;
1882 case Attribute::Returned:
return 1ULL << 39;
1883 case Attribute::Cold:
return 1ULL << 40;
1884 case Attribute::Builtin:
return 1ULL << 41;
1885 case Attribute::OptimizeNone:
return 1ULL << 42;
1886 case Attribute::InAlloca:
return 1ULL << 43;
1887 case Attribute::NonNull:
return 1ULL << 44;
1888 case Attribute::JumpTable:
return 1ULL << 45;
1889 case Attribute::Convergent:
return 1ULL << 46;
1890 case Attribute::SafeStack:
return 1ULL << 47;
1891 case Attribute::NoRecurse:
return 1ULL << 48;
1894 case Attribute::SwiftSelf:
return 1ULL << 51;
1895 case Attribute::SwiftError:
return 1ULL << 52;
1896 case Attribute::WriteOnly:
return 1ULL << 53;
1897 case Attribute::Speculatable:
return 1ULL << 54;
1898 case Attribute::StrictFP:
return 1ULL << 55;
1899 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1900 case Attribute::NoCfCheck:
return 1ULL << 57;
1901 case Attribute::OptForFuzzing:
return 1ULL << 58;
1902 case Attribute::ShadowCallStack:
return 1ULL << 59;
1903 case Attribute::SpeculativeLoadHardening:
1905 case Attribute::ImmArg:
1907 case Attribute::WillReturn:
1909 case Attribute::NoFree:
1925 if (
I == Attribute::Alignment)
1926 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
1927 else if (
I == Attribute::StackAlignment)
1928 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
1930 B.addTypeAttr(
I,
nullptr);
1944 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1946 "Alignment must be a power of two.");
1949 B.addAlignmentAttr(Alignment);
1951 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1952 (EncodedAttrs & 0xffff);
1957 if (Attrs & (1ULL << 9)) {
1959 Attrs &= ~(1ULL << 9);
1962 if (Attrs & (1ULL << 10)) {
1964 Attrs &= ~(1ULL << 10);
1967 if (Attrs & (1ULL << 49)) {
1969 Attrs &= ~(1ULL << 49);
1972 if (Attrs & (1ULL << 50)) {
1974 Attrs &= ~(1ULL << 50);
1977 if (Attrs & (1ULL << 53)) {
1979 Attrs &= ~(1ULL << 53);
1983 B.addMemoryAttr(ME);
1987 if (Attrs & (1ULL << 21)) {
1988 Attrs &= ~(1ULL << 21);
1995Error BitcodeReader::parseAttributeBlock() {
1999 if (!MAttributes.empty())
2000 return error(
"Invalid multiple blocks");
2013 switch (
Entry.Kind) {
2016 return error(
"Malformed block");
2029 switch (MaybeRecord.
get()) {
2035 return error(
"Invalid parameter attribute record");
2037 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2048 Attrs.push_back(MAttributeGroups[Val]);
2063 return Attribute::Alignment;
2065 return Attribute::AlwaysInline;
2067 return Attribute::Builtin;
2069 return Attribute::ByVal;
2071 return Attribute::InAlloca;
2073 return Attribute::Cold;
2075 return Attribute::Convergent;
2077 return Attribute::DisableSanitizerInstrumentation;
2079 return Attribute::ElementType;
2081 return Attribute::FnRetThunkExtern;
2083 return Attribute::InlineHint;
2085 return Attribute::InReg;
2087 return Attribute::JumpTable;
2089 return Attribute::Memory;
2091 return Attribute::NoFPClass;
2093 return Attribute::MinSize;
2095 return Attribute::Naked;
2097 return Attribute::Nest;
2099 return Attribute::NoAlias;
2101 return Attribute::NoBuiltin;
2103 return Attribute::NoCallback;
2105 return Attribute::NoDivergenceSource;
2107 return Attribute::NoDuplicate;
2109 return Attribute::NoFree;
2111 return Attribute::NoImplicitFloat;
2113 return Attribute::NoInline;
2115 return Attribute::NoRecurse;
2117 return Attribute::NoMerge;
2119 return Attribute::NonLazyBind;
2121 return Attribute::NonNull;
2123 return Attribute::Dereferenceable;
2125 return Attribute::DereferenceableOrNull;
2127 return Attribute::AllocAlign;
2129 return Attribute::AllocKind;
2131 return Attribute::AllocSize;
2133 return Attribute::AllocatedPointer;
2135 return Attribute::NoRedZone;
2137 return Attribute::NoReturn;
2139 return Attribute::NoSync;
2141 return Attribute::NoCfCheck;
2143 return Attribute::NoProfile;
2145 return Attribute::SkipProfile;
2147 return Attribute::NoUnwind;
2149 return Attribute::NoSanitizeBounds;
2151 return Attribute::NoSanitizeCoverage;
2153 return Attribute::NullPointerIsValid;
2155 return Attribute::OptimizeForDebugging;
2157 return Attribute::OptForFuzzing;
2159 return Attribute::OptimizeForSize;
2161 return Attribute::OptimizeNone;
2163 return Attribute::ReadNone;
2165 return Attribute::ReadOnly;
2167 return Attribute::Returned;
2169 return Attribute::ReturnsTwice;
2171 return Attribute::SExt;
2173 return Attribute::Speculatable;
2175 return Attribute::StackAlignment;
2177 return Attribute::StackProtect;
2179 return Attribute::StackProtectReq;
2181 return Attribute::StackProtectStrong;
2183 return Attribute::SafeStack;
2185 return Attribute::ShadowCallStack;
2187 return Attribute::StrictFP;
2189 return Attribute::StructRet;
2191 return Attribute::SanitizeAddress;
2193 return Attribute::SanitizeHWAddress;
2195 return Attribute::SanitizeThread;
2197 return Attribute::SanitizeType;
2199 return Attribute::SanitizeMemory;
2201 return Attribute::SanitizeNumericalStability;
2203 return Attribute::SanitizeRealtime;
2205 return Attribute::SanitizeRealtimeBlocking;
2207 return Attribute::SpeculativeLoadHardening;
2209 return Attribute::SwiftError;
2211 return Attribute::SwiftSelf;
2213 return Attribute::SwiftAsync;
2215 return Attribute::UWTable;
2217 return Attribute::VScaleRange;
2219 return Attribute::WillReturn;
2221 return Attribute::WriteOnly;
2223 return Attribute::ZExt;
2225 return Attribute::ImmArg;
2227 return Attribute::SanitizeMemTag;
2229 return Attribute::Preallocated;
2231 return Attribute::NoUndef;
2233 return Attribute::ByRef;
2235 return Attribute::MustProgress;
2237 return Attribute::Hot;
2239 return Attribute::PresplitCoroutine;
2241 return Attribute::Writable;
2243 return Attribute::CoroDestroyOnlyWhenComplete;
2245 return Attribute::DeadOnUnwind;
2247 return Attribute::Range;
2249 return Attribute::Initializes;
2251 return Attribute::CoroElideSafe;
2253 return Attribute::NoExt;
2255 return Attribute::Captures;
2257 return Attribute::DeadOnReturn;
2266 return error(
"Invalid alignment value");
2274 return error(
"Unknown attribute kind (" +
Twine(Code) +
")");
2279 switch (EncodedKind) {
2303Error BitcodeReader::parseAttributeGroupBlock() {
2307 if (!MAttributeGroups.empty())
2308 return error(
"Invalid multiple blocks");
2319 switch (
Entry.Kind) {
2322 return error(
"Malformed block");
2335 switch (MaybeRecord.
get()) {
2340 return error(
"Invalid grp record");
2347 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2360 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2366 if (Kind == Attribute::ByVal)
2367 B.addByValAttr(
nullptr);
2368 else if (Kind == Attribute::StructRet)
2369 B.addStructRetAttr(
nullptr);
2370 else if (Kind == Attribute::InAlloca)
2371 B.addInAllocaAttr(
nullptr);
2372 else if (Kind == Attribute::UWTable)
2373 B.addUWTableAttr(UWTableKind::Default);
2375 B.addAttribute(Kind);
2377 return error(
"Not an enum attribute");
2378 }
else if (
Record[i] == 1) {
2380 if (
Error Err = parseAttrKind(
Record[++i], &Kind))
2383 return error(
"Not an int attribute");
2384 if (Kind == Attribute::Alignment)
2385 B.addAlignmentAttr(
Record[++i]);
2386 else if (Kind == Attribute::StackAlignment)
2387 B.addStackAlignmentAttr(
Record[++i]);
2388 else if (Kind == Attribute::Dereferenceable)
2389 B.addDereferenceableAttr(
Record[++i]);
2390 else if (Kind == Attribute::DereferenceableOrNull)
2391 B.addDereferenceableOrNullAttr(
Record[++i]);
2392 else if (Kind == Attribute::AllocSize)
2393 B.addAllocSizeAttrFromRawRepr(
Record[++i]);
2394 else if (Kind == Attribute::VScaleRange)
2395 B.addVScaleRangeAttrFromRawRepr(
Record[++i]);
2396 else if (Kind == Attribute::UWTable)
2398 else if (Kind == Attribute::AllocKind)
2400 else if (Kind == Attribute::Memory) {
2414 B.addMemoryAttr(ME);
2419 EncodedME & 0x00FFFFFFFFFFFFFFULL));
2421 }
else if (Kind == Attribute::Captures)
2423 else if (Kind == Attribute::NoFPClass)
2431 while (
Record[i] != 0 && i != e)
2433 assert(
Record[i] == 0 &&
"Kind string not null terminated");
2438 while (
Record[i] != 0 && i != e)
2440 assert(
Record[i] == 0 &&
"Value string not null terminated");
2443 B.addAttribute(KindStr.
str(), ValStr.
str());
2445 bool HasType =
Record[i] == 6;
2447 if (
Error Err = parseAttrKind(
Record[++i], &Kind))
2450 return error(
"Not a type attribute");
2452 B.addTypeAttr(Kind, HasType ? getTypeByID(
Record[++i]) :
nullptr);
2453 }
else if (
Record[i] == 7) {
2457 if (
Error Err = parseAttrKind(
Record[i++], &Kind))
2460 return error(
"Not a ConstantRange attribute");
2463 readBitWidthAndConstantRange(
Record, i);
2468 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2469 }
else if (
Record[i] == 8) {
2473 if (
Error Err = parseAttrKind(
Record[i++], &Kind))
2476 return error(
"Not a constant range list attribute");
2480 return error(
"Too few records for constant range list");
2481 unsigned RangeSize =
Record[i++];
2483 for (
unsigned Idx = 0;
Idx < RangeSize; ++
Idx) {
2493 return error(
"Invalid (unordered or overlapping) range list");
2494 B.addConstantRangeListAttr(Kind, Val);
2496 return error(
"Invalid attribute group entry");
2501 B.addMemoryAttr(ME);
2511Error BitcodeReader::parseTypeTable() {
2515 return parseTypeTableBody();
2518Error BitcodeReader::parseTypeTableBody() {
2519 if (!TypeList.empty())
2520 return error(
"Invalid multiple blocks");
2523 unsigned NumRecords = 0;
2534 switch (
Entry.Kind) {
2537 return error(
"Malformed block");
2539 if (NumRecords != TypeList.size())
2540 return error(
"Malformed block");
2549 Type *ResultTy =
nullptr;
2554 switch (MaybeRecord.
get()) {
2556 return error(
"Invalid value");
2561 return error(
"Invalid numentry record");
2562 TypeList.resize(
Record[0]);
2607 return error(
"Invalid integer record");
2612 return error(
"Bitwidth for integer type out of range");
2619 return error(
"Invalid pointer record");
2623 ResultTy = getTypeByID(
Record[0]);
2625 !PointerType::isValidElementType(ResultTy))
2626 return error(
"Invalid type");
2633 return error(
"Invalid opaque pointer record");
2642 return error(
"Invalid function record");
2644 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2651 ResultTy = getTypeByID(
Record[2]);
2652 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2653 return error(
"Invalid type");
2656 ResultTy = FunctionType::get(ResultTy, ArgTys,
Record[0]);
2662 return error(
"Invalid function record");
2664 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2666 if (!FunctionType::isValidArgumentType(
T))
2667 return error(
"Invalid function argument type");
2674 ResultTy = getTypeByID(
Record[1]);
2675 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2676 return error(
"Invalid type");
2679 ResultTy = FunctionType::get(ResultTy, ArgTys,
Record[0]);
2684 return error(
"Invalid anon struct record");
2686 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2693 return error(
"Invalid type");
2700 return error(
"Invalid struct name record");
2705 return error(
"Invalid named struct record");
2707 if (NumRecords >= TypeList.size())
2708 return error(
"Invalid TYPE table");
2711 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2714 TypeList[NumRecords] =
nullptr;
2716 Res = createIdentifiedStructType(Context, TypeName);
2720 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2727 return error(
"Invalid named struct record");
2736 return error(
"Invalid opaque type record");
2738 if (NumRecords >= TypeList.size())
2739 return error(
"Invalid TYPE table");
2742 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2745 TypeList[NumRecords] =
nullptr;
2747 Res = createIdentifiedStructType(Context, TypeName);
2754 return error(
"Invalid target extension type record");
2756 if (NumRecords >= TypeList.size())
2757 return error(
"Invalid TYPE table");
2760 return error(
"Too many type parameters");
2762 unsigned NumTys =
Record[0];
2765 for (
unsigned i = 0; i < NumTys; i++) {
2769 return error(
"Invalid type");
2772 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2773 if (
Record[i] > UINT_MAX)
2774 return error(
"Integer parameter too large");
2779 if (
auto E = TTy.takeError())
2787 return error(
"Invalid array type record");
2788 ResultTy = getTypeByID(
Record[1]);
2789 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2790 return error(
"Invalid type");
2792 ResultTy = ArrayType::get(ResultTy,
Record[0]);
2797 return error(
"Invalid vector type record");
2799 return error(
"Invalid vector length");
2800 ResultTy = getTypeByID(
Record[1]);
2801 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2802 return error(
"Invalid type");
2805 ResultTy = VectorType::get(ResultTy,
Record[0], Scalable);
2809 if (NumRecords >= TypeList.size())
2810 return error(
"Invalid TYPE table");
2811 if (TypeList[NumRecords])
2813 "Invalid TYPE table: Only named structs can be forward referenced");
2814 assert(ResultTy &&
"Didn't read a type?");
2815 TypeList[NumRecords] = ResultTy;
2816 if (!ContainedIDs.
empty())
2817 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2822Error BitcodeReader::parseOperandBundleTags() {
2826 if (!BundleTags.empty())
2827 return error(
"Invalid multiple blocks");
2837 switch (
Entry.Kind) {
2840 return error(
"Malformed block");
2854 return error(
"Invalid operand bundle record");
2857 BundleTags.emplace_back();
2859 return error(
"Invalid operand bundle record");
2864Error BitcodeReader::parseSyncScopeNames() {
2869 return error(
"Invalid multiple synchronization scope names blocks");
2878 switch (
Entry.Kind) {
2881 return error(
"Malformed block");
2884 return error(
"Invalid empty synchronization scope names block");
2898 return error(
"Invalid sync scope record");
2902 return error(
"Invalid sync scope record");
2911 unsigned NameIndex,
Triple &TT) {
2914 return error(
"Invalid record");
2915 unsigned ValueID =
Record[0];
2916 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
2917 return error(
"Invalid record");
2918 Value *
V = ValueList[ValueID];
2921 if (NameStr.contains(0))
2922 return error(
"Invalid value name");
2923 V->setName(NameStr);
2924 auto *GO = dyn_cast<GlobalObject>(V);
2925 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
2938 return std::move(JumpFailed);
2944 return error(
"Expected value symbol table subblock");
2948void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
2955 uint64_t FuncBitOffset = FuncWordOffset * 32;
2956 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2960 if (FuncBitOffset > LastFunctionBlockBit)
2961 LastFunctionBlockBit = FuncBitOffset;
2965Error BitcodeReader::parseGlobalValueSymbolTable() {
2966 unsigned FuncBitcodeOffsetDelta =
2979 switch (
Entry.Kind) {
2982 return error(
"Malformed block");
2993 switch (MaybeRecord.
get()) {
2995 unsigned ValueID =
Record[0];
2996 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
2997 return error(
"Invalid value reference in symbol table");
2998 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2999 cast<Function>(ValueList[ValueID]),
Record);
3015 if (!MaybeCurrentBit)
3017 CurrentBit = MaybeCurrentBit.
get();
3020 if (
Error Err = parseGlobalValueSymbolTable())
3022 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
3041 unsigned FuncBitcodeOffsetDelta =
3060 switch (
Entry.Kind) {
3063 return error(
"Malformed block");
3066 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
3079 switch (MaybeRecord.
get()) {
3098 if (
auto *
F = dyn_cast<Function>(V))
3099 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F,
Record);
3104 return error(
"Invalid bbentry record");
3107 return error(
"Invalid bbentry record");
3129Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3130 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3131 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3132 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3134 GlobalInitWorklist.swap(GlobalInits);
3135 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3136 FunctionOperandWorklist.swap(FunctionOperands);
3138 while (!GlobalInitWorklist.empty()) {
3139 unsigned ValID = GlobalInitWorklist.back().second;
3142 GlobalInits.push_back(GlobalInitWorklist.back());
3147 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3149 GlobalInitWorklist.pop_back();
3152 while (!IndirectSymbolInitWorklist.empty()) {
3153 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3155 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3161 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3162 if (
auto *GA = dyn_cast<GlobalAlias>(GV)) {
3164 return error(
"Alias and aliasee types don't match");
3166 }
else if (
auto *GI = dyn_cast<GlobalIFunc>(GV)) {
3169 return error(
"Expected an alias or an ifunc");
3172 IndirectSymbolInitWorklist.pop_back();
3175 while (!FunctionOperandWorklist.empty()) {
3176 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3177 if (
Info.PersonalityFn) {
3178 unsigned ValID =
Info.PersonalityFn - 1;
3183 Info.F->setPersonalityFn(MaybeC.
get());
3184 Info.PersonalityFn = 0;
3193 Info.F->setPrefixData(MaybeC.
get());
3197 if (
Info.Prologue) {
3203 Info.F->setPrologueData(MaybeC.
get());
3207 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3208 FunctionOperands.push_back(Info);
3209 FunctionOperandWorklist.pop_back();
3218 BitcodeReader::decodeSignRotatedValue);
3220 return APInt(TypeBits, Words);
3223Error BitcodeReader::parseConstants() {
3231 unsigned Int32TyID = getVirtualTypeID(CurTy);
3232 unsigned CurTyID = Int32TyID;
3233 Type *CurElemTy =
nullptr;
3234 unsigned NextCstNo = ValueList.
size();
3242 switch (Entry.Kind) {
3245 return error(
"Malformed block");
3247 if (NextCstNo != ValueList.
size())
3248 return error(
"Invalid constant reference");
3262 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3272 return error(
"Invalid settype record");
3273 if (
Record[0] >= TypeList.size() || !TypeList[
Record[0]])
3274 return error(
"Invalid settype record");
3275 if (TypeList[
Record[0]] == VoidType)
3276 return error(
"Invalid constant type");
3278 CurTy = TypeList[CurTyID];
3279 CurElemTy = getPtrElementTypeByID(CurTyID);
3283 return error(
"Invalid type for a constant null value");
3284 if (
auto *TETy = dyn_cast<TargetExtType>(CurTy))
3286 return error(
"Invalid type for a constant null value");
3291 return error(
"Invalid integer const record");
3296 return error(
"Invalid wide integer const record");
3300 V = ConstantInt::get(CurTy, VInt);
3305 return error(
"Invalid float const record");
3308 if (ScalarTy->isHalfTy())
3309 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3311 else if (ScalarTy->isBFloatTy())
3312 V = ConstantFP::get(
3314 else if (ScalarTy->isFloatTy())
3315 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3317 else if (ScalarTy->isDoubleTy())
3318 V = ConstantFP::get(
3320 else if (ScalarTy->isX86_FP80Ty()) {
3323 Rearrange[0] = (
Record[1] & 0xffffLL) | (
Record[0] << 16);
3324 Rearrange[1] =
Record[0] >> 48;
3325 V = ConstantFP::get(
3326 CurTy,
APFloat(APFloat::x87DoubleExtended(),
APInt(80, Rearrange)));
3327 }
else if (ScalarTy->isFP128Ty())
3328 V = ConstantFP::get(CurTy,
3330 else if (ScalarTy->isPPC_FP128Ty())
3331 V = ConstantFP::get(
3340 return error(
"Invalid aggregate record");
3345 if (isa<StructType>(CurTy)) {
3346 V = BitcodeConstant::create(
3347 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3348 }
else if (isa<ArrayType>(CurTy)) {
3349 V = BitcodeConstant::create(Alloc, CurTy,
3350 BitcodeConstant::ConstantArrayOpcode, Elts);
3351 }
else if (isa<VectorType>(CurTy)) {
3352 V = BitcodeConstant::create(
3353 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3362 return error(
"Invalid string record");
3371 return error(
"Invalid data record");
3374 if (
auto *Array = dyn_cast<ArrayType>(CurTy))
3375 EltTy =
Array->getElementType();
3377 EltTy = cast<VectorType>(CurTy)->getElementType();
3380 if (isa<VectorType>(CurTy))
3386 if (isa<VectorType>(CurTy))
3392 if (isa<VectorType>(CurTy))
3398 if (isa<VectorType>(CurTy))
3404 if (isa<VectorType>(CurTy))
3410 if (isa<VectorType>(CurTy))
3416 if (isa<VectorType>(CurTy))
3422 if (isa<VectorType>(CurTy))
3427 return error(
"Invalid type for value");
3433 return error(
"Invalid unary op constexpr record");
3438 V = BitcodeConstant::create(Alloc, CurTy,
Opc, (
unsigned)
Record[1]);
3444 return error(
"Invalid binary op constexpr record");
3450 if (
Record.size() >= 4) {
3451 if (
Opc == Instruction::Add ||
3452 Opc == Instruction::Sub ||
3453 Opc == Instruction::Mul ||
3454 Opc == Instruction::Shl) {
3459 }
else if (
Opc == Instruction::SDiv ||
3460 Opc == Instruction::UDiv ||
3461 Opc == Instruction::LShr ||
3462 Opc == Instruction::AShr) {
3467 V = BitcodeConstant::create(Alloc, CurTy, {(
uint8_t)
Opc, Flags},
3474 return error(
"Invalid cast constexpr record");
3479 unsigned OpTyID =
Record[1];
3480 Type *OpTy = getTypeByID(OpTyID);
3482 return error(
"Invalid cast constexpr record");
3483 V = BitcodeConstant::create(Alloc, CurTy,
Opc, (
unsigned)
Record[2]);
3495 return error(
"Constant GEP record must have at least two elements");
3497 Type *PointeeType =
nullptr;
3501 PointeeType = getTypeByID(
Record[OpNum++]);
3504 std::optional<ConstantRange>
InRange;
3508 unsigned InRangeIndex =
Op >> 1;
3515 readBitWidthAndConstantRange(
Record, OpNum);
3525 unsigned BaseTypeID =
Record[OpNum];
3526 while (OpNum !=
Record.size()) {
3527 unsigned ElTyID =
Record[OpNum++];
3528 Type *ElTy = getTypeByID(ElTyID);
3530 return error(
"Invalid getelementptr constexpr record");
3534 if (Elts.
size() < 1)
3535 return error(
"Invalid gep with no operands");
3539 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3540 BaseType = getTypeByID(BaseTypeID);
3545 return error(
"GEP base operand must be pointer or vector of pointer");
3548 PointeeType = getPtrElementTypeByID(BaseTypeID);
3550 return error(
"Missing element type for old-style constant GEP");
3553 V = BitcodeConstant::create(
3555 {Instruction::GetElementPtr,
uint8_t(Flags), PointeeType,
InRange},
3561 return error(
"Invalid select constexpr record");
3563 V = BitcodeConstant::create(
3564 Alloc, CurTy, Instruction::Select,
3571 return error(
"Invalid extractelement constexpr record");
3572 unsigned OpTyID =
Record[0];
3574 dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
3576 return error(
"Invalid extractelement constexpr record");
3578 if (
Record.size() == 4) {
3579 unsigned IdxTyID =
Record[2];
3580 Type *IdxTy = getTypeByID(IdxTyID);
3582 return error(
"Invalid extractelement constexpr record");
3588 V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
3594 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3595 if (
Record.size() < 3 || !OpTy)
3596 return error(
"Invalid insertelement constexpr record");
3598 if (
Record.size() == 4) {
3599 unsigned IdxTyID =
Record[2];
3600 Type *IdxTy = getTypeByID(IdxTyID);
3602 return error(
"Invalid insertelement constexpr record");
3608 V = BitcodeConstant::create(
3609 Alloc, CurTy, Instruction::InsertElement,
3614 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3615 if (
Record.size() < 3 || !OpTy)
3616 return error(
"Invalid shufflevector constexpr record");
3617 V = BitcodeConstant::create(
3618 Alloc, CurTy, Instruction::ShuffleVector,
3623 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3625 dyn_cast_or_null<VectorType>(getTypeByID(
Record[0]));
3626 if (
Record.size() < 4 || !RTy || !OpTy)
3627 return error(
"Invalid shufflevector constexpr record");
3628 V = BitcodeConstant::create(
3629 Alloc, CurTy, Instruction::ShuffleVector,
3635 return error(
"Invalid cmp constexpt record");
3636 unsigned OpTyID =
Record[0];
3637 Type *OpTy = getTypeByID(OpTyID);
3639 return error(
"Invalid cmp constexpr record");
3640 V = BitcodeConstant::create(
3643 : Instruction::ICmp),
3652 return error(
"Invalid inlineasm record");
3653 std::string AsmStr, ConstrStr;
3654 bool HasSideEffects =
Record[0] & 1;
3655 bool IsAlignStack =
Record[0] >> 1;
3656 unsigned AsmStrSize =
Record[1];
3657 if (2+AsmStrSize >=
Record.size())
3658 return error(
"Invalid inlineasm record");
3659 unsigned ConstStrSize =
Record[2+AsmStrSize];
3660 if (3+AsmStrSize+ConstStrSize >
Record.size())
3661 return error(
"Invalid inlineasm record");
3663 for (
unsigned i = 0; i != AsmStrSize; ++i)
3664 AsmStr += (
char)
Record[2+i];
3665 for (
unsigned i = 0; i != ConstStrSize; ++i)
3666 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3669 return error(
"Missing element type for old-style inlineasm");
3671 HasSideEffects, IsAlignStack);
3678 return error(
"Invalid inlineasm record");
3679 std::string AsmStr, ConstrStr;
3680 bool HasSideEffects =
Record[0] & 1;
3681 bool IsAlignStack = (
Record[0] >> 1) & 1;
3682 unsigned AsmDialect =
Record[0] >> 2;
3683 unsigned AsmStrSize =
Record[1];
3684 if (2+AsmStrSize >=
Record.size())
3685 return error(
"Invalid inlineasm record");
3686 unsigned ConstStrSize =
Record[2+AsmStrSize];
3687 if (3+AsmStrSize+ConstStrSize >
Record.size())
3688 return error(
"Invalid inlineasm record");
3690 for (
unsigned i = 0; i != AsmStrSize; ++i)
3691 AsmStr += (
char)
Record[2+i];
3692 for (
unsigned i = 0; i != ConstStrSize; ++i)
3693 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3696 return error(
"Missing element type for old-style inlineasm");
3698 HasSideEffects, IsAlignStack,
3705 return error(
"Invalid inlineasm record");
3707 std::string AsmStr, ConstrStr;
3708 bool HasSideEffects =
Record[OpNum] & 1;
3709 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3710 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3711 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3713 unsigned AsmStrSize =
Record[OpNum];
3715 if (OpNum + AsmStrSize >=
Record.size())
3716 return error(
"Invalid inlineasm record");
3717 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3718 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3719 return error(
"Invalid inlineasm record");
3721 for (
unsigned i = 0; i != AsmStrSize; ++i)
3722 AsmStr += (
char)
Record[OpNum + i];
3724 for (
unsigned i = 0; i != ConstStrSize; ++i)
3725 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3728 return error(
"Missing element type for old-style inlineasm");
3730 HasSideEffects, IsAlignStack,
3737 return error(
"Invalid inlineasm record");
3739 auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(
Record[OpNum]));
3742 return error(
"Invalid inlineasm record");
3743 std::string AsmStr, ConstrStr;
3744 bool HasSideEffects =
Record[OpNum] & 1;
3745 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3746 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3747 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3749 unsigned AsmStrSize =
Record[OpNum];
3751 if (OpNum + AsmStrSize >=
Record.size())
3752 return error(
"Invalid inlineasm record");
3753 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3754 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3755 return error(
"Invalid inlineasm record");
3757 for (
unsigned i = 0; i != AsmStrSize; ++i)
3758 AsmStr += (
char)
Record[OpNum + i];
3760 for (
unsigned i = 0; i != ConstStrSize; ++i)
3761 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3763 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3769 return error(
"Invalid blockaddress record");
3770 unsigned FnTyID =
Record[0];
3771 Type *FnTy = getTypeByID(FnTyID);
3773 return error(
"Invalid blockaddress record");
3774 V = BitcodeConstant::create(
3782 return error(
"Invalid dso_local record");
3783 unsigned GVTyID =
Record[0];
3784 Type *GVTy = getTypeByID(GVTyID);
3786 return error(
"Invalid dso_local record");
3787 V = BitcodeConstant::create(
3788 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode,
Record[1]);
3793 return error(
"Invalid no_cfi record");
3794 unsigned GVTyID =
Record[0];
3795 Type *GVTy = getTypeByID(GVTyID);
3797 return error(
"Invalid no_cfi record");
3798 V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3804 return error(
"Invalid ptrauth record");
3806 V = BitcodeConstant::create(Alloc, CurTy,
3807 BitcodeConstant::ConstantPtrAuthOpcode,
3814 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3821Error BitcodeReader::parseUseLists() {
3834 switch (
Entry.Kind) {
3837 return error(
"Malformed block");
3851 switch (MaybeRecord.
get()) {
3859 if (RecordLength < 3)
3861 return error(
"Invalid record");
3862 unsigned ID =
Record.pop_back_val();
3866 assert(
ID < FunctionBBs.size() &&
"Basic block not found");
3867 V = FunctionBBs[
ID];
3871 if (!
V->hasUseList())
3874 unsigned NumUses = 0;
3876 for (
const Use &U :
V->materialized_uses()) {
3877 if (++NumUses >
Record.size())
3879 Order[&
U] =
Record[NumUses - 1];
3886 V->sortUseList([&](
const Use &L,
const Use &R) {
3897Error BitcodeReader::rememberAndSkipMetadata() {
3899 uint64_t CurBit = Stream.GetCurrentBitNo();
3900 DeferredMetadataInfo.push_back(CurBit);
3903 if (
Error Err = Stream.SkipBlock())
3908Error BitcodeReader::materializeMetadata() {
3909 for (
uint64_t BitPos : DeferredMetadataInfo) {
3911 if (
Error JumpFailed = Stream.JumpToBit(BitPos))
3913 if (
Error Err = MDLoader->parseModuleMetadata())
3924 for (
const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3925 LinkerOpts->
addOperand(cast<MDNode>(MDOptions));
3929 DeferredMetadataInfo.clear();
3933void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
3937Error BitcodeReader::rememberAndSkipFunctionBody() {
3939 if (FunctionsWithBodies.empty())
3940 return error(
"Insufficient function protos");
3943 FunctionsWithBodies.pop_back();
3946 uint64_t CurBit = Stream.GetCurrentBitNo();
3948 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3949 "Mismatch between VST and scanned function offsets");
3950 DeferredFunctionInfo[Fn] = CurBit;
3953 if (
Error Err = Stream.SkipBlock())
3958Error BitcodeReader::globalCleanup() {
3960 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
3962 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3963 return error(
"Malformed global initializer set");
3968 MDLoader->upgradeDebugIntrinsics(
F);
3971 UpgradedIntrinsics[&
F] = NewFn;
3977 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3980 UpgradedVariables.emplace_back(&GV, Upgraded);
3981 for (
auto &Pair : UpgradedVariables) {
3982 Pair.first->eraseFromParent();
3983 TheModule->insertGlobalVariable(Pair.second);
3988 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
3989 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
3997Error BitcodeReader::rememberAndSkipFunctionBodies() {
3998 if (
Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
4001 if (Stream.AtEndOfStream())
4002 return error(
"Could not find function in stream");
4004 if (!SeenFirstFunctionBody)
4005 return error(
"Trying to materialize functions before seeing function blocks");
4009 assert(SeenValueSymbolTable);
4017 switch (
Entry.Kind) {
4019 return error(
"Expect SubBlock");
4023 return error(
"Expect function block");
4025 if (
Error Err = rememberAndSkipFunctionBody())
4027 NextUnreadBit = Stream.GetCurrentBitNo();
4034Error BitcodeReaderBase::readBlockInfo() {
4036 Stream.ReadBlockInfoBlock();
4037 if (!MaybeNewBlockInfo)
4039 std::optional<BitstreamBlockInfo> NewBlockInfo =
4040 std::move(MaybeNewBlockInfo.
get());
4042 return error(
"Malformed block");
4043 BlockInfo = std::move(*NewBlockInfo);
4054 return error(
"Invalid record");
4056 std::string OldFormatName;
4059 return error(
"Invalid record");
4060 unsigned ComdatNameSize =
Record[1];
4061 if (ComdatNameSize >
Record.size() - 2)
4062 return error(
"Comdat name size too large");
4063 OldFormatName.reserve(ComdatNameSize);
4064 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4065 OldFormatName += (
char)
Record[2 + i];
4066 Name = OldFormatName;
4069 C->setSelectionKind(SK);
4070 ComdatList.push_back(
C);
4084 Meta.NoAddress =
true;
4086 Meta.NoHWAddress =
true;
4090 Meta.IsDynInit =
true;
4105 return error(
"Invalid record");
4106 unsigned TyID =
Record[0];
4107 Type *Ty = getTypeByID(TyID);
4109 return error(
"Invalid record");
4111 bool explicitType =
Record[1] & 2;
4117 return error(
"Invalid type for value");
4118 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
4119 TyID = getContainedTypeID(TyID);
4120 Ty = getTypeByID(TyID);
4122 return error(
"Missing element type for old-style global");
4128 if (
Error Err = parseAlignmentValue(
Record[4], Alignment))
4132 if (
Record[5] - 1 >= SectionTable.size())
4133 return error(
"Invalid ID");
4150 bool ExternallyInitialized =
false;
4152 ExternallyInitialized =
Record[9];
4164 if (
Record.size() > 10) {
4176 if (
unsigned InitID =
Record[2])
4177 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4179 if (
Record.size() > 11) {
4180 if (
unsigned ComdatID =
Record[11]) {
4181 if (ComdatID > ComdatList.size())
4182 return error(
"Invalid global variable comdat ID");
4183 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4186 ImplicitComdatObjects.
insert(NewGV);
4189 if (
Record.size() > 12) {
4194 if (
Record.size() > 13) {
4213 return error(
"Invalid global variable code model");
4219void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4220 if (ValueTypeCallback) {
4221 (*ValueTypeCallback)(
4222 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4223 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4236 return error(
"Invalid record");
4237 unsigned FTyID =
Record[0];
4238 Type *FTy = getTypeByID(FTyID);
4240 return error(
"Invalid record");
4241 if (isa<PointerType>(FTy)) {
4242 FTyID = getContainedTypeID(FTyID, 0);
4243 FTy = getTypeByID(FTyID);
4245 return error(
"Missing element type for old-style function");
4248 if (!isa<FunctionType>(FTy))
4249 return error(
"Invalid type for value");
4252 return error(
"Invalid calling convention ID");
4254 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4260 AddrSpace,
Name, TheModule);
4263 "Incorrect fully specified type provided for function");
4264 FunctionTypeIDs[
Func] = FTyID;
4266 Func->setCallingConv(CC);
4267 bool isProto =
Record[2];
4271 callValueTypeCallback(Func, FTyID);
4276 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4278 Attribute::InAlloca}) {
4279 if (!
Func->hasParamAttribute(i, Kind))
4282 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4285 Func->removeParamAttr(i, Kind);
4287 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4288 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4290 return error(
"Missing param element type for attribute upgrade");
4294 case Attribute::ByVal:
4297 case Attribute::StructRet:
4300 case Attribute::InAlloca:
4307 Func->addParamAttr(i, NewAttr);
4312 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4313 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4314 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4316 return error(
"Missing param element type for x86_intrcc upgrade");
4318 Func->addParamAttr(0, NewAttr);
4322 if (
Error Err = parseAlignmentValue(
Record[5], Alignment))
4325 Func->setAlignment(*Alignment);
4327 if (
Record[6] - 1 >= SectionTable.size())
4328 return error(
"Invalid ID");
4329 Func->setSection(SectionTable[
Record[6] - 1]);
4333 if (!
Func->hasLocalLinkage())
4336 if (
Record[8] - 1 >= GCTable.size())
4337 return error(
"Invalid ID");
4343 Func->setUnnamedAddr(UnnamedAddr);
4345 FunctionOperandInfo OperandInfo = {
Func, 0, 0, 0};
4347 OperandInfo.Prologue =
Record[10];
4349 if (
Record.size() > 11) {
4351 if (!
Func->hasLocalLinkage()) {
4358 if (
Record.size() > 12) {
4359 if (
unsigned ComdatID =
Record[12]) {
4360 if (ComdatID > ComdatList.size())
4361 return error(
"Invalid function comdat ID");
4362 Func->setComdat(ComdatList[ComdatID - 1]);
4365 ImplicitComdatObjects.
insert(Func);
4369 OperandInfo.Prefix =
Record[13];
4372 OperandInfo.PersonalityFn =
Record[14];
4374 if (
Record.size() > 15) {
4383 if (
Record.size() > 18 && Strtab.data() &&
4388 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4390 if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4391 FunctionOperands.push_back(OperandInfo);
4396 Func->setIsMaterializable(
true);
4397 FunctionsWithBodies.push_back(Func);
4398 DeferredFunctionInfo[
Func] = 0;
4403Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4417 if (
Record.size() < (3 + (
unsigned)NewRecord))
4418 return error(
"Invalid record");
4423 return error(
"Invalid record");
4427 auto *PTy = dyn_cast<PointerType>(Ty);
4429 return error(
"Invalid type for value");
4430 AddrSpace = PTy->getAddressSpace();
4432 Ty = getTypeByID(
TypeID);
4434 return error(
"Missing element type for old-style indirect symbol");
4436 AddrSpace =
Record[OpNum++];
4439 auto Val =
Record[OpNum++];
4448 nullptr, TheModule);
4452 if (OpNum !=
Record.size()) {
4453 auto VisInd = OpNum++;
4459 if (OpNum !=
Record.size()) {
4460 auto S =
Record[OpNum++];
4467 if (OpNum !=
Record.size())
4469 if (OpNum !=
Record.size())
4472 if (OpNum !=
Record.size())
4477 if (OpNum + 1 <
Record.size()) {
4480 return error(
"Malformed partition, too large.");
4486 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4491 bool ShouldLazyLoadMetadata,
4493 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4495 if (
Error JumpFailed = Stream.JumpToBit(ResumeBit))
4504 bool ResolvedDataLayout =
false;
4509 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4511 auto ResolveDataLayout = [&]() ->
Error {
4512 if (ResolvedDataLayout)
4516 ResolvedDataLayout =
true;
4520 TentativeDataLayoutStr, TheModule->getTargetTriple().str());
4524 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4525 TheModule->getTargetTriple().str(), TentativeDataLayoutStr))
4526 TentativeDataLayoutStr = *LayoutOverride;
4534 TheModule->setDataLayout(MaybeDL.
get());
4545 switch (
Entry.Kind) {
4547 return error(
"Malformed block");
4549 if (
Error Err = ResolveDataLayout())
4551 return globalCleanup();
4556 if (
Error Err = Stream.SkipBlock())
4560 if (
Error Err = readBlockInfo())
4564 if (
Error Err = parseAttributeBlock())
4568 if (
Error Err = parseAttributeGroupBlock())
4572 if (
Error Err = parseTypeTable())
4576 if (!SeenValueSymbolTable) {
4582 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4583 if (
Error Err = parseValueSymbolTable())
4585 SeenValueSymbolTable =
true;
4590 if (
Error Err = Stream.SkipBlock())
4595 if (
Error Err = parseConstants())
4597 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4601 if (ShouldLazyLoadMetadata) {
4602 if (
Error Err = rememberAndSkipMetadata())
4606 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4607 if (
Error Err = MDLoader->parseModuleMetadata())
4611 if (
Error Err = MDLoader->parseMetadataKinds())
4615 if (
Error Err = ResolveDataLayout())
4620 if (!SeenFirstFunctionBody) {
4621 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4622 if (
Error Err = globalCleanup())
4624 SeenFirstFunctionBody =
true;
4627 if (VSTOffset > 0) {
4631 if (!SeenValueSymbolTable) {
4632 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4634 SeenValueSymbolTable =
true;
4646 if (
Error Err = Stream.SkipBlock())
4656 if (
Error Err = rememberAndSkipFunctionBody())
4663 if (SeenValueSymbolTable) {
4664 NextUnreadBit = Stream.GetCurrentBitNo();
4667 return globalCleanup();
4671 if (
Error Err = parseUseLists())
4675 if (
Error Err = parseOperandBundleTags())
4679 if (
Error Err = parseSyncScopeNames())
4694 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4700 UseRelativeIDs = *VersionOrErr >= 1;
4704 if (ResolvedDataLayout)
4705 return error(
"target triple too late in module");
4708 return error(
"Invalid record");
4709 TheModule->setTargetTriple(
Triple(std::move(S)));
4713 if (ResolvedDataLayout)
4714 return error(
"datalayout too late in module");
4716 return error(
"Invalid record");
4722 return error(
"Invalid record");
4723 TheModule->setModuleInlineAsm(S);
4730 return error(
"Invalid record");
4737 return error(
"Invalid record");
4738 SectionTable.push_back(S);
4744 return error(
"Invalid record");
4745 GCTable.push_back(S);
4762 if (
Error Err = ResolveDataLayout())
4770 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode,
Record))
4776 return error(
"Invalid record");
4780 VSTOffset =
Record[0] - 1;
4786 return error(
"Invalid record");
4787 TheModule->setSourceFileName(
ValueName);
4792 this->ValueTypeCallback = std::nullopt;
4796Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4801 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(
ID); };
4803 return getContainedTypeID(
I, J);
4806 MDLoader =
MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4807 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4810Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4811 if (!isa<PointerType>(PtrType))
4812 return error(
"Load/Store operand is not a pointer type");
4813 if (!PointerType::isLoadableOrStorableType(ValType))
4814 return error(
"Cannot load/store from pointer");
4821 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4823 Attribute::InAlloca}) {
4824 if (!
Attrs.hasParamAttr(i, Kind) ||
4825 Attrs.getParamAttr(i, Kind).getValueAsType())
4828 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4830 return error(
"Missing element type for typed attribute upgrade");
4834 case Attribute::ByVal:
4837 case Attribute::StructRet:
4840 case Attribute::InAlloca:
4847 Attrs =
Attrs.addParamAttribute(Context, i, NewAttr);
4858 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
4859 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4861 return error(
"Missing element type for inline asm upgrade");
4872 case Intrinsic::preserve_array_access_index:
4873 case Intrinsic::preserve_struct_access_index:
4874 case Intrinsic::aarch64_ldaxr:
4875 case Intrinsic::aarch64_ldxr:
4876 case Intrinsic::aarch64_stlxr:
4877 case Intrinsic::aarch64_stxr:
4878 case Intrinsic::arm_ldaex:
4879 case Intrinsic::arm_ldrex:
4880 case Intrinsic::arm_stlex:
4881 case Intrinsic::arm_strex: {
4884 case Intrinsic::aarch64_stlxr:
4885 case Intrinsic::aarch64_stxr:
4886 case Intrinsic::arm_stlex:
4887 case Intrinsic::arm_strex:
4894 if (!
Attrs.getParamElementType(ArgNo)) {
4895 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4897 return error(
"Missing element type for elementtype upgrade");
4899 Attrs =
Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4917 if (MDLoader->hasFwdRefs())
4918 return error(
"Invalid function metadata: incoming forward references");
4920 InstructionList.
clear();
4921 unsigned ModuleValueListSize = ValueList.
size();
4922 unsigned ModuleMDLoaderSize = MDLoader->size();
4926 unsigned FTyID = FunctionTypeIDs[
F];
4928 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4929 assert(
I.getType() == getTypeByID(ArgTyID) &&
4930 "Incorrect fully specified type for Function Argument");
4934 unsigned NextValueNo = ValueList.
size();
4936 unsigned CurBBNo = 0;
4945 auto getLastInstruction = [&]() ->
Instruction * {
4946 if (CurBB && !CurBB->
empty())
4947 return &CurBB->
back();
4948 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4949 !FunctionBBs[CurBBNo - 1]->empty())
4950 return &FunctionBBs[CurBBNo - 1]->back();
4954 std::vector<OperandBundleDef> OperandBundles;
4965 switch (
Entry.Kind) {
4967 return error(
"Malformed block");
4969 goto OutOfRecordLoop;
4974 if (
Error Err = Stream.SkipBlock())
4978 if (
Error Err = parseConstants())
4980 NextValueNo = ValueList.
size();
4983 if (
Error Err = parseValueSymbolTable())
4987 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
4991 assert(DeferredMetadataInfo.empty() &&
4992 "Must read all module-level metadata before function-level");
4993 if (
Error Err = MDLoader->parseFunctionMetadata())
4997 if (
Error Err = parseUseLists())
5011 unsigned ResTypeID = InvalidTypeID;
5015 switch (
unsigned BitCode = MaybeBitCode.
get()) {
5017 return error(
"Invalid value");
5020 return error(
"Invalid record");
5022 FunctionBBs.resize(
Record[0]);
5025 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5026 if (BBFRI == BasicBlockFwdRefs.
end()) {
5030 auto &BBRefs = BBFRI->second;
5032 if (BBRefs.size() > FunctionBBs.size())
5033 return error(
"Invalid ID");
5034 assert(!BBRefs.empty() &&
"Unexpected empty array");
5035 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5036 for (
unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size();
I != E;
5038 if (
I < RE && BBRefs[
I]) {
5039 BBRefs[
I]->insertInto(
F);
5040 FunctionBBs[
I] = BBRefs[
I];
5046 BasicBlockFwdRefs.
erase(BBFRI);
5049 CurBB = FunctionBBs[0];
5056 return error(
"Invalid record");
5071 if (
auto *
F = dyn_cast<Function>(ValueList[
ValID]))
5072 BackwardRefFunctions.push_back(
F);
5074 return error(
"Invalid record");
5081 I = getLastInstruction();
5084 return error(
"Invalid record");
5085 I->setDebugLoc(LastLoc);
5090 I = getLastInstruction();
5092 return error(
"Invalid record");
5102 Scope = dyn_cast_or_null<MDNode>(
5103 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5105 return error(
"Invalid record");
5108 IA = dyn_cast_or_null<MDNode>(
5109 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5111 return error(
"Invalid record");
5114 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5115 isImplicitCode, AtomGroup, AtomRank);
5116 I->setDebugLoc(LastLoc);
5124 if (getValueTypePair(
Record, OpNum, NextValueNo, LHS,
TypeID, CurBB) ||
5126 return error(
"Invalid record");
5130 return error(
"Invalid record");
5134 if (OpNum <
Record.size()) {
5135 if (isa<FPMathOperator>(
I)) {
5138 I->setFastMathFlags(FMF);
5147 if (getValueTypePair(
Record, OpNum, NextValueNo, LHS,
TypeID, CurBB) ||
5151 return error(
"Invalid record");
5155 return error(
"Invalid record");
5159 if (OpNum <
Record.size()) {
5160 if (
Opc == Instruction::Add ||
5161 Opc == Instruction::Sub ||
5162 Opc == Instruction::Mul ||
5163 Opc == Instruction::Shl) {
5165 cast<BinaryOperator>(
I)->setHasNoSignedWrap(
true);
5167 cast<BinaryOperator>(
I)->setHasNoUnsignedWrap(
true);
5168 }
else if (
Opc == Instruction::SDiv ||
5169 Opc == Instruction::UDiv ||
5170 Opc == Instruction::LShr ||
5171 Opc == Instruction::AShr) {
5173 cast<BinaryOperator>(
I)->setIsExact(
true);
5174 }
else if (
Opc == Instruction::Or) {
5176 cast<PossiblyDisjointInst>(
I)->setIsDisjoint(
true);
5177 }
else if (isa<FPMathOperator>(
I)) {
5180 I->setFastMathFlags(FMF);
5189 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5190 OpNum + 1 >
Record.size())
5191 return error(
"Invalid record");
5193 ResTypeID =
Record[OpNum++];
5194 Type *ResTy = getTypeByID(ResTypeID);
5197 if (
Opc == -1 || !ResTy)
5198 return error(
"Invalid record");
5203 assert(CurBB &&
"No current BB?");
5209 return error(
"Invalid cast");
5213 if (OpNum <
Record.size()) {
5214 if (
Opc == Instruction::ZExt ||
Opc == Instruction::UIToFP) {
5216 cast<PossiblyNonNegInst>(
I)->setNonNeg(
true);
5217 }
else if (
Opc == Instruction::Trunc) {
5219 cast<TruncInst>(
I)->setHasNoUnsignedWrap(
true);
5221 cast<TruncInst>(
I)->setHasNoSignedWrap(
true);
5223 if (isa<FPMathOperator>(
I)) {
5226 I->setFastMathFlags(FMF);
5245 Ty = getTypeByID(TyID);
5249 TyID = InvalidTypeID;
5254 unsigned BasePtrTypeID;
5255 if (getValueTypePair(
Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5257 return error(
"Invalid record");
5260 TyID = getContainedTypeID(BasePtrTypeID);
5261 if (
BasePtr->getType()->isVectorTy())
5262 TyID = getContainedTypeID(TyID);
5263 Ty = getTypeByID(TyID);
5267 while (OpNum !=
Record.size()) {
5270 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5271 return error(
"Invalid record");
5279 if (cast<GEPOperator>(
I)->getNumIndices() != 0) {
5282 unsigned SubType = 0;
5283 if (GTI.isStruct()) {
5285 Idx->getType()->isVectorTy()
5290 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5297 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5298 if (
I->getType()->isVectorTy())
5299 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5302 GEP->setNoWrapFlags(NW);
5311 if (getValueTypePair(
Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5312 return error(
"Invalid record");
5315 unsigned RecSize =
Record.size();
5316 if (OpNum == RecSize)
5317 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5320 ResTypeID = AggTypeID;
5321 for (; OpNum != RecSize; ++OpNum) {
5326 if (!IsStruct && !IsArray)
5327 return error(
"EXTRACTVAL: Invalid type");
5328 if ((
unsigned)Index != Index)
5329 return error(
"Invalid value");
5331 return error(
"EXTRACTVAL: Invalid struct index");
5333 return error(
"EXTRACTVAL: Invalid array index");
5334 EXTRACTVALIdx.
push_back((
unsigned)Index);
5338 ResTypeID = getContainedTypeID(ResTypeID, Index);
5341 ResTypeID = getContainedTypeID(ResTypeID);
5355 if (getValueTypePair(
Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5356 return error(
"Invalid record");
5359 if (getValueTypePair(
Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5360 return error(
"Invalid record");
5362 unsigned RecSize =
Record.size();
5363 if (OpNum == RecSize)
5364 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5368 for (; OpNum != RecSize; ++OpNum) {
5373 if (!IsStruct && !IsArray)
5374 return error(
"INSERTVAL: Invalid type");
5375 if ((
unsigned)Index != Index)
5376 return error(
"Invalid value");
5378 return error(
"INSERTVAL: Invalid struct index");
5380 return error(
"INSERTVAL: Invalid array index");
5382 INSERTVALIdx.
push_back((
unsigned)Index);
5390 return error(
"Inserted value type doesn't match aggregate type");
5393 ResTypeID = AggTypeID;
5405 if (getValueTypePair(
Record, OpNum, NextValueNo, TrueVal,
TypeID,
5409 popValue(
Record, OpNum, NextValueNo, CondType,
5410 getVirtualTypeID(CondType),
Cond, CurBB))
5411 return error(
"Invalid record");
5424 unsigned ValTypeID, CondTypeID;
5425 if (getValueTypePair(
Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5427 popValue(
Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5429 getValueTypePair(
Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5430 return error(
"Invalid record");
5434 dyn_cast<VectorType>(
Cond->getType())) {
5437 return error(
"Invalid type for value");
5441 return error(
"Invalid type for value");
5445 ResTypeID = ValTypeID;
5447 if (OpNum <
Record.size() && isa<FPMathOperator>(
I)) {
5450 I->setFastMathFlags(FMF);
5458 unsigned VecTypeID, IdxTypeID;
5459 if (getValueTypePair(
Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5460 getValueTypePair(
Record, OpNum, NextValueNo,
Idx, IdxTypeID, CurBB))
5461 return error(
"Invalid record");
5463 return error(
"Invalid type for value");
5465 ResTypeID = getContainedTypeID(VecTypeID);
5473 unsigned VecTypeID, IdxTypeID;
5474 if (getValueTypePair(
Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5475 return error(
"Invalid record");
5477 return error(
"Invalid type for value");
5478 if (popValue(
Record, OpNum, NextValueNo,
5479 cast<VectorType>(Vec->
getType())->getElementType(),
5480 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5481 getValueTypePair(
Record, OpNum, NextValueNo,
Idx, IdxTypeID, CurBB))
5482 return error(
"Invalid record");
5484 ResTypeID = VecTypeID;
5492 unsigned Vec1TypeID;
5493 if (getValueTypePair(
Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5495 popValue(
Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5497 return error(
"Invalid record");
5499 unsigned MaskTypeID;
5500 if (getValueTypePair(
Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5501 return error(
"Invalid record");
5503 return error(
"Invalid type for value");
5507 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5522 if (getValueTypePair(
Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
5525 return error(
"Invalid record");
5527 if (OpNum >=
Record.size())
5529 "Invalid record: operand number exceeded available operands");
5534 if (IsFP &&
Record.size() > OpNum+1)
5539 return error(
"Invalid fcmp predicate");
5543 return error(
"Invalid icmp predicate");
5545 if (
Record.size() > OpNum + 1 &&
5547 cast<ICmpInst>(
I)->setSameSign();
5550 if (OpNum + 1 !=
Record.size())
5551 return error(
"Invalid record");
5553 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5555 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5558 I->setFastMathFlags(FMF);
5575 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5576 return error(
"Invalid record");
5577 if (OpNum !=
Record.size())
5578 return error(
"Invalid record");
5586 return error(
"Invalid record");
5589 return error(
"Invalid record");
5591 if (
Record.size() == 1) {
5599 getVirtualTypeID(CondType), CurBB);
5600 if (!FalseDest || !
Cond)
5601 return error(
"Invalid record");
5609 return error(
"Invalid record");
5612 Value *CleanupPad = getValue(
Record,
Idx++, NextValueNo, TokenTy,
5613 getVirtualTypeID(TokenTy), CurBB);
5615 return error(
"Invalid record");
5617 if (
Record.size() == 2) {
5618 UnwindDest = getBasicBlock(
Record[
Idx++]);
5620 return error(
"Invalid record");
5629 return error(
"Invalid record");
5633 getVirtualTypeID(TokenTy), CurBB);
5635 return error(
"Invalid record");
5638 return error(
"Invalid record");
5647 return error(
"Invalid record");
5653 getVirtualTypeID(TokenTy), CurBB);
5655 return error(
"Invalid record");
5660 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5663 return error(
"Invalid record");
5669 UnwindDest = getBasicBlock(
Record[
Idx++]);
5671 return error(
"Invalid record");
5675 return error(
"Invalid record");
5680 CatchSwitch->addHandler(Handler);
5682 ResTypeID = getVirtualTypeID(
I->getType());
5690 return error(
"Invalid record");
5696 getVirtualTypeID(TokenTy), CurBB);
5698 return error(
"Invald record");
5700 unsigned NumArgOperands =
Record[
Idx++];
5703 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5706 if (getValueTypePair(
Record,
Idx, NextValueNo, Val, ValTypeID,
nullptr))
5707 return error(
"Invalid record");
5708 Args.push_back(Val);
5712 return error(
"Invalid record");
5718 ResTypeID = getVirtualTypeID(
I->getType());
5724 if ((
Record[0] >> 16) == SWITCH_INST_MAGIC) {
5730 unsigned OpTyID =
Record[1];
5731 Type *OpTy = getTypeByID(OpTyID);
5732 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5737 return error(
"Invalid record");
5739 unsigned NumCases =
Record[4];
5744 unsigned CurIdx = 5;
5745 for (
unsigned i = 0; i != NumCases; ++i) {
5747 unsigned NumItems =
Record[CurIdx++];
5748 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5749 bool isSingleNumber =
Record[CurIdx++];
5752 unsigned ActiveWords = 1;
5753 if (ValueBitWidth > 64)
5754 ActiveWords =
Record[CurIdx++];
5757 CurIdx += ActiveWords;
5759 if (!isSingleNumber) {
5761 if (ValueBitWidth > 64)
5762 ActiveWords =
Record[CurIdx++];
5765 CurIdx += ActiveWords;
5778 SI->addCase(Cst, DestBB);
5787 return error(
"Invalid record");
5788 unsigned OpTyID =
Record[0];
5789 Type *OpTy = getTypeByID(OpTyID);
5793 return error(
"Invalid record");
5794 unsigned NumCases = (
Record.size()-3)/2;
5797 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
5798 ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
5799 getFnValueByID(
Record[3+i*2], OpTy, OpTyID,
nullptr));
5801 if (!CaseVal || !DestBB) {
5803 return error(
"Invalid record");
5805 SI->addCase(CaseVal, DestBB);
5812 return error(
"Invalid record");
5813 unsigned OpTyID =
Record[0];
5814 Type *OpTy = getTypeByID(OpTyID);
5816 if (!OpTy || !Address)
5817 return error(
"Invalid record");
5818 unsigned NumDests =
Record.size()-2;
5821 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
5826 return error(
"Invalid record");
5836 return error(
"Invalid record");
5839 unsigned CCInfo =
Record[OpNum++];
5843 unsigned FTyID = InvalidTypeID;
5845 if ((CCInfo >> 13) & 1) {
5847 FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5849 return error(
"Explicit invoke type is not a function type");
5853 unsigned CalleeTypeID;
5854 if (getValueTypePair(
Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5856 return error(
"Invalid record");
5860 return error(
"Callee is not a pointer");
5862 FTyID = getContainedTypeID(CalleeTypeID);
5863 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5865 return error(
"Callee is not of pointer to function type");
5867 if (
Record.size() < FTy->getNumParams() + OpNum)
5868 return error(
"Insufficient operands to call");
5872 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5873 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5874 Ops.
push_back(getValue(
Record, OpNum, NextValueNo, FTy->getParamType(i),
5878 return error(
"Invalid record");
5881 if (!FTy->isVarArg()) {
5882 if (
Record.size() != OpNum)
5883 return error(
"Invalid record");
5886 while (OpNum !=
Record.size()) {
5889 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5890 return error(
"Invalid record");
5897 if (!OperandBundles.empty())
5902 ResTypeID = getContainedTypeID(FTyID);
5903 OperandBundles.clear();
5905 cast<InvokeInst>(
I)->setCallingConv(
5907 cast<InvokeInst>(
I)->setAttributes(PAL);
5908 if (
Error Err = propagateAttributeTypes(cast<CallBase>(
I), ArgTyIDs)) {
5917 Value *Val =
nullptr;
5919 if (getValueTypePair(
Record,
Idx, NextValueNo, Val, ValTypeID, CurBB))
5920 return error(
"Invalid record");
5929 unsigned CCInfo =
Record[OpNum++];
5932 unsigned NumIndirectDests =
Record[OpNum++];
5934 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
5937 unsigned FTyID = InvalidTypeID;
5941 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5943 return error(
"Explicit call type is not a function type");
5947 unsigned CalleeTypeID;
5948 if (getValueTypePair(
Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5950 return error(
"Invalid record");
5954 return error(
"Callee is not a pointer type");
5956 FTyID = getContainedTypeID(CalleeTypeID);
5957 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5959 return error(
"Callee is not of pointer to function type");
5961 if (
Record.size() < FTy->getNumParams() + OpNum)
5962 return error(
"Insufficient operands to call");
5967 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5969 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5970 if (FTy->getParamType(i)->isLabelTy())
5971 Arg = getBasicBlock(
Record[OpNum]);
5973 Arg = getValue(
Record, OpNum, NextValueNo, FTy->getParamType(i),
5976 return error(
"Invalid record");
5977 Args.push_back(Arg);
5982 if (!FTy->isVarArg()) {
5983 if (OpNum !=
Record.size())
5984 return error(
"Invalid record");
5986 while (OpNum !=
Record.size()) {
5989 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5990 return error(
"Invalid record");
5997 if (!OperandBundles.empty())
6000 if (
auto *IA = dyn_cast<InlineAsm>(Callee)) {
6005 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
6010 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
6011 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
6012 unsigned LabelNo = ArgNo - FirstBlockArg;
6013 auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
6014 if (!BA || BA->getFunction() !=
F ||
6015 LabelNo > IndirectDests.
size() ||
6016 BA->getBasicBlock() != IndirectDests[LabelNo])
6017 return error(
"callbr argument does not match indirect dest");
6022 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6026 for (
Value *Arg : Args)
6029 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6032 std::string Constraints =
IA->getConstraintString().str();
6035 for (
const auto &CI : ConstraintInfo) {
6037 if (ArgNo >= FirstBlockArg)
6038 Constraints.insert(Pos,
"!");
6043 Pos = Constraints.find(
',', Pos);
6044 if (Pos == std::string::npos)
6050 IA->hasSideEffects(),
IA->isAlignStack(),
6051 IA->getDialect(),
IA->canThrow());
6057 ResTypeID = getContainedTypeID(FTyID);
6058 OperandBundles.clear();
6060 cast<CallBrInst>(
I)->setCallingConv(
6062 cast<CallBrInst>(
I)->setAttributes(PAL);
6063 if (
Error Err = propagateAttributeTypes(cast<CallBase>(
I), ArgTyIDs)) {
6075 return error(
"Invalid phi record");
6077 unsigned TyID =
Record[0];
6078 Type *Ty = getTypeByID(TyID);
6080 return error(
"Invalid phi record");
6085 size_t NumArgs = (
Record.size() - 1) / 2;
6087 if ((
Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
6089 return error(
"Invalid phi record");
6094 for (
unsigned i = 0; i != NumArgs; i++) {
6098 return error(
"Invalid phi BB");
6105 auto It =
Args.find(BB);
6107 if (It !=
Args.end()) {
6121 if (!PhiConstExprBB)
6123 EdgeBB = PhiConstExprBB;
6131 V = getValueSigned(
Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6133 V = getValue(
Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6137 return error(
"Invalid phi record");
6140 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6141 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6142 PhiConstExprBB =
nullptr;
6145 Args.insert({BB,
V});
6151 if (
Record.size() % 2 == 0) {
6152 assert(isa<FPMathOperator>(
I) &&
"Unexpected phi type");
6155 I->setFastMathFlags(FMF);
6167 return error(
"Invalid record");
6171 return error(
"Invalid record");
6174 Type *Ty = getTypeByID(ResTypeID);
6176 return error(
"Invalid record");
6178 Value *PersFn =
nullptr;
6179 unsigned PersFnTypeID;
6180 if (getValueTypePair(
Record,
Idx, NextValueNo, PersFn, PersFnTypeID,
6182 return error(
"Invalid record");
6184 if (!
F->hasPersonalityFn())
6185 F->setPersonalityFn(cast<Constant>(PersFn));
6186 else if (
F->getPersonalityFn() != cast<Constant>(PersFn))
6187 return error(
"Personality function mismatch");
6194 for (
unsigned J = 0; J != NumClauses; ++J) {
6200 if (getValueTypePair(
Record,
Idx, NextValueNo, Val, ValTypeID,
6203 return error(
"Invalid record");
6207 !isa<ArrayType>(Val->
getType())) &&
6208 "Catch clause has a invalid type!");
6210 isa<ArrayType>(Val->
getType())) &&
6211 "Filter clause has invalid type!");
6222 return error(
"Invalid record");
6225 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
6226 const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
6227 unsigned TyID =
Record[0];
6228 Type *Ty = getTypeByID(TyID);
6229 if (!Bitfield::get<APV::ExplicitType>(Rec)) {
6230 TyID = getContainedTypeID(TyID);
6231 Ty = getTypeByID(TyID);
6233 return error(
"Missing element type for old-style alloca");
6235 unsigned OpTyID =
Record[1];
6236 Type *OpTy = getTypeByID(OpTyID);
6240 Bitfield::get<APV::AlignLower>(Rec) |
6241 (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
6242 if (
Error Err = parseAlignmentValue(AlignExp,
Align)) {
6246 return error(
"Invalid record");
6249 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6253 return error(
"alloca of unsized type");
6255 Align =
DL.getPrefTypeAlign(Ty);
6257 if (!
Size->getType()->isIntegerTy())
6258 return error(
"alloca element count must have integer type");
6264 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6272 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6273 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6274 return error(
"Invalid record");
6276 if (!isa<PointerType>(
Op->getType()))
6277 return error(
"Load operand is not a pointer type");
6280 if (OpNum + 3 ==
Record.size()) {
6281 ResTypeID =
Record[OpNum++];
6282 Ty = getTypeByID(ResTypeID);
6284 ResTypeID = getContainedTypeID(OpTypeID);
6285 Ty = getTypeByID(ResTypeID);
6289 return error(
"Missing load type");
6291 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6299 return error(
"load of unsized type");
6301 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6311 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6312 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size()))
6313 return error(
"Invalid record");
6315 if (!isa<PointerType>(
Op->getType()))
6316 return error(
"Load operand is not a pointer type");
6319 if (OpNum + 5 ==
Record.size()) {
6320 ResTypeID =
Record[OpNum++];
6321 Ty = getTypeByID(ResTypeID);
6323 ResTypeID = getContainedTypeID(OpTypeID);
6324 Ty = getTypeByID(ResTypeID);
6328 return error(
"Missing atomic load type");
6330 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6334 if (Ordering == AtomicOrdering::NotAtomic ||
6335 Ordering == AtomicOrdering::Release ||
6336 Ordering == AtomicOrdering::AcquireRelease)
6337 return error(
"Invalid record");
6338 if (Ordering != AtomicOrdering::NotAtomic &&
Record[OpNum] == 0)
6339 return error(
"Invalid record");
6346 return error(
"Alignment missing from atomic load");
6355 unsigned PtrTypeID, ValTypeID;
6356 if (getValueTypePair(
Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6357 return error(
"Invalid record");
6360 if (getValueTypePair(
Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6361 return error(
"Invalid record");
6363 ValTypeID = getContainedTypeID(PtrTypeID);
6364 if (popValue(
Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6365 ValTypeID, Val, CurBB))
6366 return error(
"Invalid record");
6369 if (OpNum + 2 !=
Record.size())
6370 return error(
"Invalid record");
6372 if (
Error Err = typeCheckLoadStoreInst(Val->
getType(),
Ptr->getType()))
6379 return error(
"store of unsized type");
6381 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6391 unsigned PtrTypeID, ValTypeID;
6392 if (getValueTypePair(
Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB) ||
6393 !isa<PointerType>(
Ptr->getType()))
6394 return error(
"Invalid record");
6396 if (getValueTypePair(
Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6397 return error(
"Invalid record");
6399 ValTypeID = getContainedTypeID(PtrTypeID);
6400 if (popValue(
Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6401 ValTypeID, Val, CurBB))
6402 return error(
"Invalid record");
6405 if (OpNum + 4 !=
Record.size())
6406 return error(
"Invalid record");
6408 if (
Error Err = typeCheckLoadStoreInst(Val->
getType(),
Ptr->getType()))
6411 if (Ordering == AtomicOrdering::NotAtomic ||
6412 Ordering == AtomicOrdering::Acquire ||
6413 Ordering == AtomicOrdering::AcquireRelease)
6414 return error(
"Invalid record");
6416 if (Ordering != AtomicOrdering::NotAtomic &&
Record[OpNum] == 0)
6417 return error(
"Invalid record");
6423 return error(
"Alignment missing from atomic store");
6431 const size_t NumRecords =
Record.size();
6435 if (getValueTypePair(
Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6436 return error(
"Invalid record");
6438 if (!isa<PointerType>(
Ptr->getType()))
6439 return error(
"Cmpxchg operand is not a pointer type");
6442 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6443 if (popValue(
Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6444 CmpTypeID, Cmp, CurBB))
6445 return error(
"Invalid record");
6448 if (popValue(
Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6450 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6451 return error(
"Invalid record");
6455 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6456 SuccessOrdering == AtomicOrdering::Unordered)
6457 return error(
"Invalid record");
6461 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(),
Ptr->getType()))
6469 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6470 FailureOrdering == AtomicOrdering::Unordered)
6471 return error(
"Invalid record");
6473 const Align Alignment(
6474 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6477 FailureOrdering, SSID);
6478 cast<AtomicCmpXchgInst>(
I)->setVolatile(
Record[OpNum]);
6480 if (NumRecords < 8) {
6484 I->insertInto(CurBB, CurBB->
end());
6486 ResTypeID = CmpTypeID;
6488 cast<AtomicCmpXchgInst>(
I)->setWeak(
Record[OpNum + 4]);
6490 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6499 const size_t NumRecords =
Record.size();
6503 if (getValueTypePair(
Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6504 return error(
"Invalid record");
6506 if (!isa<PointerType>(
Ptr->getType()))
6507 return error(
"Cmpxchg operand is not a pointer type");
6511 if (getValueTypePair(
Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6512 return error(
"Invalid record");
6514 Value *Val =
nullptr;
6515 if (popValue(
Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6517 return error(
"Invalid record");
6519 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6520 return error(
"Invalid record");
6522 const bool IsVol =
Record[OpNum];
6527 return error(
"Invalid cmpxchg success ordering");
6531 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(),
Ptr->getType()))
6537 return error(
"Invalid cmpxchg failure ordering");
6539 const bool IsWeak =
Record[OpNum + 4];
6543 if (NumRecords == (OpNum + 6)) {
6544 if (
Error Err = parseAlignmentValue(
Record[OpNum + 5], Alignment))
6549 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6552 FailureOrdering, SSID);
6553 cast<AtomicCmpXchgInst>(
I)->setVolatile(IsVol);
6554 cast<AtomicCmpXchgInst>(
I)->setWeak(IsWeak);
6557 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6566 const size_t NumRecords =
Record.size();
6571 if (getValueTypePair(
Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6572 return error(
"Invalid record");
6574 if (!isa<PointerType>(
Ptr->getType()))
6575 return error(
"Invalid record");
6577 Value *Val =
nullptr;
6578 unsigned ValTypeID = InvalidTypeID;
6580 ValTypeID = getContainedTypeID(PtrTypeID);
6581 if (popValue(
Record, OpNum, NextValueNo,
6582 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6583 return error(
"Invalid record");
6585 if (getValueTypePair(
Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6586 return error(
"Invalid record");
6589 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6590 return error(
"Invalid record");
6596 return error(
"Invalid record");
6598 const bool IsVol =
Record[OpNum + 1];
6601 if (Ordering == AtomicOrdering::NotAtomic ||
6602 Ordering == AtomicOrdering::Unordered)
6603 return error(
"Invalid record");
6609 if (NumRecords == (OpNum + 5)) {
6610 if (
Error Err = parseAlignmentValue(
Record[OpNum + 4], Alignment))
6616 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6619 ResTypeID = ValTypeID;
6620 cast<AtomicRMWInst>(
I)->setVolatile(IsVol);
6627 return error(
"Invalid record");
6629 if (Ordering == AtomicOrdering::NotAtomic ||
6630 Ordering == AtomicOrdering::Unordered ||
6631 Ordering == AtomicOrdering::Monotonic)
6632 return error(
"Invalid record");
6641 SeenDebugRecord =
true;
6644 return error(
"Invalid dbg record: missing instruction");
6647 Inst->
getParent()->insertDbgRecordBefore(
6657 SeenDebugRecord =
true;
6660 return error(
"Invalid dbg record: missing instruction");
6676 cast<DILocalVariable>(getFnMetadataByID(
Record[Slot++]));
6678 cast<DIExpression>(getFnMetadataByID(
Record[Slot++]));
6690 unsigned SlotBefore =
Slot;
6691 if (getValueTypePair(
Record, Slot, NextValueNo, V, TyID, CurBB))
6692 return error(
"Invalid dbg record: invalid value");
6694 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6697 RawLocation = getFnMetadataByID(
Record[Slot++]);
6705 DbgVariableRecord::LocationType::Value);
6709 DbgVariableRecord::LocationType::Declare);
6714 cast<DIExpression>(getFnMetadataByID(
Record[Slot++]));
6729 return error(
"Invalid record");
6733 unsigned CCInfo =
Record[OpNum++];
6739 return error(
"Fast math flags indicator set for call with no FMF");
6742 unsigned FTyID = InvalidTypeID;
6746 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6748 return error(
"Explicit call type is not a function type");
6752 unsigned CalleeTypeID;
6753 if (getValueTypePair(
Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6755 return error(
"Invalid record");
6759 return error(
"Callee is not a pointer type");
6761 FTyID = getContainedTypeID(CalleeTypeID);
6762 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6764 return error(
"Callee is not of pointer to function type");
6766 if (
Record.size() < FTy->getNumParams() + OpNum)
6767 return error(
"Insufficient operands to call");
6772 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6773 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6774 if (FTy->getParamType(i)->isLabelTy())
6775 Args.push_back(getBasicBlock(
Record[OpNum]));
6777 Args.push_back(getValue(
Record, OpNum, NextValueNo,
6778 FTy->getParamType(i), ArgTyID, CurBB));
6781 return error(
"Invalid record");
6785 if (!FTy->isVarArg()) {
6786 if (OpNum !=
Record.size())
6787 return error(
"Invalid record");
6789 while (OpNum !=
Record.size()) {
6792 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6793 return error(
"Invalid record");
6800 if (!OperandBundles.empty())
6804 ResTypeID = getContainedTypeID(FTyID);
6805 OperandBundles.clear();
6807 cast<CallInst>(
I)->setCallingConv(
6816 cast<CallInst>(
I)->setTailCallKind(TCK);
6817 cast<CallInst>(
I)->setAttributes(PAL);
6818 if (isa<DbgInfoIntrinsic>(
I))
6819 SeenDebugIntrinsic =
true;
6820 if (
Error Err = propagateAttributeTypes(cast<CallBase>(
I), ArgTyIDs)) {
6825 if (!isa<FPMathOperator>(
I))
6826 return error(
"Fast-math-flags specified for call without "
6827 "floating-point scalar or vector return type");
6828 I->setFastMathFlags(FMF);
6834 return error(
"Invalid record");
6835 unsigned OpTyID =
Record[0];
6836 Type *OpTy = getTypeByID(OpTyID);
6837 Value *
Op = getValue(
Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6839 Type *ResTy = getTypeByID(ResTypeID);
6840 if (!OpTy || !
Op || !ResTy)
6841 return error(
"Invalid record");
6853 return error(
"Invalid record");
6855 std::vector<Value *> Inputs;
6858 while (OpNum !=
Record.size()) {
6860 if (getValueOrMetadata(
Record, OpNum, NextValueNo,
Op, CurBB))
6861 return error(
"Invalid record");
6862 Inputs.push_back(
Op);
6865 OperandBundles.emplace_back(BundleTags[
Record[0]], std::move(Inputs));
6873 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6874 return error(
"Invalid record");
6875 if (OpNum !=
Record.size())
6876 return error(
"Invalid record");
6879 ResTypeID = OpTypeID;
6889 return error(
"Invalid instruction with no BB");
6891 if (!OperandBundles.empty()) {
6893 return error(
"Operand bundles found with no consumer");
6895 I->insertInto(CurBB, CurBB->
end());
6898 if (
I->isTerminator()) {
6900 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
6904 if (!
I->getType()->isVoidTy()) {
6905 assert(
I->getType() == getTypeByID(ResTypeID) &&
6906 "Incorrect result type ID");
6914 if (!OperandBundles.empty())
6915 return error(
"Operand bundles found with no consumer");
6919 if (!
A->getParent()) {
6921 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
6922 if ((
A = dyn_cast_or_null<Argument>(ValueList[i])) && !
A->getParent()) {
6927 return error(
"Never resolved value found in function");
6932 if (MDLoader->hasFwdRefs())
6933 return error(
"Invalid function metadata: outgoing forward refs");
6938 for (
const auto &Pair : ConstExprEdgeBBs) {
6943 From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
6949 ValueList.
shrinkTo(ModuleValueListSize);
6950 MDLoader->shrinkTo(ModuleMDLoaderSize);
6951 std::vector<BasicBlock*>().swap(FunctionBBs);
6956Error BitcodeReader::findFunctionInStream(
6959 while (DeferredFunctionInfoIterator->second == 0) {
6964 assert(VSTOffset == 0 || !
F->hasName());
6967 if (
Error Err = rememberAndSkipFunctionBodies())
6973SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
6976 if (Val >= SSIDs.
size())
6988 if (!
F || !
F->isMaterializable())
6992 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
6995 if (DFII->second == 0)
6996 if (
Error Err = findFunctionInStream(
F, DFII))
7000 if (
Error Err = materializeMetadata())
7004 if (
Error JumpFailed = Stream.JumpToBit(DFII->second))
7007 if (
Error Err = parseFunctionBody(
F))
7009 F->setIsMaterializable(
false);
7013 if (SeenDebugIntrinsic && SeenDebugRecord)
7014 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
7020 if (
DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7021 F->setSubprogram(SP);
7024 if (!MDLoader->isStrippingTBAA()) {
7026 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7029 MDLoader->setStripTBAA(
true);
7036 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7037 if (MD->getOperand(0) !=
nullptr && isa<MDString>(MD->getOperand(0))) {
7038 MDString *MDS = cast<MDString>(MD->getOperand(0));
7043 unsigned ExpectedNumOperands = 0;
7045 ExpectedNumOperands = BI->getNumSuccessors();
7046 else if (
SwitchInst *SI = dyn_cast<SwitchInst>(&
I))
7047 ExpectedNumOperands =
SI->getNumSuccessors();
7048 else if (isa<CallInst>(&
I))
7049 ExpectedNumOperands = 1;
7052 else if (isa<SelectInst>(&
I))
7053 ExpectedNumOperands = 2;
7060 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7061 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7065 if (
auto *CI = dyn_cast<CallBase>(&
I)) {
7068 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7070 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7072 CI->getArgOperand(ArgNo)->getType(),
7073 CI->getParamAttributes(ArgNo)));
7076 if (
Function *OldFn = CI->getCalledFunction()) {
7077 auto It = UpgradedIntrinsics.find(OldFn);
7078 if (It != UpgradedIntrinsics.end())
7089 return materializeForwardReferencedFunctions();
7092Error BitcodeReader::materializeModule() {
7093 if (
Error Err = materializeMetadata())
7097 WillMaterializeAllForwardRefs =
true;
7102 if (
Error Err = materialize(&
F))
7108 if (LastFunctionBlockBit || NextUnreadBit)
7110 ? LastFunctionBlockBit
7116 if (!BasicBlockFwdRefs.
empty())
7117 return error(
"Never resolved function from blockaddress");
7123 for (
auto &
I : UpgradedIntrinsics) {
7124 for (
auto *U :
I.first->users()) {
7125 if (
CallInst *CI = dyn_cast<CallInst>(U))
7128 if (
I.first !=
I.second) {
7129 if (!
I.first->use_empty())
7130 I.first->replaceAllUsesWith(
I.second);
7131 I.first->eraseFromParent();
7134 UpgradedIntrinsics.clear();
7147std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7148 return IdentifiedStructTypes;
7151ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7154 : BitcodeReaderBase(
std::
move(Cursor), Strtab), TheIndex(TheIndex),
7155 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7157void ModuleSummaryIndexBitcodeReader::addThisModule() {
7162ModuleSummaryIndexBitcodeReader::getThisModule() {
7166template <
bool AllowNullValueInfo>
7167std::pair<ValueInfo, GlobalValue::GUID>
7168ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7169 auto VGI = ValueIdToValueInfoMap[ValueId];
7174 assert(AllowNullValueInfo || std::get<0>(VGI));
7178void ModuleSummaryIndexBitcodeReader::setValueGUID(
7181 std::string GlobalId =
7182 GlobalValue::getGlobalIdentifier(
ValueName, Linkage, SourceFileName);
7184 auto OriginalNameID = ValueGUID;
7188 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7194 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7203Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7212 if (!MaybeCurrentBit)
7230 switch (
Entry.Kind) {
7233 return error(
"Malformed block");
7236 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
7249 switch (MaybeRecord.
get()) {
7254 return error(
"Invalid record");
7255 unsigned ValueID =
Record[0];
7257 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7258 assert(VLI != ValueIdToLinkageMap.
end() &&
7259 "No linkage found for VST entry?");
7261 setValueGUID(ValueID,
ValueName, Linkage, SourceFileName);
7268 return error(
"Invalid record");
7269 unsigned ValueID =
Record[0];
7271 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7272 assert(VLI != ValueIdToLinkageMap.
end() &&
7273 "No linkage found for VST entry?");
7275 setValueGUID(ValueID,
ValueName, Linkage, SourceFileName);
7281 unsigned ValueID =
Record[0];
7285 ValueIdToValueInfoMap[ValueID] =
7296Error ModuleSummaryIndexBitcodeReader::parseModule() {
7302 unsigned ValueId = 0;
7311 switch (
Entry.Kind) {
7313 return error(
"Malformed block");
7320 if (
Error Err = Stream.SkipBlock())
7325 if (
Error Err = readBlockInfo())
7331 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7332 !SeenGlobalValSummary) &&
7333 "Expected early VST parse via VSTOffset record");
7334 if (
Error Err = Stream.SkipBlock())
7340 if (!SourceFileName.
empty())
7342 assert(!SeenValueSymbolTable &&
7343 "Already read VST when parsing summary block?");
7348 if (VSTOffset > 0) {
7349 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7351 SeenValueSymbolTable =
true;
7353 SeenGlobalValSummary =
true;
7354 if (
Error Err = parseEntireSummary(
Entry.ID))
7358 if (
Error Err = parseModuleStringTable())
7369 switch (MaybeBitCode.
get()) {
7373 if (
Error Err = parseVersionRecord(
Record).takeError())
7381 return error(
"Invalid record");
7389 auto &Hash = getThisModule()->second;
7391 for (
auto &Val :
Record) {
7392 assert(!(Val >> 32) &&
"Unexpected high bits set");
7400 return error(
"Invalid record");
7404 VSTOffset =
Record[0] - 1;
7415 std::tie(
Name, GVRecord) = readNameFromStrtab(
Record);
7416 if (GVRecord.
size() <= 3)
7417 return error(
"Invalid record");
7421 ValueIdToLinkageMap[ValueId++] =
Linkage;
7425 setValueGUID(ValueId++,
Name, Linkage, SourceFileName);
7440 Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7446 bool IsOldProfileFormat,
7447 bool HasProfile,
bool HasRelBF) {
7451 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7456 for (
unsigned I = 0, E =
Record.size();
I != E; ++
I) {
7458 bool HasTailCall =
false;
7461 if (IsOldProfileFormat) {
7465 }
else if (HasProfile)
7466 std::tie(Hotness, HasTailCall) =
7499 static_cast<size_t>(
Record[Slot + 1])};
7522 while (Slot <
Record.size())
7526std::vector<FunctionSummary::ParamAccess>
7528 auto ReadRange = [&]() {
7530 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7532 BitcodeReader::decodeSignRotatedValue(
Record.consume_front()));
7539 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7540 while (!
Record.empty()) {
7541 PendingParamAccesses.emplace_back();
7544 ParamAccess.
Use = ReadRange();
7546 for (
auto &Call : ParamAccess.
Calls) {
7549 std::get<0>(getValueInfoFromValueId(
Record.consume_front()));
7550 Call.Offsets = ReadRange();
7553 return PendingParamAccesses;
7556void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7564void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7570 static_cast<size_t>(
Record[Slot + 1])});
7573 while (Slot <
Record.size())
7574 parseTypeIdCompatibleVtableInfo(
Record, Slot, TypeId);
7583 if (RadixArray.empty()) {
7584 unsigned NumStackEntries =
Record[
I++];
7586 StackIdList.
reserve(NumStackEntries);
7587 for (
unsigned J = 0; J < NumStackEntries; J++) {
7593 unsigned RadixIndex =
Record[
I++];
7599 assert(RadixIndex < RadixArray.size());
7600 unsigned NumStackIds = RadixArray[RadixIndex++];
7601 StackIdList.
reserve(NumStackIds);
7602 while (NumStackIds--) {
7603 assert(RadixIndex < RadixArray.size());
7604 unsigned Elem = RadixArray[RadixIndex];
7605 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7606 RadixIndex = RadixIndex - Elem;
7607 assert(RadixIndex < RadixArray.size());
7608 Elem = RadixArray[RadixIndex];
7610 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7623 unsigned FirstWORef = Refs.
size() - WOCnt;
7624 unsigned RefNo = FirstWORef - ROCnt;
7625 for (; RefNo < FirstWORef; ++RefNo)
7626 Refs[RefNo].setReadOnly();
7627 for (; RefNo < Refs.
size(); ++RefNo)
7628 Refs[RefNo].setWriteOnly();
7633Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7634 if (
Error Err = Stream.EnterSubBlock(
ID))
7646 return error(
"Invalid Summary Block: record for version expected");
7651 return error(
"Invalid Summary Block: version expected");
7654 const bool IsOldProfileFormat =
Version == 1;
7656 return error(
"Invalid summary version " +
Twine(Version) +
7657 ". Version should be in the range [1-" +
7670 std::vector<GlobalValue::GUID> PendingTypeTests;
7671 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7672 PendingTypeCheckedLoadVCalls;
7673 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7674 PendingTypeCheckedLoadConstVCalls;
7675 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7677 std::vector<CallsiteInfo> PendingCallsites;
7678 std::vector<AllocInfo> PendingAllocs;
7679 std::vector<uint64_t> PendingContextIds;
7687 switch (
Entry.Kind) {
7690 return error(
"Malformed block");
7709 switch (
unsigned BitCode = MaybeBitCode.
get()) {
7719 if (Version >= 11) {
7724 ValueIdToValueInfoMap[ValueID] =
7740 unsigned ValueID =
Record[0];
7742 unsigned InstCount =
Record[2];
7744 unsigned NumRefs =
Record[3];
7745 unsigned NumRORefs = 0, NumWORefs = 0;
7746 int RefListStartIndex = 4;
7750 RefListStartIndex = 5;
7753 RefListStartIndex = 6;
7756 RefListStartIndex = 7;
7767 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7769 "Record size inconsistent with number of references");
7776 IsOldProfileFormat, HasProfile, HasRelBF);
7778 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7784 !IsPrevailing(VIAndOriginalGUID.first.getGUID())) {
7785 PendingCallsites.clear();
7786 PendingAllocs.clear();
7788 auto FS = std::make_unique<FunctionSummary>(
7790 std::move(Calls), std::move(PendingTypeTests),
7791 std::move(PendingTypeTestAssumeVCalls),
7792 std::move(PendingTypeCheckedLoadVCalls),
7793 std::move(PendingTypeTestAssumeConstVCalls),
7794 std::move(PendingTypeCheckedLoadConstVCalls),
7795 std::move(PendingParamAccesses), std::move(PendingCallsites),
7796 std::move(PendingAllocs));
7797 FS->setModulePath(getThisModule()->first());
7798 FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7807 unsigned ValueID =
Record[0];
7809 unsigned AliaseeID =
Record[2];
7811 auto AS = std::make_unique<AliasSummary>(Flags);
7817 AS->setModulePath(getThisModule()->first());
7819 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7821 if (!AliaseeInModule)
7822 return error(
"Alias expects aliasee summary to be parsed");
7823 AS->setAliasee(AliaseeVI, AliaseeInModule);
7825 auto GUID = getValueInfoFromValueId(ValueID);
7826 AS->setOriginalName(std::get<1>(GUID));
7832 unsigned ValueID =
Record[0];
7834 unsigned RefArrayStart = 2;
7847 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7848 FS->setModulePath(getThisModule()->first());
7849 auto GUID = getValueInfoFromValueId(ValueID);
7850 FS->setOriginalName(std::get<1>(GUID));
7858 unsigned ValueID =
Record[0];
7861 unsigned NumRefs =
Record[3];
7862 unsigned RefListStartIndex = 4;
7863 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7868 for (
unsigned I = VTableListStartIndex, E =
Record.size();
I != E; ++
I) {
7874 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7875 VS->setModulePath(getThisModule()->first());
7876 VS->setVTableFuncs(VTableFuncs);
7877 auto GUID = getValueInfoFromValueId(ValueID);
7878 VS->setOriginalName(std::get<1>(GUID));
7890 unsigned ValueID =
Record[0];
7893 unsigned InstCount =
Record[3];
7895 unsigned NumRefs =
Record[4];
7896 unsigned NumRORefs = 0, NumWORefs = 0;
7897 int RefListStartIndex = 5;
7901 RefListStartIndex = 6;
7902 size_t NumRefsIndex = 5;
7904 unsigned NumRORefsOffset = 1;
7905 RefListStartIndex = 7;
7908 RefListStartIndex = 8;
7910 RefListStartIndex = 9;
7912 NumRORefsOffset = 2;
7915 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
7917 NumRefs =
Record[NumRefsIndex];
7921 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7923 "Record size inconsistent with number of references");
7929 IsOldProfileFormat, HasProfile,
false);
7930 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7932 auto FS = std::make_unique<FunctionSummary>(
7934 std::move(Edges), std::move(PendingTypeTests),
7935 std::move(PendingTypeTestAssumeVCalls),
7936 std::move(PendingTypeCheckedLoadVCalls),
7937 std::move(PendingTypeTestAssumeConstVCalls),
7938 std::move(PendingTypeCheckedLoadConstVCalls),
7939 std::move(PendingParamAccesses), std::move(PendingCallsites),
7940 std::move(PendingAllocs));
7941 LastSeenSummary =
FS.get();
7942 LastSeenGUID =
VI.getGUID();
7943 FS->setModulePath(ModuleIdMap[ModuleId]);
7951 unsigned ValueID =
Record[0];
7954 unsigned AliaseeValueId =
Record[3];
7956 auto AS = std::make_unique<AliasSummary>(Flags);
7957 LastSeenSummary = AS.get();
7958 AS->setModulePath(ModuleIdMap[ModuleId]);
7960 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
7962 AS->setAliasee(AliaseeVI, AliaseeInModule);
7964 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7965 LastSeenGUID =
VI.getGUID();
7971 unsigned ValueID =
Record[0];
7974 unsigned RefArrayStart = 3;
7987 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7988 LastSeenSummary =
FS.get();
7989 FS->setModulePath(ModuleIdMap[ModuleId]);
7990 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7991 LastSeenGUID =
VI.getGUID();
7998 if (!LastSeenSummary)
7999 return error(
"Name attachment that does not follow a combined record");
8003 LastSeenSummary =
nullptr;
8008 assert(PendingTypeTests.empty());
8013 assert(PendingTypeTestAssumeVCalls.empty());
8014 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8015 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8019 assert(PendingTypeCheckedLoadVCalls.empty());
8020 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8021 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8025 PendingTypeTestAssumeConstVCalls.push_back(
8030 PendingTypeCheckedLoadConstVCalls.push_back(
8036 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8038 static_cast<size_t>(
Record[
I + 1]));
8044 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8046 static_cast<size_t>(
Record[
I + 1]));
8055 parseTypeIdCompatibleVtableSummaryRecord(
Record);
8063 PendingParamAccesses = parseParamAccesses(
Record);
8070 if (Version <= 11) {
8077 StackIds.reserve(
Record.size() / 2);
8078 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8079 StackIds.push_back(*R << 32 | *(R + 1));
8089 unsigned ValueID =
Record[0];
8092 assert(R < StackIds.size());
8095 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8096 PendingCallsites.push_back(
CallsiteInfo({
VI, std::move(StackIdList)}));
8101 auto RecordIter =
Record.begin();
8102 unsigned ValueID = *RecordIter++;
8103 unsigned NumStackIds = *RecordIter++;
8104 unsigned NumVersions = *RecordIter++;
8105 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8107 for (
unsigned J = 0; J < NumStackIds; J++) {
8108 assert(*RecordIter < StackIds.size());
8113 for (
unsigned J = 0; J < NumVersions; J++)
8116 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8117 PendingCallsites.push_back(
8118 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8126 PendingContextIds.reserve(
Record.size() / 2);
8127 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8128 PendingContextIds.push_back(*R << 32 | *(R + 1));
8134 std::vector<MIBInfo> MIBs;
8135 unsigned NumMIBs = 0;
8138 unsigned MIBsRead = 0;
8139 while ((Version >= 10 && MIBsRead++ < NumMIBs) ||
8140 (Version < 10 &&
I <
Record.size())) {
8143 auto StackIdList = parseAllocInfoContext(
Record,
I);
8150 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8152 assert(!PendingContextIds.empty() &&
8153 "Missing context ids for alloc sizes");
8154 unsigned ContextIdIndex = 0;
8160 while (MIBsRead++ < NumMIBs) {
8162 unsigned NumContextSizeInfoEntries =
Record[
I++];
8164 std::vector<ContextTotalSize> ContextSizes;
8165 ContextSizes.reserve(NumContextSizeInfoEntries);
8166 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8167 assert(ContextIdIndex < PendingContextIds.size());
8169 if (PendingContextIds[ContextIdIndex] == 0) {
8178 ContextSizes.push_back(
8179 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8181 AllContextSizes.push_back(std::move(ContextSizes));
8183 PendingContextIds.clear();
8185 PendingAllocs.push_back(
AllocInfo(std::move(MIBs)));
8186 if (!AllContextSizes.empty()) {
8187 assert(PendingAllocs.back().MIBs.size() == AllContextSizes.size());
8188 PendingAllocs.back().ContextSizeInfos = std::move(AllContextSizes);
8196 std::vector<MIBInfo> MIBs;
8197 unsigned NumMIBs =
Record[
I++];
8198 unsigned NumVersions =
Record[
I++];
8199 unsigned MIBsRead = 0;
8200 while (MIBsRead++ < NumMIBs) {
8205 StackIdList = parseAllocInfoContext(
Record,
I);
8210 for (
unsigned J = 0; J < NumVersions; J++)
8213 PendingAllocs.push_back(
AllocInfo(std::move(Versions), std::move(MIBs)));
8223Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8238 switch (
Entry.Kind) {
8241 return error(
"Malformed block");
8253 switch (MaybeRecord.
get()) {
8261 return error(
"Invalid record");
8263 LastSeenModule = TheIndex.
addModule(ModulePath);
8264 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8273 if (!LastSeenModule)
8274 return error(
"Invalid hash that does not follow a module path");
8276 for (
auto &Val :
Record) {
8277 assert(!(Val >> 32) &&
"Unexpected high bits set");
8278 LastSeenModule->
second[Pos++] = Val;
8281 LastSeenModule =
nullptr;
8294class BitcodeErrorCategoryType :
public std::error_category {
8295 const char *
name()
const noexcept
override {
8296 return "llvm.bitcode";
8299 std::string message(
int IE)
const override {
8302 case BitcodeError::CorruptedBitcode:
8303 return "Corrupted bitcode";
8312 static BitcodeErrorCategoryType ErrorCategory;
8313 return ErrorCategory;
8317 unsigned Block,
unsigned RecordID) {
8319 return std::move(Err);
8328 switch (Entry.Kind) {
8333 return error(
"Malformed block");
8337 return std::move(Err);
8347 if (MaybeRecord.
get() == RecordID)
8362 return FOrErr.takeError();
8363 return std::move(FOrErr->Mods);
8388 switch (Entry.Kind) {
8391 return error(
"Malformed block");
8394 uint64_t IdentificationBit = -1ull;
8398 return std::move(Err);
8404 Entry = MaybeEntry.
get();
8409 return error(
"Malformed block");
8415 return std::move(Err);
8434 if (!
I.Strtab.empty())
8441 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8442 F.StrtabForSymtab = *Strtab;
8458 if (
F.Symtab.empty())
8459 F.Symtab = *SymtabOrErr;
8464 return std::move(Err);
8469 return std::move(E);
8484BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8485 bool ShouldLazyLoadMetadata,
bool IsImporting,
8489 std::string ProducerIdentification;
8490 if (IdentificationBit != -1ull) {
8491 if (
Error JumpFailed = Stream.JumpToBit(IdentificationBit))
8492 return std::move(JumpFailed);
8495 return std::move(E);
8498 if (
Error JumpFailed = Stream.JumpToBit(ModuleBit))
8499 return std::move(JumpFailed);
8500 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8503 std::unique_ptr<Module>
M =
8504 std::make_unique<Module>(ModuleIdentifier, Context);
8505 M->setMaterializer(R);
8508 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8509 IsImporting, Callbacks))
8510 return std::move(Err);
8512 if (MaterializeAll) {
8514 if (
Error Err =
M->materializeAll())
8515 return std::move(Err);
8518 if (
Error Err =
R->materializeForwardReferencedFunctions())
8519 return std::move(Err);
8522 return std::move(M);
8528 return getModuleImpl(
Context,
false, ShouldLazyLoadMetadata, IsImporting,
8543 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8544 ModulePath, IsPrevailing);
8545 return R.parseModule();
8552 return std::move(JumpFailed);
8554 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8555 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8556 ModuleIdentifier, 0);
8558 if (
Error Err = R.parseModule())
8559 return std::move(Err);
8561 return std::move(Index);
8569 return std::move(Err);
8574 std::pair<bool, bool> Result = {
false,
false};
8576 return std::move(E);
8578 switch (Entry.Kind) {
8581 return error(
"Malformed block");
8596 switch (MaybeBitCode.
get()) {
8602 assert(Flags <= 0x2ff &&
"Unexpected bits in flag");
8604 bool EnableSplitLTOUnit = Flags & 0x8;
8605 bool UnifiedLTO = Flags & 0x200;
8606 Result = {EnableSplitLTOUnit, UnifiedLTO};
8619 return std::move(JumpFailed);
8622 return std::move(Err);
8627 return std::move(E);
8629 switch (Entry.Kind) {
8631 return error(
"Malformed block");
8642 return Flags.takeError();
8654 return Flags.takeError();
8663 return std::move(Err);
8670 return StreamFailed.takeError();
8680 if (MsOrErr->size() != 1)
8681 return error(
"Expected a single module");
8683 return (*MsOrErr)[0];
8688 bool ShouldLazyLoadMetadata,
bool IsImporting,
8694 return BM->getLazyModule(
Context, ShouldLazyLoadMetadata, IsImporting,
8699 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
8700 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
8702 IsImporting, Callbacks);
8704 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8710 return getModuleImpl(
Context,
true,
false,
false, Callbacks);
8722 return BM->parseModule(
Context, Callbacks);
8755 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8764 return BM->getSummary();
8772 return BM->getLTOInfo();
8777 bool IgnoreEmptyThinLTOIndexFile) {
8782 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isConstant(const MachineInstr &MI)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
Atomic ordering constants.
This file contains the simple types necessary to represent the attributes associated with functions a...
static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF, bool &HasTailCall)
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
static cl::opt< bool > PrintSummaryGUIDs("print-summary-global-ids", cl::init(false), cl::Hidden, cl::desc("Print the global id for each value when reading the module summary"))
static AtomicOrdering getDecodedOrdering(unsigned Val)
static std::pair< CalleeInfo::HotnessType, bool > getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)
static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags)
static std::optional< CodeModel::Model > getDecodedCodeModel(unsigned Val)
static void setSpecialRefs(SmallVectorImpl< ValueInfo > &Refs, unsigned ROCnt, unsigned WOCnt)
static bool getDecodedDSOLocal(unsigned Val)
static bool convertToString(ArrayRef< uint64_t > Record, unsigned Idx, StrTy &Result)
Convert a string from a record into an std::string, return true on failure.
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
static void stripTBAA(Module *M)
static Expected< std::pair< bool, bool > > getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream, unsigned ID, BitcodeLTOInfo <OInfo)
static int getDecodedUnaryOpcode(unsigned Val, Type *Ty)
static Expected< std::string > readTriple(BitstreamCursor &Stream)
static void parseWholeProgramDevirtResolutionByArg(ArrayRef< uint64_t > Record, size_t &Slot, WholeProgramDevirtResolution &Wpd)
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags)
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
static Expected< uint64_t > jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
static Expected< bool > hasObjCCategoryInModule(BitstreamCursor &Stream)
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags)
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs, uint64_t AttrIdx)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
static bool hasImplicitComdat(size_t Val)
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream)
static Expected< std::string > readIdentificationCode(BitstreamCursor &Stream)
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
static Expected< bool > hasObjCCategory(BitstreamCursor &Stream)
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
static void parseWholeProgramDevirtResolution(ArrayRef< uint64_t > Record, StringRef Strtab, size_t &Slot, TypeIdSummary &TypeId)
static void inferDSOLocal(GlobalValue *GV)
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V)
static Expected< BitstreamCursor > initStream(MemoryBufferRef Buffer)
static cl::opt< bool > ExpandConstantExprs("expand-constant-exprs", cl::Hidden, cl::desc("Expand constant expressions to instructions for testing purposes"))
static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind)
static Expected< StringRef > readBlobInRecord(BitstreamCursor &Stream, unsigned Block, unsigned RecordID)
static Expected< std::string > readIdentificationBlock(BitstreamCursor &Stream)
Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the "epoch" encoded in the bit...
static bool isConstExprSupported(const BitcodeConstant *BC)
static int getDecodedCastOpcode(unsigned Val)
static Expected< std::string > readModuleTriple(BitstreamCursor &Stream)
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static StringRef getOpcodeName(uint8_t Opcode, uint8_t OpcodeBase)
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Looks at all the uses of the given value Returns the Liveness deduced from the uses of this value Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses If the result is Live
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 bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
PowerPC Reduce CR logical Operation
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
static uint64_t decodeSignRotatedValue(uint64_t V)
Decode a signed value stored with the sign bit in the LSB for dense VBR encoding.
This file defines the SmallString class.
This file defines the SmallVector class.
Class for arbitrary precision integers.
an instruction to allocate memory on the stack
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.
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
bool empty() const
empty - Check if the array is empty.
An instruction that atomically checks whether a specified value is in a memory location,...
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)
an instruction that atomically reads a memory location, combines it with another value,...
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ USubCond
Subtract only if no unsigned overflow.
@ FMinimum
*p = minimum(old, v) minimum matches the behavior of llvm.minimum.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ FMaximum
*p = maximum(old, v) maximum matches the behavior of llvm.maximum.
@ UIncWrap
Increment one up to a maximum value.
@ Max
*p = old >signed v ? old : v
@ UMin
*p = old <unsigned v ? old : v
@ FMin
*p = minnum(old, v) minnum matches the behavior of llvm.minnum.
@ UMax
*p = old >unsigned v ? old : v
@ FMax
*p = maxnum(old, v) maxnum matches the behavior of llvm.maxnum.
@ UDecWrap
Decrement one until a minimum value or zero.
LLVM_ABI AttributeSet getFnAttrs() const
The function attributes are returned.
static LLVM_ABI AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
static LLVM_ABI Attribute getWithStructRetType(LLVMContext &Context, Type *Ty)
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
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.
static bool isConstantRangeAttrKind(AttrKind Kind)
static LLVM_ABI Attribute getWithInAllocaType(LLVMContext &Context, Type *Ty)
static bool isIntAttrKind(AttrKind Kind)
static bool isConstantRangeListAttrKind(AttrKind Kind)
static LLVM_ABI Attribute getWithByValType(LLVMContext &Context, Type *Ty)
static bool isEnumAttrKind(AttrKind Kind)
LLVM Basic Block Representation.
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 & back() const
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
Represents a module in a bitcode file.
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
LLVM_ABI Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
LLVM_ABI Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, std::function< bool(GlobalValue::GUID)> IsPrevailing=nullptr)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
LLVM_ABI Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
LLVM_ABI Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks={})
Read the bitcode module and prepare for lazy deserialization of function bodies.
Value * getValueFwdRef(unsigned Idx, Type *Ty, unsigned TyID, BasicBlock *ConstExprInsertBB)
void push_back(Value *V, unsigned TypeID)
void replaceValueWithoutRAUW(unsigned ValNo, Value *NewV)
Error assignValue(unsigned Idx, Value *V, unsigned TypeID)
void shrinkTo(unsigned N)
unsigned getTypeID(unsigned ValNo) const
This class maintains the abbreviations read from a block info block.
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.
void setBlockInfo(BitstreamBlockInfo *BI)
Set the block info to be used by this BitstreamCursor to interpret abbreviated records.
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
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.
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
Allocate memory in an ever growing pool, as if by bump-pointer.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
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)
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo createFromIntValue(uint32_t Data)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void emplace(Args &&...A)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
bool isFPPredicate() const
bool isIntPredicate() const
@ Largest
The linker will choose the largest COMDAT.
@ SameSize
The data referenced by the COMDAT must be the same size.
@ Any
The linker may choose any COMDAT.
@ NoDeduplicate
No deduplication is performed.
@ ExactMatch
The data referenced by the COMDAT must be the same.
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of array type with a float element type taken from argument ...
static LLVM_ABI Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of vector type with a float element type taken from argument...
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static LLVM_ABI bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
static LLVM_ABI bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
static LLVM_ABI bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
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)
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Subprogram description. Uses SubclassData1.
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
Records a position in IR for a source label (DILabel).
Record of a variable value-assignment, aka a non instruction representation of the dbg....
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
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.
This instruction compares its operands according to the predicate given to the constructor.
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)
An instruction for ordering other memory operations.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
This class represents a freeze function that returns random concrete value if an operand is either a ...
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
BasicBlockListType::iterator iterator
const BasicBlock & back() const
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags noUnsignedWrap()
static GEPNoWrapFlags noUnsignedSignedWrap()
virtual void setStripDebugInfo()=0
virtual Error materializeModule()=0
Make sure the entire Module has been completely read.
virtual Error materializeMetadata()=0
virtual Error materialize(GlobalValue *GV)=0
Make sure the given GlobalValue is fully read.
virtual std::vector< StructType * > getIdentifiedStructTypes() const =0
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
static LLVM_ABI GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
LLVM_ABI void setComdat(Comdat *C)
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Function and variable summary information to aid decisions and implementation of importing.
void setOriginalName(GlobalValue::GUID Name)
Initialize the original name hash in this summary.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isLocalLinkage(LinkageTypes Linkage)
void setUnnamedAddr(UnnamedAddr Val)
bool hasLocalLinkage() const
bool hasDefaultVisibility() const
void setDLLStorageClass(DLLStorageClassTypes C)
void setThreadLocalMode(ThreadLocalMode Val)
bool hasExternalWeakLinkage() const
DLLStorageClassTypes
Storage classes of global values for PE targets.
@ DLLExportStorageClass
Function to be accessible from DLL.
@ DLLImportStorageClass
Function to be imported from DLL.
void setDSOLocal(bool Local)
PointerType * getType() const
Global values are always pointers.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
@ DefaultVisibility
The GV is visible.
@ HiddenVisibility
The GV is hidden.
@ ProtectedVisibility
The GV is protected.
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.
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
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)
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.
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
The landingpad instruction holds all of the information necessary to generate correct exception handl...
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.
An instruction for reading from memory.
Tracking metadata reference owned by Metadata.
LLVM_ABI StringRef getString() const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
ValueT lookup(const KeyT &Key) const
size_t getBufferSize() const
StringRef getBufferIdentifier() const
const char * getBufferStart() const
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static MemoryEffectsBase readOnly()
Create MemoryEffectsBase that can read any memory.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access argument memory.
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible memory.
static MemoryEffectsBase errnoMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access errno memory.
static MemoryEffectsBase createFromIntValue(uint32_t Data)
Create MemoryEffectsBase from an encoded integer value (used by memory attribute).
static MemoryEffectsBase writeOnly()
Create MemoryEffectsBase that can write any memory.
static MemoryEffectsBase otherMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access other memory.
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
Create MemoryEffectsBase that can only access inaccessible or argument memory.
static MemoryEffectsBase none()
Create MemoryEffectsBase that cannot read or write any memory.
static MemoryEffectsBase unknown()
Create MemoryEffectsBase that can read and write any memory.
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.
ValueInfo getOrInsertValueInfo(GlobalValue::GUID GUID)
Return a ValueInfo for GUID.
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.
static constexpr uint64_t BitcodeSummaryVersion
CfiFunctionIndex & cfiFunctionDefs()
GlobalValueSummary * findSummaryInModule(ValueInfo VI, StringRef ModuleId) const
Find the summary for ValueInfo VI in module ModuleId, or nullptr if not found.
unsigned addOrGetStackIdIndex(uint64_t StackId)
ModuleInfo * getModule(StringRef ModPath)
Return module entry for module with the given ModPath.
void addOriginalName(GlobalValue::GUID ValueGUID, GlobalValue::GUID OrigGUID)
Add an original name for the value of the given GUID.
TypeIdCompatibleVtableInfo & getOrInsertTypeIdCompatibleVtableSummary(StringRef TypeId)
Return an existing or new TypeIdCompatibleVtableMap entry for TypeId.
A Module instance is used to store all the information related to an LLVM module.
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static ResumeInst * Create(Value *Exn, InsertPosition InsertBefore=nullptr)
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, Instruction *MDFrom=nullptr)
This instruction constructs a fixed permutation of two input vectors.
ArrayRef< int > getShuffleMask() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
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.
An instruction for storing to memory.
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
StringRef - Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
constexpr bool empty() const
empty - Check if the string is empty.
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Class to represent struct types.
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)
Verify that the TBAA Metadatas are valid.
LLVM_ABI bool visitTBAAMetadata(Instruction &I, const MDNode *MD)
Visit an instruction and return true if it is valid, return false if an invalid TBAA is attached.
@ 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,...
See the file comment for details on the usage of the TrailingObjects type.
const T * getTrailingObjects() const
Returns a pointer to the trailing object array of the given type (which must be one of those specifie...
TrailingObjects()=default
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.
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
static LLVM_ABI Type * getFP128Ty(LLVMContext &C)
bool isVectorTy() const
True if this is an instance of VectorType.
static LLVM_ABI Type * getPPC_FP128Ty(LLVMContext &C)
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
bool isArrayTy() const
True if this is an instance of ArrayType.
static LLVM_ABI Type * getLabelTy(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.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Type * getArrayElementType() const
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
static LLVM_ABI Type * getHalfTy(LLVMContext &C)
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
TypeID
Definitions of all of the base types for the Type system.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
static LLVM_ABI Type * getX86_AMXTy(LLVMContext &C)
static LLVM_ABI Type * getBFloatTy(LLVMContext &C)
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
bool isStructTy() const
True if this is an instance of StructType.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
static LLVM_ABI Type * getX86_FP80Ty(LLVMContext &C)
bool isFunctionTy() const
True if this is an instance of FunctionType.
bool isIntegerTy() const
True if this is an instance of IntegerType.
LLVM_ABI Type * getStructElementType(unsigned N) const
static LLVM_ABI Type * getMetadataTy(LLVMContext &C)
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
bool isVoidTy() const
Return true if this is 'void'.
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
static LLVM_ABI Type * getTokenTy(LLVMContext &C)
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
bool isMetadataTy() const
Return true if this is 'metadata'.
static LLVM_ABI UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
LLVM Value Representation.
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.
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
Value & operator=(const Value &)=delete
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 TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
LLVM_ABI AttributeMask typeIncompatible(Type *Ty, AttributeSet AS, AttributeSafetyKind ASK=ASK_ALL)
Which attributes cannot be applied to a type.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ MaxID
The highest possible ID. Must be some 2^k - 1.
@ X86_INTR
x86 hardware interrupt context.
@ C
The default llvm calling convention, compatible with C.
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
LLVM_ABI AttributeList getAttributes(LLVMContext &C, ID id, FunctionType *FT)
Return the attributes for an intrinsic.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
@ System
Synchronized with respect to all concurrently executing threads.
@ TYPE_CODE_OPAQUE_POINTER
@ FS_CONTEXT_RADIX_TREE_ARRAY
@ FS_COMBINED_GLOBALVAR_INIT_REFS
@ FS_TYPE_CHECKED_LOAD_VCALLS
@ FS_COMBINED_ORIGINAL_NAME
@ FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_CONST_VCALL
@ FS_PERMODULE_GLOBALVAR_INIT_REFS
@ FS_TYPE_TEST_ASSUME_VCALLS
@ FS_COMBINED_ALLOC_INFO_NO_CONTEXT
@ FS_COMBINED_CALLSITE_INFO
@ FS_PERMODULE_CALLSITE_INFO
@ FS_PERMODULE_ALLOC_INFO
@ FS_TYPE_CHECKED_LOAD_CONST_VCALL
@ IDENTIFICATION_CODE_EPOCH
@ IDENTIFICATION_CODE_STRING
@ CST_CODE_CE_INBOUNDS_GEP
@ CST_CODE_INLINEASM_OLD3
@ CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD
@ CST_CODE_DSO_LOCAL_EQUIVALENT
@ CST_CODE_INLINEASM_OLD2
@ CST_CODE_CE_GEP_WITH_INRANGE
@ VST_CODE_COMBINED_ENTRY
@ COMDAT_SELECTION_KIND_LARGEST
@ COMDAT_SELECTION_KIND_ANY
@ COMDAT_SELECTION_KIND_SAME_SIZE
@ COMDAT_SELECTION_KIND_EXACT_MATCH
@ COMDAT_SELECTION_KIND_NO_DUPLICATES
@ ATTR_KIND_STACK_PROTECT
@ ATTR_KIND_STACK_PROTECT_STRONG
@ ATTR_KIND_SANITIZE_MEMORY
@ ATTR_KIND_OPTIMIZE_FOR_SIZE
@ ATTR_KIND_INACCESSIBLEMEM_ONLY
@ ATTR_KIND_FNRETTHUNK_EXTERN
@ ATTR_KIND_NO_DIVERGENCE_SOURCE
@ ATTR_KIND_SANITIZE_ADDRESS
@ ATTR_KIND_NO_IMPLICIT_FLOAT
@ ATTR_KIND_DEAD_ON_UNWIND
@ ATTR_KIND_STACK_ALIGNMENT
@ ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY
@ ATTR_KIND_STACK_PROTECT_REQ
@ ATTR_KIND_NULL_POINTER_IS_VALID
@ ATTR_KIND_SANITIZE_HWADDRESS
@ ATTR_KIND_RETURNS_TWICE
@ ATTR_KIND_SHADOWCALLSTACK
@ ATTR_KIND_OPT_FOR_FUZZING
@ ATTR_KIND_SANITIZE_NUMERICAL_STABILITY
@ ATTR_KIND_ALLOCATED_POINTER
@ ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION
@ ATTR_KIND_CORO_ELIDE_SAFE
@ ATTR_KIND_NON_LAZY_BIND
@ ATTR_KIND_DEREFERENCEABLE
@ ATTR_KIND_OPTIMIZE_NONE
@ ATTR_KIND_DEREFERENCEABLE_OR_NULL
@ ATTR_KIND_SANITIZE_REALTIME
@ ATTR_KIND_SPECULATIVE_LOAD_HARDENING
@ ATTR_KIND_ALWAYS_INLINE
@ ATTR_KIND_SANITIZE_TYPE
@ ATTR_KIND_PRESPLIT_COROUTINE
@ ATTR_KIND_NO_SANITIZE_COVERAGE
@ ATTR_KIND_DEAD_ON_RETURN
@ ATTR_KIND_SANITIZE_REALTIME_BLOCKING
@ ATTR_KIND_NO_SANITIZE_BOUNDS
@ ATTR_KIND_SANITIZE_MEMTAG
@ ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE
@ ATTR_KIND_SANITIZE_THREAD
@ ATTR_KIND_OPTIMIZE_FOR_DEBUGGING
@ SYNC_SCOPE_NAMES_BLOCK_ID
@ PARAMATTR_GROUP_BLOCK_ID
@ IDENTIFICATION_BLOCK_ID
@ GLOBALVAL_SUMMARY_BLOCK_ID
@ FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID
@ OPERAND_BUNDLE_TAGS_BLOCK_ID
@ BLOCKINFO_BLOCK_ID
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
@ MODULE_CODE_SOURCE_FILENAME
@ MODULE_CODE_SECTIONNAME
@ FUNC_CODE_INST_ATOMICRMW_OLD
@ FUNC_CODE_INST_CATCHRET
@ FUNC_CODE_INST_LANDINGPAD
@ FUNC_CODE_INST_EXTRACTVAL
@ FUNC_CODE_INST_CATCHPAD
@ FUNC_CODE_INST_CATCHSWITCH
@ FUNC_CODE_INST_INBOUNDS_GEP_OLD
@ FUNC_CODE_INST_STOREATOMIC_OLD
@ FUNC_CODE_INST_CLEANUPRET
@ FUNC_CODE_INST_LANDINGPAD_OLD
@ FUNC_CODE_DEBUG_RECORD_VALUE
@ FUNC_CODE_INST_LOADATOMIC
@ FUNC_CODE_DEBUG_RECORD_ASSIGN
@ FUNC_CODE_INST_STOREATOMIC
@ FUNC_CODE_INST_ATOMICRMW
@ FUNC_CODE_DEBUG_LOC_AGAIN
@ FUNC_CODE_INST_EXTRACTELT
@ FUNC_CODE_INST_INDIRECTBR
@ FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE
@ FUNC_CODE_INST_INSERTVAL
@ FUNC_CODE_DECLAREBLOCKS
@ FUNC_CODE_DEBUG_RECORD_LABEL
@ FUNC_CODE_INST_INSERTELT
@ FUNC_CODE_BLOCKADDR_USERS
@ FUNC_CODE_INST_CLEANUPPAD
@ FUNC_CODE_INST_SHUFFLEVEC
@ FUNC_CODE_INST_STORE_OLD
@ FUNC_CODE_INST_UNREACHABLE
@ FUNC_CODE_INST_CMPXCHG_OLD
@ FUNC_CODE_DEBUG_RECORD_DECLARE
@ FUNC_CODE_OPERAND_BUNDLE
@ PARAMATTR_CODE_ENTRY_OLD
@ PARAMATTR_GRP_CODE_ENTRY
initializer< Ty > init(const Ty &Val)
Linkage
Describes symbol linkage. This can be used to resolve definition clashes.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
NodeAddr< FuncNode * > Func
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...
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)
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...
LLVM_ABI bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
auto uninitialized_copy(R &&Src, IterTy Dst)
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
LLVM_ABI void UpgradeOperandBundles(std::vector< OperandBundleDef > &OperandBundles)
Upgrade operand bundles (without knowing about their user instruction).
std::vector< VirtFuncOffset > VTableFuncList
List of functions referenced by a particular vtable definition.
LLVM_ABI Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
StringMapEntry< Value * > ValueName
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.
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.
LLVM_ABI GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
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
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.
LLVM_ABI Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
std::vector< TypeIdOffsetVtableInfo > TypeIdCompatibleVtableInfo
List of vtable definitions decorated by a particular type identifier, and their corresponding offsets...
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.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Summary of memprof metadata on allocations.
Basic information extracted from a bitcode module to be used for LTO.
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 unsigned RelBlockFreqBits
The value stored in RelBlockFreq has to be interpreted as the digits of a scaled number with a scale ...
Summary of memprof callsite metadata.
Flags specific to function summaries.
Describes the uses of a parameter by the function.
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.
static constexpr uint32_t RangeWidth
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
static LLVM_ABI const char * BranchWeights
Summary of a single MIB in a memprof metadata on allocations.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
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.
A MapVector that performs no allocations if smaller than a certain size.
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