24#include "llvm/Config/llvm-config.h"
54#include "llvm/IR/IntrinsicsAArch64.h"
55#include "llvm/IR/IntrinsicsARM.h"
88#include <system_error>
98 "Print the global id for each value when reading the module summary"));
103 "Expand constant expressions to instructions for testing purposes"));
110 "load-bitcode-into-experimental-debuginfo-iterators",
cl::Hidden,
111 cl::desc(
"Load bitcode directly into the new debug info format (regardless "
112 "of input format)"));
121 SWITCH_INST_MAGIC = 0x4B5
127 return make_error<StringError>(
134 "file too small to contain bitcode header");
135 for (
unsigned C : {
'B',
'C'})
139 "file doesn't start with bitcode header");
141 return Res.takeError();
142 for (
unsigned C : {0x0, 0xC, 0xE, 0xD})
146 "file doesn't start with bitcode header");
148 return Res.takeError();
153 const unsigned char *BufPtr = (
const unsigned char *)Buffer.
getBufferStart();
154 const unsigned char *BufEnd = BufPtr + Buffer.
getBufferSize();
157 return error(
"Invalid bitcode signature");
163 return error(
"Invalid bitcode wrapper header");
167 return std::move(Err);
169 return std::move(Stream);
173template <
typename StrTy>
186 if (
F.isMaterializable())
189 I.setMetadata(LLVMContext::MD_tbaa,
nullptr);
197 return std::move(Err);
202 std::string ProducerIdentification;
209 switch (Entry.Kind) {
212 return error(
"Malformed block");
214 return ProducerIdentification;
225 switch (MaybeBitCode.
get()) {
227 return error(
"Invalid value");
235 Twine(
"Incompatible epoch: Bitcode '") +
Twine(epoch) +
254 switch (Entry.Kind) {
257 return error(
"Malformed block");
265 return std::move(Err);
277 return std::move(Err);
288 switch (Entry.Kind) {
291 return error(
"Malformed block");
303 switch (MaybeRecord.
get()) {
309 return error(
"Invalid section name record");
311 if (S.find(
"__DATA,__objc_catlist") != std::string::npos ||
312 S.find(
"__OBJC,__category") != std::string::npos ||
313 S.find(
"__TEXT,__swift") != std::string::npos)
331 switch (Entry.Kind) {
333 return error(
"Malformed block");
343 return std::move(Err);
356 return std::move(Err);
369 switch (Entry.Kind) {
372 return error(
"Malformed block");
384 switch (MaybeRecord.
get()) {
389 return error(
"Invalid triple record");
408 switch (Entry.Kind) {
410 return error(
"Malformed block");
420 return std::move(Err);
427 return Skipped.takeError();
434class BitcodeReaderBase {
437 : Stream(
std::
move(Stream)), Strtab(Strtab) {
447 bool UseStrtab =
false;
454 std::pair<StringRef, ArrayRef<uint64_t>>
457 Error readBlockInfo();
460 std::string ProducerIdentification;
467Error BitcodeReaderBase::error(
const Twine &Message) {
468 std::string FullMsg = Message.
str();
469 if (!ProducerIdentification.empty())
470 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
471 LLVM_VERSION_STRING
"')";
472 return ::error(FullMsg);
478 return error(
"Invalid version record");
479 unsigned ModuleVersion =
Record[0];
480 if (ModuleVersion > 2)
481 return error(
"Invalid value");
482 UseStrtab = ModuleVersion >= 2;
483 return ModuleVersion;
486std::pair<StringRef, ArrayRef<uint64_t>>
504class BitcodeConstant final :
public Value,
509 static constexpr uint8_t SubclassID = 255;
517 static constexpr uint8_t ConstantStructOpcode = 255;
518 static constexpr uint8_t ConstantArrayOpcode = 254;
519 static constexpr uint8_t ConstantVectorOpcode = 253;
520 static constexpr uint8_t NoCFIOpcode = 252;
521 static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
522 static constexpr uint8_t BlockAddressOpcode = 250;
523 static constexpr uint8_t ConstantPtrAuthOpcode = 249;
524 static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
531 unsigned BlockAddressBB = 0;
532 Type *SrcElemTy =
nullptr;
533 std::optional<ConstantRange> InRange;
536 std::optional<ConstantRange> InRange = std::nullopt)
537 : Opcode(Opcode),
Flags(
Flags), SrcElemTy(SrcElemTy),
541 : Opcode(Opcode),
Flags(
Flags), BlockAddressBB(BlockAddressBB) {}
546 unsigned NumOperands;
547 unsigned BlockAddressBB;
549 std::optional<ConstantRange>
InRange;
554 NumOperands(OpIDs.
size()), BlockAddressBB(
Info.BlockAddressBB),
555 SrcElemTy(
Info.SrcElemTy), InRange(
Info.InRange) {
556 std::uninitialized_copy(OpIDs.
begin(), OpIDs.
end(),
557 getTrailingObjects<unsigned>());
560 BitcodeConstant &
operator=(
const BitcodeConstant &) =
delete;
564 const ExtraInfo &Info,
566 void *Mem =
A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.
size()),
567 alignof(BitcodeConstant));
568 return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
571 static bool classof(
const Value *V) {
return V->getValueID() == SubclassID; }
574 return ArrayRef(getTrailingObjects<unsigned>(), NumOperands);
577 std::optional<ConstantRange> getInRange()
const {
578 assert(Opcode == Instruction::GetElementPtr);
587class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
589 Module *TheModule =
nullptr;
594 bool SeenValueSymbolTable =
false;
597 std::vector<std::string> SectionTable;
598 std::vector<std::string> GCTable;
600 std::vector<Type *> TypeList;
618 std::optional<MetadataLoader> MDLoader;
619 std::vector<Comdat *> ComdatList;
623 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
624 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
626 struct FunctionOperandInfo {
628 unsigned PersonalityFn;
632 std::vector<FunctionOperandInfo> FunctionOperands;
636 std::vector<AttributeList> MAttributes;
639 std::map<unsigned, AttributeList> MAttributeGroups;
643 std::vector<BasicBlock*> FunctionBBs;
647 std::vector<Function*> FunctionsWithBodies;
652 UpdatedIntrinsicMap UpgradedIntrinsics;
657 bool SeenFirstFunctionBody =
false;
666 std::vector<uint64_t> DeferredMetadataInfo;
672 std::deque<Function *> BasicBlockFwdRefQueue;
679 std::vector<Function *> BackwardRefFunctions;
687 bool UseRelativeIDs =
false;
691 bool WillMaterializeAllForwardRefs =
false;
695 bool SeenDebugIntrinsic =
false;
696 bool SeenDebugRecord =
false;
701 std::vector<std::string> BundleTags;
704 std::optional<ValueTypeCallbackTy> ValueTypeCallback;
710 Error materializeForwardReferencedFunctions();
718 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
729 std::vector<StructType *> IdentifiedStructTypes;
733 static constexpr unsigned InvalidTypeID = ~0
u;
735 Type *getTypeByID(
unsigned ID);
736 Type *getPtrElementTypeByID(
unsigned ID);
737 unsigned getContainedTypeID(
unsigned ID,
unsigned Idx = 0);
744 Value *getFnValueByID(
unsigned ID,
Type *Ty,
unsigned TyID,
752 return MDLoader->getMetadataFwdRefOrLoad(
ID);
756 if (
ID >= FunctionBBs.size())
return nullptr;
757 return FunctionBBs[
ID];
761 if (i-1 < MAttributes.size())
762 return MAttributes[i-1];
770 unsigned InstNum,
Value *&ResVal,
unsigned &
TypeID,
772 if (Slot ==
Record.size())
return true;
776 ValNo = InstNum - ValNo;
777 if (ValNo < InstNum) {
781 ResVal = getFnValueByID(ValNo,
nullptr,
TypeID, ConstExprInsertBB);
783 "Incorrect type ID stored for value");
784 return ResVal ==
nullptr;
786 if (Slot ==
Record.size())
790 ResVal = getFnValueByID(ValNo, getTypeByID(
TypeID),
TypeID,
792 return ResVal ==
nullptr;
796 unsigned &Slot,
unsigned InstNum,
Value *&ResVal,
798 if (Slot ==
Record.size())
803 return getValueTypePair(
Record, --Slot, InstNum, ResVal, TypeId,
806 if (Slot ==
Record.size())
817 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
819 if (getValue(
Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
828 unsigned InstNum,
Type *Ty,
unsigned TyID,
Value *&ResVal,
830 ResVal = getValue(
Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
831 return ResVal ==
nullptr;
837 unsigned InstNum,
Type *Ty,
unsigned TyID,
839 if (Slot ==
Record.size())
return nullptr;
843 ValNo = InstNum - ValNo;
844 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
849 unsigned InstNum,
Type *Ty,
unsigned TyID,
851 if (Slot ==
Record.size())
return nullptr;
855 ValNo = InstNum - ValNo;
856 return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
862 if (
Record.size() - OpNum < 2)
863 return error(
"Too few records for range");
865 unsigned LowerActiveWords =
Record[OpNum];
866 unsigned UpperActiveWords =
Record[OpNum++] >> 32;
867 if (
Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
868 return error(
"Too few records for range");
871 OpNum += LowerActiveWords;
874 OpNum += UpperActiveWords;
877 int64_t Start = BitcodeReader::decodeSignRotatedValue(
Record[OpNum++]);
878 int64_t
End = BitcodeReader::decodeSignRotatedValue(
Record[OpNum++]);
886 if (
Record.size() - OpNum < 1)
887 return error(
"Too few records for range");
908 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
911 Error parseAttributeBlock();
912 Error parseAttributeGroupBlock();
913 Error parseTypeTable();
914 Error parseTypeTableBody();
915 Error parseOperandBundleTags();
916 Error parseSyncScopeNames();
919 unsigned NameIndex,
Triple &TT);
920 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
Function *
F,
923 Error parseGlobalValueSymbolTable();
924 Error parseConstants();
925 Error rememberAndSkipFunctionBodies();
926 Error rememberAndSkipFunctionBody();
928 Error rememberAndSkipMetadata();
931 Error globalCleanup();
932 Error resolveGlobalAndIndirectSymbolInits();
933 Error parseUseLists();
934 Error findFunctionInStream(
943class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
949 bool SeenGlobalValSummary =
false;
952 bool SeenValueSymbolTable =
false;
967 ValueIdToValueInfoMap;
976 std::string SourceFileName;
988 std::vector<uint64_t> StackIds;
992 std::vector<uint64_t> RadixArray;
995 ModuleSummaryIndexBitcodeReader(
1006 Error parseValueSymbolTable(
1012 bool HasProfile,
bool HasRelBF);
1013 Error parseEntireSummary(
unsigned ID);
1014 Error parseModuleStringTable();
1018 std::vector<FunctionSummary::ParamAccess>
1023 template <
bool AllowNullValueInfo = false>
1024 std::pair<ValueInfo, GlobalValue::GUID>
1025 getValueInfoFromValueId(
unsigned ValueId);
1027 void addThisModule();
1043 return std::error_code();
1049 : BitcodeReaderBase(
std::
move(Stream), Strtab), Context(Context),
1050 ValueList(this->Stream.SizeInBytes(),
1052 return materializeValue(
ValID, InsertBB);
1054 this->ProducerIdentification = std::string(ProducerIdentification);
1057Error BitcodeReader::materializeForwardReferencedFunctions() {
1058 if (WillMaterializeAllForwardRefs)
1062 WillMaterializeAllForwardRefs =
true;
1064 while (!BasicBlockFwdRefQueue.empty()) {
1065 Function *
F = BasicBlockFwdRefQueue.front();
1066 BasicBlockFwdRefQueue.pop_front();
1067 assert(
F &&
"Expected valid function");
1068 if (!BasicBlockFwdRefs.
count(
F))
1076 if (!
F->isMaterializable())
1077 return error(
"Never resolved function from blockaddress");
1080 if (
Error Err = materialize(
F))
1083 assert(BasicBlockFwdRefs.
empty() &&
"Function missing from queue");
1085 for (
Function *
F : BackwardRefFunctions)
1086 if (
Error Err = materialize(
F))
1088 BackwardRefFunctions.clear();
1091 WillMaterializeAllForwardRefs =
false;
1155 Flags.ReadNone = RawFlags & 0x1;
1156 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1157 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1158 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1159 Flags.NoInline = (RawFlags >> 4) & 0x1;
1160 Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1161 Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1162 Flags.MayThrow = (RawFlags >> 7) & 0x1;
1163 Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1164 Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1180 RawFlags = RawFlags >> 4;
1181 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1185 bool Live = (RawFlags & 0x2) || Version < 3;
1186 bool Local = (RawFlags & 0x4);
1187 bool AutoHide = (RawFlags & 0x8);
1196 (RawFlags & 0x1) ?
true :
false, (RawFlags & 0x2) ?
true :
false,
1197 (RawFlags & 0x4) ?
true :
false,
1201static std::pair<CalleeInfo::HotnessType, bool>
1205 bool HasTailCall = (RawFlags & 0x8);
1206 return {Hotness, HasTailCall};
1210 bool &HasTailCall) {
1211 static constexpr uint64_t RelBlockFreqMask =
1213 RelBF = RawFlags & RelBlockFreqMask;
1239 case 0:
return false;
1240 case 1:
return true;
1263 case 0:
return GlobalVariable::NotThreadLocal;
1265 case 1:
return GlobalVariable::GeneralDynamicTLSModel;
1266 case 2:
return GlobalVariable::LocalDynamicTLSModel;
1267 case 3:
return GlobalVariable::InitialExecTLSModel;
1268 case 4:
return GlobalVariable::LocalExecTLSModel;
1275 case 0:
return GlobalVariable::UnnamedAddr::None;
1276 case 1:
return GlobalVariable::UnnamedAddr::Global;
1277 case 2:
return GlobalVariable::UnnamedAddr::Local;
1310 return IsFP ? Instruction::FNeg : -1;
1324 return IsFP ? Instruction::FAdd : Instruction::Add;
1326 return IsFP ? Instruction::FSub : Instruction::Sub;
1328 return IsFP ? Instruction::FMul : Instruction::Mul;
1330 return IsFP ? -1 : Instruction::UDiv;
1332 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1334 return IsFP ? -1 : Instruction::URem;
1336 return IsFP ? Instruction::FRem : Instruction::SRem;
1338 return IsFP ? -1 : Instruction::Shl;
1340 return IsFP ? -1 : Instruction::LShr;
1342 return IsFP ? -1 : Instruction::AShr;
1344 return IsFP ? -1 : Instruction::And;
1346 return IsFP ? -1 : Instruction::Or;
1348 return IsFP ? -1 : Instruction::Xor;
1441Type *BitcodeReader::getTypeByID(
unsigned ID) {
1443 if (
ID >= TypeList.size())
1446 if (
Type *Ty = TypeList[
ID])
1451 return TypeList[
ID] = createIdentifiedStructType(Context);
1454unsigned BitcodeReader::getContainedTypeID(
unsigned ID,
unsigned Idx) {
1455 auto It = ContainedTypeIDs.
find(
ID);
1456 if (It == ContainedTypeIDs.
end())
1457 return InvalidTypeID;
1459 if (
Idx >= It->second.size())
1460 return InvalidTypeID;
1462 return It->second[
Idx];
1465Type *BitcodeReader::getPtrElementTypeByID(
unsigned ID) {
1466 if (
ID >= TypeList.size())
1473 return getTypeByID(getContainedTypeID(
ID, 0));
1476unsigned BitcodeReader::getVirtualTypeID(
Type *Ty,
1478 unsigned ChildTypeID = ChildTypeIDs.
empty() ? InvalidTypeID : ChildTypeIDs[0];
1479 auto CacheKey = std::make_pair(Ty, ChildTypeID);
1480 auto It = VirtualTypeIDs.
find(CacheKey);
1481 if (It != VirtualTypeIDs.
end()) {
1487 ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1488 "Incorrect cached contained type IDs");
1492 unsigned TypeID = TypeList.size();
1493 TypeList.push_back(Ty);
1494 if (!ChildTypeIDs.
empty())
1515 if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1529 if (Opcode == Instruction::GetElementPtr)
1533 case Instruction::FNeg:
1534 case Instruction::Select:
1535 case Instruction::ICmp:
1536 case Instruction::FCmp:
1546 if (StartValID < ValueList.
size() && ValueList[StartValID] &&
1547 !isa<BitcodeConstant>(ValueList[StartValID]))
1548 return ValueList[StartValID];
1553 while (!Worklist.
empty()) {
1562 return error(
"Invalid value ID");
1565 auto *BC = dyn_cast<BitcodeConstant>(V);
1575 for (
unsigned OpID :
reverse(BC->getOperandIDs())) {
1576 auto It = MaterializedValues.
find(OpID);
1577 if (It != MaterializedValues.
end())
1585 if (Ops.
size() != BC->getOperandIDs().size())
1587 std::reverse(Ops.
begin(), Ops.
end());
1591 if (
auto *
C = dyn_cast<Constant>(
Op))
1604 switch (BC->Opcode) {
1605 case BitcodeConstant::ConstantPtrAuthOpcode: {
1606 auto *
Key = dyn_cast<ConstantInt>(ConstOps[1]);
1608 return error(
"ptrauth key operand must be ConstantInt");
1610 auto *Disc = dyn_cast<ConstantInt>(ConstOps[2]);
1612 return error(
"ptrauth disc operand must be ConstantInt");
1617 case BitcodeConstant::NoCFIOpcode: {
1618 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1620 return error(
"no_cfi operand must be GlobalValue");
1624 case BitcodeConstant::DSOLocalEquivalentOpcode: {
1625 auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1627 return error(
"dso_local operand must be GlobalValue");
1631 case BitcodeConstant::BlockAddressOpcode: {
1632 Function *Fn = dyn_cast<Function>(ConstOps[0]);
1634 return error(
"blockaddress operand must be a function");
1639 unsigned BBID = BC->BlockAddressBB;
1642 return error(
"Invalid ID");
1645 for (
size_t I = 0, E = BBID;
I != E; ++
I) {
1647 return error(
"Invalid ID");
1654 auto &FwdBBs = BasicBlockFwdRefs[Fn];
1656 BasicBlockFwdRefQueue.push_back(Fn);
1657 if (FwdBBs.size() < BBID + 1)
1658 FwdBBs.resize(BBID + 1);
1666 case BitcodeConstant::ConstantStructOpcode: {
1667 auto *
ST = cast<StructType>(BC->getType());
1668 if (
ST->getNumElements() != ConstOps.
size())
1669 return error(
"Invalid number of elements in struct initializer");
1671 for (
const auto [Ty,
Op] :
zip(
ST->elements(), ConstOps))
1672 if (
Op->getType() != Ty)
1673 return error(
"Incorrect type in struct initializer");
1678 case BitcodeConstant::ConstantArrayOpcode: {
1679 auto *AT = cast<ArrayType>(BC->getType());
1680 if (AT->getNumElements() != ConstOps.
size())
1681 return error(
"Invalid number of elements in array initializer");
1684 if (
Op->getType() != AT->getElementType())
1685 return error(
"Incorrect type in array initializer");
1690 case BitcodeConstant::ConstantVectorOpcode: {
1691 auto *VT = cast<FixedVectorType>(BC->getType());
1692 if (VT->getNumElements() != ConstOps.size())
1693 return error(
"Invalid number of elements in vector initializer");
1696 if (
Op->getType() != VT->getElementType())
1697 return error(
"Incorrect type in vector initializer");
1702 case Instruction::GetElementPtr:
1704 BC->SrcElemTy, ConstOps[0],
ArrayRef(ConstOps).drop_front(),
1707 case Instruction::ExtractElement:
1710 case Instruction::InsertElement:
1714 case Instruction::ShuffleVector: {
1733 return error(
Twine(
"Value referenced by initializer is an unsupported "
1734 "constant expression of type ") +
1735 BC->getOpcodeName());
1741 BC->getType(),
"constexpr", InsertBB);
1744 "constexpr", InsertBB);
1747 Ops[1],
"constexpr", InsertBB);
1748 if (isa<OverflowingBinaryOperator>(
I)) {
1750 I->setHasNoSignedWrap();
1752 I->setHasNoUnsignedWrap();
1754 if (isa<PossiblyExactOperator>(
I) &&
1758 switch (BC->Opcode) {
1759 case BitcodeConstant::ConstantVectorOpcode: {
1763 Value *
Idx = ConstantInt::get(IdxTy, Pair.index());
1767 I = cast<Instruction>(V);
1770 case BitcodeConstant::ConstantStructOpcode:
1771 case BitcodeConstant::ConstantArrayOpcode: {
1775 "constexpr.ins", InsertBB);
1776 I = cast<Instruction>(V);
1779 case Instruction::ICmp:
1780 case Instruction::FCmp:
1783 "constexpr", InsertBB);
1785 case Instruction::GetElementPtr:
1787 ArrayRef(Ops).drop_front(),
"constexpr",
1791 case Instruction::Select:
1794 case Instruction::ExtractElement:
1797 case Instruction::InsertElement:
1801 case Instruction::ShuffleVector:
1814 return MaterializedValues[StartValID];
1823 return cast<Constant>(MaybeV.
get());
1829 IdentifiedStructTypes.push_back(Ret);
1835 IdentifiedStructTypes.push_back(Ret);
1851 case Attribute::ZExt:
return 1 << 0;
1852 case Attribute::SExt:
return 1 << 1;
1853 case Attribute::NoReturn:
return 1 << 2;
1854 case Attribute::InReg:
return 1 << 3;
1855 case Attribute::StructRet:
return 1 << 4;
1856 case Attribute::NoUnwind:
return 1 << 5;
1857 case Attribute::NoAlias:
return 1 << 6;
1858 case Attribute::ByVal:
return 1 << 7;
1859 case Attribute::Nest:
return 1 << 8;
1860 case Attribute::ReadNone:
return 1 << 9;
1861 case Attribute::ReadOnly:
return 1 << 10;
1862 case Attribute::NoInline:
return 1 << 11;
1863 case Attribute::AlwaysInline:
return 1 << 12;
1864 case Attribute::OptimizeForSize:
return 1 << 13;
1865 case Attribute::StackProtect:
return 1 << 14;
1866 case Attribute::StackProtectReq:
return 1 << 15;
1867 case Attribute::Alignment:
return 31 << 16;
1868 case Attribute::NoCapture:
return 1 << 21;
1869 case Attribute::NoRedZone:
return 1 << 22;
1870 case Attribute::NoImplicitFloat:
return 1 << 23;
1871 case Attribute::Naked:
return 1 << 24;
1872 case Attribute::InlineHint:
return 1 << 25;
1873 case Attribute::StackAlignment:
return 7 << 26;
1874 case Attribute::ReturnsTwice:
return 1 << 29;
1875 case Attribute::UWTable:
return 1 << 30;
1876 case Attribute::NonLazyBind:
return 1U << 31;
1877 case Attribute::SanitizeAddress:
return 1ULL << 32;
1878 case Attribute::MinSize:
return 1ULL << 33;
1879 case Attribute::NoDuplicate:
return 1ULL << 34;
1880 case Attribute::StackProtectStrong:
return 1ULL << 35;
1881 case Attribute::SanitizeThread:
return 1ULL << 36;
1882 case Attribute::SanitizeMemory:
return 1ULL << 37;
1883 case Attribute::NoBuiltin:
return 1ULL << 38;
1884 case Attribute::Returned:
return 1ULL << 39;
1885 case Attribute::Cold:
return 1ULL << 40;
1886 case Attribute::Builtin:
return 1ULL << 41;
1887 case Attribute::OptimizeNone:
return 1ULL << 42;
1888 case Attribute::InAlloca:
return 1ULL << 43;
1889 case Attribute::NonNull:
return 1ULL << 44;
1890 case Attribute::JumpTable:
return 1ULL << 45;
1891 case Attribute::Convergent:
return 1ULL << 46;
1892 case Attribute::SafeStack:
return 1ULL << 47;
1893 case Attribute::NoRecurse:
return 1ULL << 48;
1896 case Attribute::SwiftSelf:
return 1ULL << 51;
1897 case Attribute::SwiftError:
return 1ULL << 52;
1898 case Attribute::WriteOnly:
return 1ULL << 53;
1899 case Attribute::Speculatable:
return 1ULL << 54;
1900 case Attribute::StrictFP:
return 1ULL << 55;
1901 case Attribute::SanitizeHWAddress:
return 1ULL << 56;
1902 case Attribute::NoCfCheck:
return 1ULL << 57;
1903 case Attribute::OptForFuzzing:
return 1ULL << 58;
1904 case Attribute::ShadowCallStack:
return 1ULL << 59;
1905 case Attribute::SpeculativeLoadHardening:
1907 case Attribute::ImmArg:
1909 case Attribute::WillReturn:
1911 case Attribute::NoFree:
1927 if (
I == Attribute::Alignment)
1928 B.addAlignmentAttr(1ULL << ((
A >> 16) - 1));
1929 else if (
I == Attribute::StackAlignment)
1930 B.addStackAlignmentAttr(1ULL << ((
A >> 26)-1));
1932 B.addTypeAttr(
I,
nullptr);
1947 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1949 "Alignment must be a power of two.");
1952 B.addAlignmentAttr(Alignment);
1954 uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1955 (EncodedAttrs & 0xffff);
1960 if (Attrs & (1ULL << 9)) {
1962 Attrs &= ~(1ULL << 9);
1965 if (Attrs & (1ULL << 10)) {
1967 Attrs &= ~(1ULL << 10);
1970 if (Attrs & (1ULL << 49)) {
1972 Attrs &= ~(1ULL << 49);
1975 if (Attrs & (1ULL << 50)) {
1977 Attrs &= ~(1ULL << 50);
1980 if (Attrs & (1ULL << 53)) {
1982 Attrs &= ~(1ULL << 53);
1986 B.addMemoryAttr(ME);
1992Error BitcodeReader::parseAttributeBlock() {
1996 if (!MAttributes.empty())
1997 return error(
"Invalid multiple blocks");
2010 switch (
Entry.Kind) {
2013 return error(
"Malformed block");
2026 switch (MaybeRecord.
get()) {
2032 return error(
"Invalid parameter attribute record");
2034 for (
unsigned i = 0, e =
Record.size(); i != e; i += 2) {
2045 Attrs.push_back(MAttributeGroups[Val]);
2060 return Attribute::Alignment;
2062 return Attribute::AlwaysInline;
2064 return Attribute::Builtin;
2066 return Attribute::ByVal;
2068 return Attribute::InAlloca;
2070 return Attribute::Cold;
2072 return Attribute::Convergent;
2074 return Attribute::DisableSanitizerInstrumentation;
2076 return Attribute::ElementType;
2078 return Attribute::FnRetThunkExtern;
2080 return Attribute::InlineHint;
2082 return Attribute::InReg;
2084 return Attribute::JumpTable;
2086 return Attribute::Memory;
2088 return Attribute::NoFPClass;
2090 return Attribute::MinSize;
2092 return Attribute::Naked;
2094 return Attribute::Nest;
2096 return Attribute::NoAlias;
2098 return Attribute::NoBuiltin;
2100 return Attribute::NoCallback;
2102 return Attribute::NoCapture;
2104 return Attribute::NoDivergenceSource;
2106 return Attribute::NoDuplicate;
2108 return Attribute::NoFree;
2110 return Attribute::NoImplicitFloat;
2112 return Attribute::NoInline;
2114 return Attribute::NoRecurse;
2116 return Attribute::NoMerge;
2118 return Attribute::NonLazyBind;
2120 return Attribute::NonNull;
2122 return Attribute::Dereferenceable;
2124 return Attribute::DereferenceableOrNull;
2126 return Attribute::AllocAlign;
2128 return Attribute::AllocKind;
2130 return Attribute::AllocSize;
2132 return Attribute::AllocatedPointer;
2134 return Attribute::NoRedZone;
2136 return Attribute::NoReturn;
2138 return Attribute::NoSync;
2140 return Attribute::NoCfCheck;
2142 return Attribute::NoProfile;
2144 return Attribute::SkipProfile;
2146 return Attribute::NoUnwind;
2148 return Attribute::NoSanitizeBounds;
2150 return Attribute::NoSanitizeCoverage;
2152 return Attribute::NullPointerIsValid;
2154 return Attribute::OptimizeForDebugging;
2156 return Attribute::OptForFuzzing;
2158 return Attribute::OptimizeForSize;
2160 return Attribute::OptimizeNone;
2162 return Attribute::ReadNone;
2164 return Attribute::ReadOnly;
2166 return Attribute::Returned;
2168 return Attribute::ReturnsTwice;
2170 return Attribute::SExt;
2172 return Attribute::Speculatable;
2174 return Attribute::StackAlignment;
2176 return Attribute::StackProtect;
2178 return Attribute::StackProtectReq;
2180 return Attribute::StackProtectStrong;
2182 return Attribute::SafeStack;
2184 return Attribute::ShadowCallStack;
2186 return Attribute::StrictFP;
2188 return Attribute::StructRet;
2190 return Attribute::SanitizeAddress;
2192 return Attribute::SanitizeHWAddress;
2194 return Attribute::SanitizeThread;
2196 return Attribute::SanitizeType;
2198 return Attribute::SanitizeMemory;
2200 return Attribute::SanitizeNumericalStability;
2202 return Attribute::SanitizeRealtime;
2204 return Attribute::SanitizeRealtimeBlocking;
2206 return Attribute::SpeculativeLoadHardening;
2208 return Attribute::SwiftError;
2210 return Attribute::SwiftSelf;
2212 return Attribute::SwiftAsync;
2214 return Attribute::UWTable;
2216 return Attribute::VScaleRange;
2218 return Attribute::WillReturn;
2220 return Attribute::WriteOnly;
2222 return Attribute::ZExt;
2224 return Attribute::ImmArg;
2226 return Attribute::SanitizeMemTag;
2228 return Attribute::Preallocated;
2230 return Attribute::NoUndef;
2232 return Attribute::ByRef;
2234 return Attribute::MustProgress;
2236 return Attribute::Hot;
2238 return Attribute::PresplitCoroutine;
2240 return Attribute::Writable;
2242 return Attribute::CoroDestroyOnlyWhenComplete;
2244 return Attribute::DeadOnUnwind;
2246 return Attribute::Range;
2248 return Attribute::Initializes;
2250 return Attribute::CoroElideSafe;
2252 return Attribute::NoExt;
2261 return error(
"Invalid alignment value");
2269 return error(
"Unknown attribute kind (" +
Twine(Code) +
")");
2274 switch (EncodedKind) {
2298Error BitcodeReader::parseAttributeGroupBlock() {
2302 if (!MAttributeGroups.empty())
2303 return error(
"Invalid multiple blocks");
2314 switch (
Entry.Kind) {
2317 return error(
"Malformed block");
2330 switch (MaybeRecord.
get()) {
2335 return error(
"Invalid grp record");
2342 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2350 if (
Error Err = parseAttrKind(EncodedKind, &Kind))
2356 if (Kind == Attribute::ByVal)
2357 B.addByValAttr(
nullptr);
2358 else if (Kind == Attribute::StructRet)
2359 B.addStructRetAttr(
nullptr);
2360 else if (Kind == Attribute::InAlloca)
2361 B.addInAllocaAttr(
nullptr);
2362 else if (Kind == Attribute::UWTable)
2363 B.addUWTableAttr(UWTableKind::Default);
2365 B.addAttribute(Kind);
2367 return error(
"Not an enum attribute");
2368 }
else if (
Record[i] == 1) {
2370 if (
Error Err = parseAttrKind(
Record[++i], &Kind))
2373 return error(
"Not an int attribute");
2374 if (Kind == Attribute::Alignment)
2375 B.addAlignmentAttr(
Record[++i]);
2376 else if (Kind == Attribute::StackAlignment)
2377 B.addStackAlignmentAttr(
Record[++i]);
2378 else if (Kind == Attribute::Dereferenceable)
2379 B.addDereferenceableAttr(
Record[++i]);
2380 else if (Kind == Attribute::DereferenceableOrNull)
2381 B.addDereferenceableOrNullAttr(
Record[++i]);
2382 else if (Kind == Attribute::AllocSize)
2383 B.addAllocSizeAttrFromRawRepr(
Record[++i]);
2384 else if (Kind == Attribute::VScaleRange)
2385 B.addVScaleRangeAttrFromRawRepr(
Record[++i]);
2386 else if (Kind == Attribute::UWTable)
2388 else if (Kind == Attribute::AllocKind)
2390 else if (Kind == Attribute::Memory)
2392 else if (Kind == Attribute::NoFPClass)
2400 while (
Record[i] != 0 && i != e)
2402 assert(
Record[i] == 0 &&
"Kind string not null terminated");
2407 while (
Record[i] != 0 && i != e)
2409 assert(
Record[i] == 0 &&
"Value string not null terminated");
2412 B.addAttribute(KindStr.
str(), ValStr.
str());
2414 bool HasType =
Record[i] == 6;
2416 if (
Error Err = parseAttrKind(
Record[++i], &Kind))
2419 return error(
"Not a type attribute");
2421 B.addTypeAttr(Kind, HasType ? getTypeByID(
Record[++i]) :
nullptr);
2422 }
else if (
Record[i] == 7) {
2426 if (
Error Err = parseAttrKind(
Record[i++], &Kind))
2429 return error(
"Not a ConstantRange attribute");
2432 readBitWidthAndConstantRange(
Record, i);
2437 B.addConstantRangeAttr(Kind, MaybeCR.
get());
2438 }
else if (
Record[i] == 8) {
2442 if (
Error Err = parseAttrKind(
Record[i++], &Kind))
2445 return error(
"Not a constant range list attribute");
2449 return error(
"Too few records for constant range list");
2450 unsigned RangeSize =
Record[i++];
2452 for (
unsigned Idx = 0;
Idx < RangeSize; ++
Idx) {
2462 return error(
"Invalid (unordered or overlapping) range list");
2463 B.addConstantRangeListAttr(Kind, Val);
2465 return error(
"Invalid attribute group entry");
2470 B.addMemoryAttr(ME);
2480Error BitcodeReader::parseTypeTable() {
2484 return parseTypeTableBody();
2487Error BitcodeReader::parseTypeTableBody() {
2488 if (!TypeList.empty())
2489 return error(
"Invalid multiple blocks");
2492 unsigned NumRecords = 0;
2503 switch (
Entry.Kind) {
2506 return error(
"Malformed block");
2508 if (NumRecords != TypeList.size())
2509 return error(
"Malformed block");
2518 Type *ResultTy =
nullptr;
2523 switch (MaybeRecord.
get()) {
2525 return error(
"Invalid value");
2530 return error(
"Invalid numentry record");
2531 TypeList.resize(
Record[0]);
2576 return error(
"Invalid integer record");
2581 return error(
"Bitwidth for integer type out of range");
2588 return error(
"Invalid pointer record");
2592 ResultTy = getTypeByID(
Record[0]);
2594 !PointerType::isValidElementType(ResultTy))
2595 return error(
"Invalid type");
2602 return error(
"Invalid opaque pointer record");
2611 return error(
"Invalid function record");
2613 for (
unsigned i = 3, e =
Record.size(); i != e; ++i) {
2620 ResultTy = getTypeByID(
Record[2]);
2621 if (!ResultTy || ArgTys.
size() <
Record.size()-3)
2622 return error(
"Invalid type");
2625 ResultTy = FunctionType::get(ResultTy, ArgTys,
Record[0]);
2631 return error(
"Invalid function record");
2633 for (
unsigned i = 2, e =
Record.size(); i != e; ++i) {
2635 if (!FunctionType::isValidArgumentType(
T))
2636 return error(
"Invalid function argument type");
2643 ResultTy = getTypeByID(
Record[1]);
2644 if (!ResultTy || ArgTys.
size() <
Record.size()-2)
2645 return error(
"Invalid type");
2648 ResultTy = FunctionType::get(ResultTy, ArgTys,
Record[0]);
2653 return error(
"Invalid anon struct record");
2655 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2662 return error(
"Invalid type");
2669 return error(
"Invalid struct name record");
2674 return error(
"Invalid named struct record");
2676 if (NumRecords >= TypeList.size())
2677 return error(
"Invalid TYPE table");
2680 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2683 TypeList[NumRecords] =
nullptr;
2685 Res = createIdentifiedStructType(Context, TypeName);
2689 for (
unsigned i = 1, e =
Record.size(); i != e; ++i) {
2696 return error(
"Invalid named struct record");
2705 return error(
"Invalid opaque type 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);
2723 return error(
"Invalid target extension type record");
2725 if (NumRecords >= TypeList.size())
2726 return error(
"Invalid TYPE table");
2729 return error(
"Too many type parameters");
2731 unsigned NumTys =
Record[0];
2734 for (
unsigned i = 0; i < NumTys; i++) {
2738 return error(
"Invalid type");
2741 for (
unsigned i = NumTys + 1, e =
Record.size(); i < e; i++) {
2742 if (
Record[i] > UINT_MAX)
2743 return error(
"Integer parameter too large");
2748 if (
auto E = TTy.takeError())
2756 return error(
"Invalid array type record");
2757 ResultTy = getTypeByID(
Record[1]);
2758 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2759 return error(
"Invalid type");
2761 ResultTy = ArrayType::get(ResultTy,
Record[0]);
2766 return error(
"Invalid vector type record");
2768 return error(
"Invalid vector length");
2769 ResultTy = getTypeByID(
Record[1]);
2770 if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2771 return error(
"Invalid type");
2774 ResultTy = VectorType::get(ResultTy,
Record[0], Scalable);
2778 if (NumRecords >= TypeList.size())
2779 return error(
"Invalid TYPE table");
2780 if (TypeList[NumRecords])
2782 "Invalid TYPE table: Only named structs can be forward referenced");
2783 assert(ResultTy &&
"Didn't read a type?");
2784 TypeList[NumRecords] = ResultTy;
2785 if (!ContainedIDs.
empty())
2786 ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2791Error BitcodeReader::parseOperandBundleTags() {
2795 if (!BundleTags.empty())
2796 return error(
"Invalid multiple blocks");
2806 switch (
Entry.Kind) {
2809 return error(
"Malformed block");
2823 return error(
"Invalid operand bundle record");
2826 BundleTags.emplace_back();
2828 return error(
"Invalid operand bundle record");
2833Error BitcodeReader::parseSyncScopeNames() {
2838 return error(
"Invalid multiple synchronization scope names blocks");
2847 switch (
Entry.Kind) {
2850 return error(
"Malformed block");
2853 return error(
"Invalid empty synchronization scope names block");
2867 return error(
"Invalid sync scope record");
2871 return error(
"Invalid sync scope record");
2880 unsigned NameIndex,
Triple &TT) {
2883 return error(
"Invalid record");
2884 unsigned ValueID =
Record[0];
2885 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
2886 return error(
"Invalid record");
2887 Value *
V = ValueList[ValueID];
2890 if (NameStr.contains(0))
2891 return error(
"Invalid value name");
2892 V->setName(NameStr);
2893 auto *GO = dyn_cast<GlobalObject>(V);
2894 if (GO && ImplicitComdatObjects.
contains(GO) &&
TT.supportsCOMDAT())
2907 return std::move(JumpFailed);
2913 return error(
"Expected value symbol table subblock");
2917void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
2924 uint64_t FuncBitOffset = FuncWordOffset * 32;
2925 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2929 if (FuncBitOffset > LastFunctionBlockBit)
2930 LastFunctionBlockBit = FuncBitOffset;
2934Error BitcodeReader::parseGlobalValueSymbolTable() {
2935 unsigned FuncBitcodeOffsetDelta =
2948 switch (
Entry.Kind) {
2951 return error(
"Malformed block");
2962 switch (MaybeRecord.
get()) {
2964 unsigned ValueID =
Record[0];
2965 if (ValueID >= ValueList.
size() || !ValueList[ValueID])
2966 return error(
"Invalid value reference in symbol table");
2967 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2968 cast<Function>(ValueList[ValueID]),
Record);
2984 if (!MaybeCurrentBit)
2986 CurrentBit = MaybeCurrentBit.
get();
2989 if (
Error Err = parseGlobalValueSymbolTable())
2991 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
3010 unsigned FuncBitcodeOffsetDelta =
3029 switch (
Entry.Kind) {
3032 return error(
"Malformed block");
3035 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
3048 switch (MaybeRecord.
get()) {
3067 if (
auto *
F = dyn_cast<Function>(V))
3068 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
F,
Record);
3073 return error(
"Invalid bbentry record");
3076 return error(
"Invalid bbentry record");
3098Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3099 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3100 std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3101 std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3103 GlobalInitWorklist.swap(GlobalInits);
3104 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3105 FunctionOperandWorklist.swap(FunctionOperands);
3107 while (!GlobalInitWorklist.empty()) {
3108 unsigned ValID = GlobalInitWorklist.back().second;
3111 GlobalInits.push_back(GlobalInitWorklist.back());
3116 GlobalInitWorklist.back().first->setInitializer(MaybeC.
get());
3118 GlobalInitWorklist.pop_back();
3121 while (!IndirectSymbolInitWorklist.empty()) {
3122 unsigned ValID = IndirectSymbolInitWorklist.back().second;
3124 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3130 GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3131 if (
auto *GA = dyn_cast<GlobalAlias>(GV)) {
3133 return error(
"Alias and aliasee types don't match");
3135 }
else if (
auto *GI = dyn_cast<GlobalIFunc>(GV)) {
3138 return error(
"Expected an alias or an ifunc");
3141 IndirectSymbolInitWorklist.pop_back();
3144 while (!FunctionOperandWorklist.empty()) {
3145 FunctionOperandInfo &
Info = FunctionOperandWorklist.back();
3146 if (
Info.PersonalityFn) {
3147 unsigned ValID =
Info.PersonalityFn - 1;
3152 Info.F->setPersonalityFn(MaybeC.
get());
3153 Info.PersonalityFn = 0;
3162 Info.F->setPrefixData(MaybeC.
get());
3166 if (
Info.Prologue) {
3172 Info.F->setPrologueData(MaybeC.
get());
3176 if (
Info.PersonalityFn ||
Info.Prefix ||
Info.Prologue)
3177 FunctionOperands.push_back(Info);
3178 FunctionOperandWorklist.pop_back();
3187 BitcodeReader::decodeSignRotatedValue);
3189 return APInt(TypeBits, Words);
3192Error BitcodeReader::parseConstants() {
3200 unsigned Int32TyID = getVirtualTypeID(CurTy);
3201 unsigned CurTyID = Int32TyID;
3202 Type *CurElemTy =
nullptr;
3203 unsigned NextCstNo = ValueList.
size();
3211 switch (Entry.Kind) {
3214 return error(
"Malformed block");
3216 if (NextCstNo != ValueList.
size())
3217 return error(
"Invalid constant reference");
3231 switch (
unsigned BitCode = MaybeBitCode.
get()) {
3241 return error(
"Invalid settype record");
3242 if (
Record[0] >= TypeList.size() || !TypeList[
Record[0]])
3243 return error(
"Invalid settype record");
3244 if (TypeList[
Record[0]] == VoidType)
3245 return error(
"Invalid constant type");
3247 CurTy = TypeList[CurTyID];
3248 CurElemTy = getPtrElementTypeByID(CurTyID);
3252 return error(
"Invalid type for a constant null value");
3253 if (
auto *TETy = dyn_cast<TargetExtType>(CurTy))
3255 return error(
"Invalid type for a constant null value");
3260 return error(
"Invalid integer const record");
3265 return error(
"Invalid wide integer const record");
3269 V = ConstantInt::get(CurTy, VInt);
3274 return error(
"Invalid float const record");
3277 if (ScalarTy->isHalfTy())
3278 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEhalf(),
3280 else if (ScalarTy->isBFloatTy())
3281 V = ConstantFP::get(
3283 else if (ScalarTy->isFloatTy())
3284 V = ConstantFP::get(CurTy,
APFloat(APFloat::IEEEsingle(),
3286 else if (ScalarTy->isDoubleTy())
3287 V = ConstantFP::get(
3289 else if (ScalarTy->isX86_FP80Ty()) {
3292 Rearrange[0] = (
Record[1] & 0xffffLL) | (
Record[0] << 16);
3293 Rearrange[1] =
Record[0] >> 48;
3294 V = ConstantFP::get(
3295 CurTy,
APFloat(APFloat::x87DoubleExtended(),
APInt(80, Rearrange)));
3296 }
else if (ScalarTy->isFP128Ty())
3297 V = ConstantFP::get(CurTy,
3299 else if (ScalarTy->isPPC_FP128Ty())
3300 V = ConstantFP::get(
3309 return error(
"Invalid aggregate record");
3313 for (
unsigned i = 0; i !=
Size; ++i)
3316 if (isa<StructType>(CurTy)) {
3317 V = BitcodeConstant::create(
3318 Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3319 }
else if (isa<ArrayType>(CurTy)) {
3320 V = BitcodeConstant::create(Alloc, CurTy,
3321 BitcodeConstant::ConstantArrayOpcode, Elts);
3322 }
else if (isa<VectorType>(CurTy)) {
3323 V = BitcodeConstant::create(
3324 Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3333 return error(
"Invalid string record");
3342 return error(
"Invalid data record");
3345 if (
auto *Array = dyn_cast<ArrayType>(CurTy))
3346 EltTy =
Array->getElementType();
3348 EltTy = cast<VectorType>(CurTy)->getElementType();
3351 if (isa<VectorType>(CurTy))
3357 if (isa<VectorType>(CurTy))
3363 if (isa<VectorType>(CurTy))
3369 if (isa<VectorType>(CurTy))
3375 if (isa<VectorType>(CurTy))
3381 if (isa<VectorType>(CurTy))
3387 if (isa<VectorType>(CurTy))
3393 if (isa<VectorType>(CurTy))
3398 return error(
"Invalid type for value");
3404 return error(
"Invalid unary op constexpr record");
3409 V = BitcodeConstant::create(Alloc, CurTy, Opc, (
unsigned)
Record[1]);
3415 return error(
"Invalid binary op constexpr record");
3421 if (
Record.size() >= 4) {
3422 if (Opc == Instruction::Add ||
3423 Opc == Instruction::Sub ||
3424 Opc == Instruction::Mul ||
3425 Opc == Instruction::Shl) {
3430 }
else if (Opc == Instruction::SDiv ||
3431 Opc == Instruction::UDiv ||
3432 Opc == Instruction::LShr ||
3433 Opc == Instruction::AShr) {
3438 V = BitcodeConstant::create(Alloc, CurTy, {(
uint8_t)Opc, Flags},
3445 return error(
"Invalid cast constexpr record");
3450 unsigned OpTyID =
Record[1];
3451 Type *OpTy = getTypeByID(OpTyID);
3453 return error(
"Invalid cast constexpr record");
3454 V = BitcodeConstant::create(Alloc, CurTy, Opc, (
unsigned)
Record[2]);
3466 return error(
"Constant GEP record must have at least two elements");
3468 Type *PointeeType =
nullptr;
3472 PointeeType = getTypeByID(
Record[OpNum++]);
3475 std::optional<ConstantRange>
InRange;
3479 unsigned InRangeIndex =
Op >> 1;
3486 readBitWidthAndConstantRange(
Record, OpNum);
3496 unsigned BaseTypeID =
Record[OpNum];
3497 while (OpNum !=
Record.size()) {
3498 unsigned ElTyID =
Record[OpNum++];
3499 Type *ElTy = getTypeByID(ElTyID);
3501 return error(
"Invalid getelementptr constexpr record");
3505 if (Elts.
size() < 1)
3506 return error(
"Invalid gep with no operands");
3510 BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3511 BaseType = getTypeByID(BaseTypeID);
3516 return error(
"GEP base operand must be pointer or vector of pointer");
3519 PointeeType = getPtrElementTypeByID(BaseTypeID);
3521 return error(
"Missing element type for old-style constant GEP");
3524 V = BitcodeConstant::create(
3526 {Instruction::GetElementPtr,
uint8_t(Flags), PointeeType,
InRange},
3532 return error(
"Invalid select constexpr record");
3534 V = BitcodeConstant::create(
3535 Alloc, CurTy, Instruction::Select,
3542 return error(
"Invalid extractelement constexpr record");
3543 unsigned OpTyID =
Record[0];
3545 dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
3547 return error(
"Invalid extractelement constexpr record");
3549 if (
Record.size() == 4) {
3550 unsigned IdxTyID =
Record[2];
3551 Type *IdxTy = getTypeByID(IdxTyID);
3553 return error(
"Invalid extractelement constexpr record");
3559 V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
3565 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3566 if (
Record.size() < 3 || !OpTy)
3567 return error(
"Invalid insertelement constexpr record");
3569 if (
Record.size() == 4) {
3570 unsigned IdxTyID =
Record[2];
3571 Type *IdxTy = getTypeByID(IdxTyID);
3573 return error(
"Invalid insertelement constexpr record");
3579 V = BitcodeConstant::create(
3580 Alloc, CurTy, Instruction::InsertElement,
3585 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3586 if (
Record.size() < 3 || !OpTy)
3587 return error(
"Invalid shufflevector constexpr record");
3588 V = BitcodeConstant::create(
3589 Alloc, CurTy, Instruction::ShuffleVector,
3594 VectorType *RTy = dyn_cast<VectorType>(CurTy);
3596 dyn_cast_or_null<VectorType>(getTypeByID(
Record[0]));
3597 if (
Record.size() < 4 || !RTy || !OpTy)
3598 return error(
"Invalid shufflevector constexpr record");
3599 V = BitcodeConstant::create(
3600 Alloc, CurTy, Instruction::ShuffleVector,
3606 return error(
"Invalid cmp constexpt record");
3607 unsigned OpTyID =
Record[0];
3608 Type *OpTy = getTypeByID(OpTyID);
3610 return error(
"Invalid cmp constexpr record");
3611 V = BitcodeConstant::create(
3614 : Instruction::ICmp),
3623 return error(
"Invalid inlineasm record");
3624 std::string AsmStr, ConstrStr;
3625 bool HasSideEffects =
Record[0] & 1;
3626 bool IsAlignStack =
Record[0] >> 1;
3627 unsigned AsmStrSize =
Record[1];
3628 if (2+AsmStrSize >=
Record.size())
3629 return error(
"Invalid inlineasm record");
3630 unsigned ConstStrSize =
Record[2+AsmStrSize];
3631 if (3+AsmStrSize+ConstStrSize >
Record.size())
3632 return error(
"Invalid inlineasm record");
3634 for (
unsigned i = 0; i != AsmStrSize; ++i)
3635 AsmStr += (
char)
Record[2+i];
3636 for (
unsigned i = 0; i != ConstStrSize; ++i)
3637 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3640 return error(
"Missing element type for old-style inlineasm");
3642 HasSideEffects, IsAlignStack);
3649 return error(
"Invalid inlineasm record");
3650 std::string AsmStr, ConstrStr;
3651 bool HasSideEffects =
Record[0] & 1;
3652 bool IsAlignStack = (
Record[0] >> 1) & 1;
3653 unsigned AsmDialect =
Record[0] >> 2;
3654 unsigned AsmStrSize =
Record[1];
3655 if (2+AsmStrSize >=
Record.size())
3656 return error(
"Invalid inlineasm record");
3657 unsigned ConstStrSize =
Record[2+AsmStrSize];
3658 if (3+AsmStrSize+ConstStrSize >
Record.size())
3659 return error(
"Invalid inlineasm record");
3661 for (
unsigned i = 0; i != AsmStrSize; ++i)
3662 AsmStr += (
char)
Record[2+i];
3663 for (
unsigned i = 0; i != ConstStrSize; ++i)
3664 ConstrStr += (
char)
Record[3+AsmStrSize+i];
3667 return error(
"Missing element type for old-style inlineasm");
3669 HasSideEffects, IsAlignStack,
3676 return error(
"Invalid inlineasm record");
3678 std::string AsmStr, ConstrStr;
3679 bool HasSideEffects =
Record[OpNum] & 1;
3680 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3681 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3682 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3684 unsigned AsmStrSize =
Record[OpNum];
3686 if (OpNum + AsmStrSize >=
Record.size())
3687 return error(
"Invalid inlineasm record");
3688 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3689 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3690 return error(
"Invalid inlineasm record");
3692 for (
unsigned i = 0; i != AsmStrSize; ++i)
3693 AsmStr += (
char)
Record[OpNum + i];
3695 for (
unsigned i = 0; i != ConstStrSize; ++i)
3696 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3699 return error(
"Missing element type for old-style inlineasm");
3701 HasSideEffects, IsAlignStack,
3708 return error(
"Invalid inlineasm record");
3710 auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(
Record[OpNum]));
3713 return error(
"Invalid inlineasm record");
3714 std::string AsmStr, ConstrStr;
3715 bool HasSideEffects =
Record[OpNum] & 1;
3716 bool IsAlignStack = (
Record[OpNum] >> 1) & 1;
3717 unsigned AsmDialect = (
Record[OpNum] >> 2) & 1;
3718 bool CanThrow = (
Record[OpNum] >> 3) & 1;
3720 unsigned AsmStrSize =
Record[OpNum];
3722 if (OpNum + AsmStrSize >=
Record.size())
3723 return error(
"Invalid inlineasm record");
3724 unsigned ConstStrSize =
Record[OpNum + AsmStrSize];
3725 if (OpNum + 1 + AsmStrSize + ConstStrSize >
Record.size())
3726 return error(
"Invalid inlineasm record");
3728 for (
unsigned i = 0; i != AsmStrSize; ++i)
3729 AsmStr += (
char)
Record[OpNum + i];
3731 for (
unsigned i = 0; i != ConstStrSize; ++i)
3732 ConstrStr += (
char)
Record[OpNum + AsmStrSize + i];
3734 V =
InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3740 return error(
"Invalid blockaddress record");
3741 unsigned FnTyID =
Record[0];
3742 Type *FnTy = getTypeByID(FnTyID);
3744 return error(
"Invalid blockaddress record");
3745 V = BitcodeConstant::create(
3753 return error(
"Invalid dso_local record");
3754 unsigned GVTyID =
Record[0];
3755 Type *GVTy = getTypeByID(GVTyID);
3757 return error(
"Invalid dso_local record");
3758 V = BitcodeConstant::create(
3759 Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode,
Record[1]);
3764 return error(
"Invalid no_cfi record");
3765 unsigned GVTyID =
Record[0];
3766 Type *GVTy = getTypeByID(GVTyID);
3768 return error(
"Invalid no_cfi record");
3769 V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3775 return error(
"Invalid ptrauth record");
3777 V = BitcodeConstant::create(Alloc, CurTy,
3778 BitcodeConstant::ConstantPtrAuthOpcode,
3785 assert(
V->getType() == getTypeByID(CurTyID) &&
"Incorrect result type ID");
3792Error BitcodeReader::parseUseLists() {
3805 switch (
Entry.Kind) {
3808 return error(
"Malformed block");
3822 switch (MaybeRecord.
get()) {
3830 if (RecordLength < 3)
3832 return error(
"Invalid record");
3833 unsigned ID =
Record.pop_back_val();
3837 assert(
ID < FunctionBBs.size() &&
"Basic block not found");
3838 V = FunctionBBs[
ID];
3841 unsigned NumUses = 0;
3843 for (
const Use &U :
V->materialized_uses()) {
3844 if (++NumUses >
Record.size())
3846 Order[&
U] =
Record[NumUses - 1];
3853 V->sortUseList([&](
const Use &L,
const Use &R) {
3864Error BitcodeReader::rememberAndSkipMetadata() {
3866 uint64_t CurBit = Stream.GetCurrentBitNo();
3867 DeferredMetadataInfo.push_back(CurBit);
3870 if (
Error Err = Stream.SkipBlock())
3875Error BitcodeReader::materializeMetadata() {
3876 for (
uint64_t BitPos : DeferredMetadataInfo) {
3878 if (
Error JumpFailed = Stream.JumpToBit(BitPos))
3880 if (
Error Err = MDLoader->parseModuleMetadata())
3891 for (
const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3892 LinkerOpts->
addOperand(cast<MDNode>(MDOptions));
3896 DeferredMetadataInfo.clear();
3900void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
3904Error BitcodeReader::rememberAndSkipFunctionBody() {
3906 if (FunctionsWithBodies.empty())
3907 return error(
"Insufficient function protos");
3910 FunctionsWithBodies.pop_back();
3913 uint64_t CurBit = Stream.GetCurrentBitNo();
3915 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3916 "Mismatch between VST and scanned function offsets");
3917 DeferredFunctionInfo[Fn] = CurBit;
3920 if (
Error Err = Stream.SkipBlock())
3925Error BitcodeReader::globalCleanup() {
3927 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
3929 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3930 return error(
"Malformed global initializer set");
3935 MDLoader->upgradeDebugIntrinsics(
F);
3942 UpgradedIntrinsics[&
F] = NewFn;
3948 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3951 UpgradedVariables.emplace_back(&GV, Upgraded);
3952 for (
auto &Pair : UpgradedVariables) {
3953 Pair.first->eraseFromParent();
3954 TheModule->insertGlobalVariable(Pair.second);
3959 std::vector<std::pair<GlobalVariable *, unsigned>>().
swap(GlobalInits);
3960 std::vector<std::pair<GlobalValue *, unsigned>>().
swap(IndirectSymbolInits);
3968Error BitcodeReader::rememberAndSkipFunctionBodies() {
3969 if (
Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3972 if (Stream.AtEndOfStream())
3973 return error(
"Could not find function in stream");
3975 if (!SeenFirstFunctionBody)
3976 return error(
"Trying to materialize functions before seeing function blocks");
3980 assert(SeenValueSymbolTable);
3990 switch (
Entry.Kind) {
3992 return error(
"Expect SubBlock");
3996 return error(
"Expect function block");
3998 if (
Error Err = rememberAndSkipFunctionBody())
4000 NextUnreadBit = Stream.GetCurrentBitNo();
4007Error BitcodeReaderBase::readBlockInfo() {
4009 Stream.ReadBlockInfoBlock();
4010 if (!MaybeNewBlockInfo)
4012 std::optional<BitstreamBlockInfo> NewBlockInfo =
4013 std::move(MaybeNewBlockInfo.
get());
4015 return error(
"Malformed block");
4016 BlockInfo = std::move(*NewBlockInfo);
4027 return error(
"Invalid record");
4029 std::string OldFormatName;
4032 return error(
"Invalid record");
4033 unsigned ComdatNameSize =
Record[1];
4034 if (ComdatNameSize >
Record.size() - 2)
4035 return error(
"Comdat name size too large");
4036 OldFormatName.reserve(ComdatNameSize);
4037 for (
unsigned i = 0; i != ComdatNameSize; ++i)
4038 OldFormatName += (
char)
Record[2 + i];
4039 Name = OldFormatName;
4042 C->setSelectionKind(SK);
4043 ComdatList.push_back(
C);
4057 Meta.NoAddress =
true;
4059 Meta.NoHWAddress =
true;
4063 Meta.IsDynInit =
true;
4078 return error(
"Invalid record");
4079 unsigned TyID =
Record[0];
4080 Type *Ty = getTypeByID(TyID);
4082 return error(
"Invalid record");
4084 bool explicitType =
Record[1] & 2;
4090 return error(
"Invalid type for value");
4091 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
4092 TyID = getContainedTypeID(TyID);
4093 Ty = getTypeByID(TyID);
4095 return error(
"Missing element type for old-style global");
4101 if (
Error Err = parseAlignmentValue(
Record[4], Alignment))
4105 if (
Record[5] - 1 >= SectionTable.size())
4106 return error(
"Invalid ID");
4123 bool ExternallyInitialized =
false;
4125 ExternallyInitialized =
Record[9];
4137 if (
Record.size() > 10) {
4149 if (
unsigned InitID =
Record[2])
4150 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
4152 if (
Record.size() > 11) {
4153 if (
unsigned ComdatID =
Record[11]) {
4154 if (ComdatID > ComdatList.size())
4155 return error(
"Invalid global variable comdat ID");
4156 NewGV->
setComdat(ComdatList[ComdatID - 1]);
4159 ImplicitComdatObjects.
insert(NewGV);
4162 if (
Record.size() > 12) {
4167 if (
Record.size() > 13) {
4186 return error(
"Invalid global variable code model");
4192void BitcodeReader::callValueTypeCallback(
Value *
F,
unsigned TypeID) {
4193 if (ValueTypeCallback) {
4194 (*ValueTypeCallback)(
4195 F,
TypeID, [
this](
unsigned I) {
return getTypeByID(
I); },
4196 [
this](
unsigned I,
unsigned J) {
return getContainedTypeID(
I, J); });
4209 return error(
"Invalid record");
4210 unsigned FTyID =
Record[0];
4211 Type *FTy = getTypeByID(FTyID);
4213 return error(
"Invalid record");
4214 if (isa<PointerType>(FTy)) {
4215 FTyID = getContainedTypeID(FTyID, 0);
4216 FTy = getTypeByID(FTyID);
4218 return error(
"Missing element type for old-style function");
4221 if (!isa<FunctionType>(FTy))
4222 return error(
"Invalid type for value");
4225 return error(
"Invalid calling convention ID");
4227 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4233 AddrSpace,
Name, TheModule);
4236 "Incorrect fully specified type provided for function");
4237 FunctionTypeIDs[
Func] = FTyID;
4239 Func->setCallingConv(
CC);
4240 bool isProto =
Record[2];
4244 callValueTypeCallback(Func, FTyID);
4249 for (
unsigned i = 0; i !=
Func->arg_size(); ++i) {
4251 Attribute::InAlloca}) {
4252 if (!
Func->hasParamAttribute(i, Kind))
4255 if (
Func->getParamAttribute(i, Kind).getValueAsType())
4258 Func->removeParamAttr(i, Kind);
4260 unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4261 Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4263 return error(
"Missing param element type for attribute upgrade");
4267 case Attribute::ByVal:
4270 case Attribute::StructRet:
4273 case Attribute::InAlloca:
4280 Func->addParamAttr(i, NewAttr);
4285 !
Func->arg_empty() && !
Func->hasParamAttribute(0, Attribute::ByVal)) {
4286 unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4287 Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4289 return error(
"Missing param element type for x86_intrcc upgrade");
4291 Func->addParamAttr(0, NewAttr);
4295 if (
Error Err = parseAlignmentValue(
Record[5], Alignment))
4298 Func->setAlignment(*Alignment);
4300 if (
Record[6] - 1 >= SectionTable.size())
4301 return error(
"Invalid ID");
4302 Func->setSection(SectionTable[
Record[6] - 1]);
4306 if (!
Func->hasLocalLinkage())
4309 if (
Record[8] - 1 >= GCTable.size())
4310 return error(
"Invalid ID");
4316 Func->setUnnamedAddr(UnnamedAddr);
4322 if (
Record.size() > 11) {
4324 if (!
Func->hasLocalLinkage()) {
4331 if (
Record.size() > 12) {
4332 if (
unsigned ComdatID =
Record[12]) {
4333 if (ComdatID > ComdatList.size())
4334 return error(
"Invalid function comdat ID");
4335 Func->setComdat(ComdatList[ComdatID - 1]);
4338 ImplicitComdatObjects.
insert(Func);
4347 if (
Record.size() > 15) {
4356 if (
Record.size() > 18 && Strtab.data() &&
4361 ValueList.
push_back(Func, getVirtualTypeID(
Func->getType(), FTyID));
4369 Func->setIsMaterializable(
true);
4370 FunctionsWithBodies.push_back(Func);
4371 DeferredFunctionInfo[
Func] = 0;
4376Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4390 if (
Record.size() < (3 + (
unsigned)NewRecord))
4391 return error(
"Invalid record");
4396 return error(
"Invalid record");
4400 auto *PTy = dyn_cast<PointerType>(Ty);
4402 return error(
"Invalid type for value");
4403 AddrSpace = PTy->getAddressSpace();
4405 Ty = getTypeByID(
TypeID);
4407 return error(
"Missing element type for old-style indirect symbol");
4409 AddrSpace =
Record[OpNum++];
4412 auto Val =
Record[OpNum++];
4421 nullptr, TheModule);
4425 if (OpNum !=
Record.size()) {
4426 auto VisInd = OpNum++;
4432 if (OpNum !=
Record.size()) {
4433 auto S =
Record[OpNum++];
4440 if (OpNum !=
Record.size())
4442 if (OpNum !=
Record.size())
4445 if (OpNum !=
Record.size())
4450 if (OpNum + 1 <
Record.size()) {
4453 return error(
"Malformed partition, too large.");
4459 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4464 bool ShouldLazyLoadMetadata,
4470 TheModule->IsNewDbgInfoFormat =
4475 this->ValueTypeCallback = std::move(Callbacks.
ValueType);
4477 if (
Error JumpFailed = Stream.JumpToBit(ResumeBit))
4486 bool ResolvedDataLayout =
false;
4491 std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4493 auto ResolveDataLayout = [&]() ->
Error {
4494 if (ResolvedDataLayout)
4498 ResolvedDataLayout =
true;
4502 TentativeDataLayoutStr, TheModule->getTargetTriple());
4506 if (
auto LayoutOverride = (*Callbacks.
DataLayout)(
4507 TheModule->getTargetTriple(), TentativeDataLayoutStr))
4508 TentativeDataLayoutStr = *LayoutOverride;
4516 TheModule->setDataLayout(MaybeDL.
get());
4527 switch (
Entry.Kind) {
4529 return error(
"Malformed block");
4531 if (
Error Err = ResolveDataLayout())
4533 return globalCleanup();
4538 if (
Error Err = Stream.SkipBlock())
4542 if (
Error Err = readBlockInfo())
4546 if (
Error Err = parseAttributeBlock())
4550 if (
Error Err = parseAttributeGroupBlock())
4554 if (
Error Err = parseTypeTable())
4558 if (!SeenValueSymbolTable) {
4564 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4565 if (
Error Err = parseValueSymbolTable())
4567 SeenValueSymbolTable =
true;
4572 if (
Error Err = Stream.SkipBlock())
4577 if (
Error Err = parseConstants())
4579 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
4583 if (ShouldLazyLoadMetadata) {
4584 if (
Error Err = rememberAndSkipMetadata())
4588 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
4589 if (
Error Err = MDLoader->parseModuleMetadata())
4593 if (
Error Err = MDLoader->parseMetadataKinds())
4597 if (
Error Err = ResolveDataLayout())
4602 if (!SeenFirstFunctionBody) {
4603 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4604 if (
Error Err = globalCleanup())
4606 SeenFirstFunctionBody =
true;
4609 if (VSTOffset > 0) {
4613 if (!SeenValueSymbolTable) {
4614 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4616 SeenValueSymbolTable =
true;
4628 if (
Error Err = Stream.SkipBlock())
4638 if (
Error Err = rememberAndSkipFunctionBody())
4645 if (SeenValueSymbolTable) {
4646 NextUnreadBit = Stream.GetCurrentBitNo();
4649 return globalCleanup();
4653 if (
Error Err = parseUseLists())
4657 if (
Error Err = parseOperandBundleTags())
4661 if (
Error Err = parseSyncScopeNames())
4676 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4682 UseRelativeIDs = *VersionOrErr >= 1;
4686 if (ResolvedDataLayout)
4687 return error(
"target triple too late in module");
4690 return error(
"Invalid record");
4691 TheModule->setTargetTriple(S);
4695 if (ResolvedDataLayout)
4696 return error(
"datalayout too late in module");
4698 return error(
"Invalid record");
4704 return error(
"Invalid record");
4705 TheModule->setModuleInlineAsm(S);
4712 return error(
"Invalid record");
4719 return error(
"Invalid record");
4720 SectionTable.push_back(S);
4726 return error(
"Invalid record");
4727 GCTable.push_back(S);
4744 if (
Error Err = ResolveDataLayout())
4752 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode,
Record))
4758 return error(
"Invalid record");
4762 VSTOffset =
Record[0] - 1;
4768 return error(
"Invalid record");
4769 TheModule->setSourceFileName(
ValueName);
4774 this->ValueTypeCallback = std::nullopt;
4778Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
4783 MDCallbacks.
GetTypeByID = [&](
unsigned ID) {
return getTypeByID(
ID); };
4785 return getContainedTypeID(
I, J);
4788 MDLoader =
MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4789 return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4792Error BitcodeReader::typeCheckLoadStoreInst(
Type *ValType,
Type *PtrType) {
4793 if (!isa<PointerType>(PtrType))
4794 return error(
"Load/Store operand is not a pointer type");
4795 if (!PointerType::isLoadableOrStorableType(ValType))
4796 return error(
"Cannot load/store from pointer");
4803 for (
unsigned i = 0; i != CB->
arg_size(); ++i) {
4805 Attribute::InAlloca}) {
4806 if (!
Attrs.hasParamAttr(i, Kind) ||
4807 Attrs.getParamAttr(i, Kind).getValueAsType())
4810 Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4812 return error(
"Missing element type for typed attribute upgrade");
4816 case Attribute::ByVal:
4819 case Attribute::StructRet:
4822 case Attribute::InAlloca:
4829 Attrs =
Attrs.addParamAttribute(Context, i, NewAttr);
4840 if (CI.isIndirect && !
Attrs.getParamElementType(ArgNo)) {
4841 Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4843 return error(
"Missing element type for inline asm upgrade");
4854 case Intrinsic::preserve_array_access_index:
4855 case Intrinsic::preserve_struct_access_index:
4856 case Intrinsic::aarch64_ldaxr:
4857 case Intrinsic::aarch64_ldxr:
4858 case Intrinsic::aarch64_stlxr:
4859 case Intrinsic::aarch64_stxr:
4860 case Intrinsic::arm_ldaex:
4861 case Intrinsic::arm_ldrex:
4862 case Intrinsic::arm_stlex:
4863 case Intrinsic::arm_strex: {
4866 case Intrinsic::aarch64_stlxr:
4867 case Intrinsic::aarch64_stxr:
4868 case Intrinsic::arm_stlex:
4869 case Intrinsic::arm_strex:
4876 if (!
Attrs.getParamElementType(ArgNo)) {
4877 Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4879 return error(
"Missing element type for elementtype upgrade");
4881 Attrs =
Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4899 if (MDLoader->hasFwdRefs())
4900 return error(
"Invalid function metadata: incoming forward references");
4902 InstructionList.
clear();
4903 unsigned ModuleValueListSize = ValueList.
size();
4904 unsigned ModuleMDLoaderSize = MDLoader->size();
4908 unsigned FTyID = FunctionTypeIDs[
F];
4910 unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4911 assert(
I.getType() == getTypeByID(ArgTyID) &&
4912 "Incorrect fully specified type for Function Argument");
4916 unsigned NextValueNo = ValueList.
size();
4918 unsigned CurBBNo = 0;
4927 auto getLastInstruction = [&]() ->
Instruction * {
4928 if (CurBB && !CurBB->
empty())
4929 return &CurBB->
back();
4930 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4931 !FunctionBBs[CurBBNo - 1]->empty())
4932 return &FunctionBBs[CurBBNo - 1]->back();
4936 std::vector<OperandBundleDef> OperandBundles;
4947 switch (
Entry.Kind) {
4949 return error(
"Malformed block");
4951 goto OutOfRecordLoop;
4956 if (
Error Err = Stream.SkipBlock())
4960 if (
Error Err = parseConstants())
4962 NextValueNo = ValueList.
size();
4965 if (
Error Err = parseValueSymbolTable())
4969 if (
Error Err = MDLoader->parseMetadataAttachment(*
F, InstructionList))
4973 assert(DeferredMetadataInfo.empty() &&
4974 "Must read all module-level metadata before function-level");
4975 if (
Error Err = MDLoader->parseFunctionMetadata())
4979 if (
Error Err = parseUseLists())
4993 unsigned ResTypeID = InvalidTypeID;
4997 switch (
unsigned BitCode = MaybeBitCode.
get()) {
4999 return error(
"Invalid value");
5002 return error(
"Invalid record");
5004 FunctionBBs.resize(
Record[0]);
5007 auto BBFRI = BasicBlockFwdRefs.
find(
F);
5008 if (BBFRI == BasicBlockFwdRefs.
end()) {
5012 auto &BBRefs = BBFRI->second;
5014 if (BBRefs.size() > FunctionBBs.size())
5015 return error(
"Invalid ID");
5016 assert(!BBRefs.empty() &&
"Unexpected empty array");
5017 assert(!BBRefs.front() &&
"Invalid reference to entry block");
5018 for (
unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size();
I != E;
5020 if (
I < RE && BBRefs[
I]) {
5021 BBRefs[
I]->insertInto(
F);
5022 FunctionBBs[
I] = BBRefs[
I];
5028 BasicBlockFwdRefs.
erase(BBFRI);
5031 CurBB = FunctionBBs[0];
5038 return error(
"Invalid record");
5053 if (
auto *
F = dyn_cast<Function>(ValueList[
ValID]))
5054 BackwardRefFunctions.push_back(
F);
5056 return error(
"Invalid record");
5063 I = getLastInstruction();
5066 return error(
"Invalid record");
5067 I->setDebugLoc(LastLoc);
5072 I = getLastInstruction();
5074 return error(
"Invalid record");
5082 Scope = dyn_cast_or_null<MDNode>(
5083 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
5085 return error(
"Invalid record");
5088 IA = dyn_cast_or_null<MDNode>(
5089 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
5091 return error(
"Invalid record");
5093 LastLoc = DILocation::get(
Scope->getContext(), Line, Col, Scope, IA,
5095 I->setDebugLoc(LastLoc);
5103 if (getValueTypePair(
Record, OpNum, NextValueNo, LHS,
TypeID, CurBB) ||
5105 return error(
"Invalid record");
5109 return error(
"Invalid record");
5113 if (OpNum <
Record.size()) {
5114 if (isa<FPMathOperator>(
I)) {
5117 I->setFastMathFlags(FMF);
5126 if (getValueTypePair(
Record, OpNum, NextValueNo, LHS,
TypeID, CurBB) ||
5130 return error(
"Invalid record");
5134 return error(
"Invalid record");
5138 if (OpNum <
Record.size()) {
5139 if (Opc == Instruction::Add ||
5140 Opc == Instruction::Sub ||
5141 Opc == Instruction::Mul ||
5142 Opc == Instruction::Shl) {
5144 cast<BinaryOperator>(
I)->setHasNoSignedWrap(
true);
5146 cast<BinaryOperator>(
I)->setHasNoUnsignedWrap(
true);
5147 }
else if (Opc == Instruction::SDiv ||
5148 Opc == Instruction::UDiv ||
5149 Opc == Instruction::LShr ||
5150 Opc == Instruction::AShr) {
5152 cast<BinaryOperator>(
I)->setIsExact(
true);
5153 }
else if (Opc == Instruction::Or) {
5155 cast<PossiblyDisjointInst>(
I)->setIsDisjoint(
true);
5156 }
else if (isa<FPMathOperator>(
I)) {
5159 I->setFastMathFlags(FMF);
5168 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
5169 OpNum + 1 >
Record.size())
5170 return error(
"Invalid record");
5172 ResTypeID =
Record[OpNum++];
5173 Type *ResTy = getTypeByID(ResTypeID);
5176 if (Opc == -1 || !ResTy)
5177 return error(
"Invalid record");
5182 assert(CurBB &&
"No current BB?");
5188 return error(
"Invalid cast");
5192 if (OpNum <
Record.size()) {
5193 if (Opc == Instruction::ZExt || Opc == Instruction::UIToFP) {
5195 cast<PossiblyNonNegInst>(
I)->setNonNeg(
true);
5196 }
else if (Opc == Instruction::Trunc) {
5198 cast<TruncInst>(
I)->setHasNoUnsignedWrap(
true);
5200 cast<TruncInst>(
I)->setHasNoSignedWrap(
true);
5202 if (isa<FPMathOperator>(
I)) {
5205 I->setFastMathFlags(FMF);
5224 Ty = getTypeByID(TyID);
5228 TyID = InvalidTypeID;
5233 unsigned BasePtrTypeID;
5234 if (getValueTypePair(
Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5236 return error(
"Invalid record");
5239 TyID = getContainedTypeID(BasePtrTypeID);
5240 if (
BasePtr->getType()->isVectorTy())
5241 TyID = getContainedTypeID(TyID);
5242 Ty = getTypeByID(TyID);
5246 while (OpNum !=
Record.size()) {
5249 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5250 return error(
"Invalid record");
5258 if (cast<GEPOperator>(
I)->getNumIndices() != 0) {
5261 unsigned SubType = 0;
5262 if (GTI.isStruct()) {
5264 Idx->getType()->isVectorTy()
5269 ResTypeID = getContainedTypeID(ResTypeID, SubType);
5276 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType(), ResTypeID);
5277 if (
I->getType()->isVectorTy())
5278 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5281 GEP->setNoWrapFlags(NW);
5290 if (getValueTypePair(
Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5291 return error(
"Invalid record");
5294 unsigned RecSize =
Record.size();
5295 if (OpNum == RecSize)
5296 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
5299 ResTypeID = AggTypeID;
5300 for (; OpNum != RecSize; ++OpNum) {
5305 if (!IsStruct && !IsArray)
5306 return error(
"EXTRACTVAL: Invalid type");
5307 if ((
unsigned)Index != Index)
5308 return error(
"Invalid value");
5310 return error(
"EXTRACTVAL: Invalid struct index");
5312 return error(
"EXTRACTVAL: Invalid array index");
5313 EXTRACTVALIdx.
push_back((
unsigned)Index);
5317 ResTypeID = getContainedTypeID(ResTypeID, Index);
5320 ResTypeID = getContainedTypeID(ResTypeID);
5334 if (getValueTypePair(
Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5335 return error(
"Invalid record");
5338 if (getValueTypePair(
Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5339 return error(
"Invalid record");
5341 unsigned RecSize =
Record.size();
5342 if (OpNum == RecSize)
5343 return error(
"INSERTVAL: Invalid instruction with 0 indices");
5347 for (; OpNum != RecSize; ++OpNum) {
5352 if (!IsStruct && !IsArray)
5353 return error(
"INSERTVAL: Invalid type");
5354 if ((
unsigned)Index != Index)
5355 return error(
"Invalid value");
5357 return error(
"INSERTVAL: Invalid struct index");
5359 return error(
"INSERTVAL: Invalid array index");
5361 INSERTVALIdx.
push_back((
unsigned)Index);
5369 return error(
"Inserted value type doesn't match aggregate type");
5372 ResTypeID = AggTypeID;
5384 if (getValueTypePair(
Record, OpNum, NextValueNo, TrueVal,
TypeID,
5388 popValue(
Record, OpNum, NextValueNo, CondType,
5389 getVirtualTypeID(CondType),
Cond, CurBB))
5390 return error(
"Invalid record");
5403 unsigned ValTypeID, CondTypeID;
5404 if (getValueTypePair(
Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5406 popValue(
Record, OpNum, NextValueNo,
TrueVal->getType(), ValTypeID,
5408 getValueTypePair(
Record, OpNum, NextValueNo,
Cond, CondTypeID, CurBB))
5409 return error(
"Invalid record");
5413 dyn_cast<VectorType>(
Cond->getType())) {
5416 return error(
"Invalid type for value");
5420 return error(
"Invalid type for value");
5424 ResTypeID = ValTypeID;
5426 if (OpNum <
Record.size() && isa<FPMathOperator>(
I)) {
5429 I->setFastMathFlags(FMF);
5437 unsigned VecTypeID, IdxTypeID;
5438 if (getValueTypePair(
Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5439 getValueTypePair(
Record, OpNum, NextValueNo,
Idx, IdxTypeID, CurBB))
5440 return error(
"Invalid record");
5442 return error(
"Invalid type for value");
5444 ResTypeID = getContainedTypeID(VecTypeID);
5452 unsigned VecTypeID, IdxTypeID;
5453 if (getValueTypePair(
Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5454 return error(
"Invalid record");
5456 return error(
"Invalid type for value");
5457 if (popValue(
Record, OpNum, NextValueNo,
5458 cast<VectorType>(Vec->
getType())->getElementType(),
5459 getContainedTypeID(VecTypeID), Elt, CurBB) ||
5460 getValueTypePair(
Record, OpNum, NextValueNo,
Idx, IdxTypeID, CurBB))
5461 return error(
"Invalid record");
5463 ResTypeID = VecTypeID;
5471 unsigned Vec1TypeID;
5472 if (getValueTypePair(
Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5474 popValue(
Record, OpNum, NextValueNo, Vec1->
getType(), Vec1TypeID,
5476 return error(
"Invalid record");
5478 unsigned MaskTypeID;
5479 if (getValueTypePair(
Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5480 return error(
"Invalid record");
5482 return error(
"Invalid type for value");
5486 getVirtualTypeID(
I->getType(), getContainedTypeID(Vec1TypeID));
5501 if (getValueTypePair(
Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
5504 return error(
"Invalid record");
5506 if (OpNum >=
Record.size())
5508 "Invalid record: operand number exceeded available operands");
5513 if (IsFP &&
Record.size() > OpNum+1)
5518 return error(
"Invalid fcmp predicate");
5522 return error(
"Invalid icmp predicate");
5524 if (
Record.size() > OpNum + 1 &&
5526 cast<ICmpInst>(
I)->setSameSign();
5529 if (OpNum + 1 !=
Record.size())
5530 return error(
"Invalid record");
5532 ResTypeID = getVirtualTypeID(
I->getType()->getScalarType());
5534 ResTypeID = getVirtualTypeID(
I->getType(), ResTypeID);
5537 I->setFastMathFlags(FMF);
5554 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5555 return error(
"Invalid record");
5556 if (OpNum !=
Record.size())
5557 return error(
"Invalid record");
5565 return error(
"Invalid record");
5568 return error(
"Invalid record");
5570 if (
Record.size() == 1) {
5578 getVirtualTypeID(CondType), CurBB);
5579 if (!FalseDest || !
Cond)
5580 return error(
"Invalid record");
5588 return error(
"Invalid record");
5591 Value *CleanupPad = getValue(
Record,
Idx++, NextValueNo, TokenTy,
5592 getVirtualTypeID(TokenTy), CurBB);
5594 return error(
"Invalid record");
5596 if (
Record.size() == 2) {
5597 UnwindDest = getBasicBlock(
Record[
Idx++]);
5599 return error(
"Invalid record");
5608 return error(
"Invalid record");
5612 getVirtualTypeID(TokenTy), CurBB);
5614 return error(
"Invalid record");
5617 return error(
"Invalid record");
5626 return error(
"Invalid record");
5632 getVirtualTypeID(TokenTy), CurBB);
5634 return error(
"Invalid record");
5639 for (
unsigned Op = 0;
Op != NumHandlers; ++
Op) {
5642 return error(
"Invalid record");
5648 UnwindDest = getBasicBlock(
Record[
Idx++]);
5650 return error(
"Invalid record");
5654 return error(
"Invalid record");
5659 CatchSwitch->addHandler(Handler);
5661 ResTypeID = getVirtualTypeID(
I->getType());
5669 return error(
"Invalid record");
5675 getVirtualTypeID(TokenTy), CurBB);
5677 return error(
"Invald record");
5679 unsigned NumArgOperands =
Record[
Idx++];
5682 for (
unsigned Op = 0;
Op != NumArgOperands; ++
Op) {
5685 if (getValueTypePair(
Record,
Idx, NextValueNo, Val, ValTypeID,
nullptr))
5686 return error(
"Invalid record");
5687 Args.push_back(Val);
5691 return error(
"Invalid record");
5697 ResTypeID = getVirtualTypeID(
I->getType());
5703 if ((
Record[0] >> 16) == SWITCH_INST_MAGIC) {
5709 unsigned OpTyID =
Record[1];
5710 Type *OpTy = getTypeByID(OpTyID);
5711 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5716 return error(
"Invalid record");
5718 unsigned NumCases =
Record[4];
5723 unsigned CurIdx = 5;
5724 for (
unsigned i = 0; i != NumCases; ++i) {
5726 unsigned NumItems =
Record[CurIdx++];
5727 for (
unsigned ci = 0; ci != NumItems; ++ci) {
5728 bool isSingleNumber =
Record[CurIdx++];
5731 unsigned ActiveWords = 1;
5732 if (ValueBitWidth > 64)
5733 ActiveWords =
Record[CurIdx++];
5736 CurIdx += ActiveWords;
5738 if (!isSingleNumber) {
5740 if (ValueBitWidth > 64)
5741 ActiveWords =
Record[CurIdx++];
5744 CurIdx += ActiveWords;
5757 SI->addCase(Cst, DestBB);
5766 return error(
"Invalid record");
5767 unsigned OpTyID =
Record[0];
5768 Type *OpTy = getTypeByID(OpTyID);
5772 return error(
"Invalid record");
5773 unsigned NumCases = (
Record.size()-3)/2;
5776 for (
unsigned i = 0, e = NumCases; i !=
e; ++i) {
5777 ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
5778 getFnValueByID(
Record[3+i*2], OpTy, OpTyID,
nullptr));
5780 if (!CaseVal || !DestBB) {
5782 return error(
"Invalid record");
5784 SI->addCase(CaseVal, DestBB);
5791 return error(
"Invalid record");
5792 unsigned OpTyID =
Record[0];
5793 Type *OpTy = getTypeByID(OpTyID);
5795 if (!OpTy || !Address)
5796 return error(
"Invalid record");
5797 unsigned NumDests =
Record.size()-2;
5800 for (
unsigned i = 0, e = NumDests; i !=
e; ++i) {
5805 return error(
"Invalid record");
5815 return error(
"Invalid record");
5818 unsigned CCInfo =
Record[OpNum++];
5822 unsigned FTyID = InvalidTypeID;
5824 if ((CCInfo >> 13) & 1) {
5826 FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5828 return error(
"Explicit invoke type is not a function type");
5832 unsigned CalleeTypeID;
5833 if (getValueTypePair(
Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5835 return error(
"Invalid record");
5839 return error(
"Callee is not a pointer");
5841 FTyID = getContainedTypeID(CalleeTypeID);
5842 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5844 return error(
"Callee is not of pointer to function type");
5846 if (
Record.size() < FTy->getNumParams() + OpNum)
5847 return error(
"Insufficient operands to call");
5851 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5852 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5853 Ops.
push_back(getValue(
Record, OpNum, NextValueNo, FTy->getParamType(i),
5857 return error(
"Invalid record");
5860 if (!FTy->isVarArg()) {
5861 if (
Record.size() != OpNum)
5862 return error(
"Invalid record");
5865 while (OpNum !=
Record.size()) {
5868 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5869 return error(
"Invalid record");
5876 if (!OperandBundles.empty())
5881 ResTypeID = getContainedTypeID(FTyID);
5882 OperandBundles.clear();
5884 cast<InvokeInst>(
I)->setCallingConv(
5886 cast<InvokeInst>(
I)->setAttributes(PAL);
5887 if (
Error Err = propagateAttributeTypes(cast<CallBase>(
I), ArgTyIDs)) {
5896 Value *Val =
nullptr;
5898 if (getValueTypePair(
Record,
Idx, NextValueNo, Val, ValTypeID, CurBB))
5899 return error(
"Invalid record");
5908 unsigned CCInfo =
Record[OpNum++];
5911 unsigned NumIndirectDests =
Record[OpNum++];
5913 for (
unsigned i = 0, e = NumIndirectDests; i !=
e; ++i)
5916 unsigned FTyID = InvalidTypeID;
5920 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5922 return error(
"Explicit call type is not a function type");
5926 unsigned CalleeTypeID;
5927 if (getValueTypePair(
Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5929 return error(
"Invalid record");
5933 return error(
"Callee is not a pointer type");
5935 FTyID = getContainedTypeID(CalleeTypeID);
5936 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5938 return error(
"Callee is not of pointer to function type");
5940 if (
Record.size() < FTy->getNumParams() + OpNum)
5941 return error(
"Insufficient operands to call");
5946 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5948 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5949 if (FTy->getParamType(i)->isLabelTy())
5950 Arg = getBasicBlock(
Record[OpNum]);
5952 Arg = getValue(
Record, OpNum, NextValueNo, FTy->getParamType(i),
5955 return error(
"Invalid record");
5956 Args.push_back(Arg);
5961 if (!FTy->isVarArg()) {
5962 if (OpNum !=
Record.size())
5963 return error(
"Invalid record");
5965 while (OpNum !=
Record.size()) {
5968 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
5969 return error(
"Invalid record");
5976 if (!OperandBundles.empty())
5979 if (
auto *IA = dyn_cast<InlineAsm>(Callee)) {
5984 if (
none_of(ConstraintInfo, IsLabelConstraint)) {
5989 unsigned FirstBlockArg =
Args.size() - IndirectDests.
size();
5990 for (
unsigned ArgNo = FirstBlockArg; ArgNo <
Args.size(); ++ArgNo) {
5991 unsigned LabelNo = ArgNo - FirstBlockArg;
5992 auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
5993 if (!BA || BA->getFunction() !=
F ||
5994 LabelNo > IndirectDests.
size() ||
5995 BA->getBasicBlock() != IndirectDests[LabelNo])
5996 return error(
"callbr argument does not match indirect dest");
6001 ArgTyIDs.
erase(ArgTyIDs.
begin() + FirstBlockArg, ArgTyIDs.
end());
6005 for (
Value *Arg : Args)
6008 FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6011 std::string Constraints =
IA->getConstraintString();
6014 for (
const auto &CI : ConstraintInfo) {
6016 if (ArgNo >= FirstBlockArg)
6017 Constraints.insert(Pos,
"!");
6022 Pos = Constraints.find(
',', Pos);
6023 if (Pos == std::string::npos)
6029 IA->hasSideEffects(),
IA->isAlignStack(),
6030 IA->getDialect(),
IA->canThrow());
6036 ResTypeID = getContainedTypeID(FTyID);
6037 OperandBundles.clear();
6039 cast<CallBrInst>(
I)->setCallingConv(
6041 cast<CallBrInst>(
I)->setAttributes(PAL);
6042 if (
Error Err = propagateAttributeTypes(cast<CallBase>(
I), ArgTyIDs)) {
6054 return error(
"Invalid phi record");
6056 unsigned TyID =
Record[0];
6057 Type *Ty = getTypeByID(TyID);
6059 return error(
"Invalid phi record");
6064 size_t NumArgs = (
Record.size() - 1) / 2;
6066 if ((
Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
6068 return error(
"Invalid phi record");
6073 for (
unsigned i = 0; i != NumArgs; i++) {
6077 return error(
"Invalid phi BB");
6084 auto It =
Args.find(BB);
6085 if (It !=
Args.end()) {
6096 if (!PhiConstExprBB)
6098 EdgeBB = PhiConstExprBB;
6106 V = getValueSigned(
Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6108 V = getValue(
Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6112 return error(
"Invalid phi record");
6115 if (EdgeBB == PhiConstExprBB && !EdgeBB->
empty()) {
6116 ConstExprEdgeBBs.
insert({{BB, CurBB}, EdgeBB});
6117 PhiConstExprBB =
nullptr;
6120 Args.insert({BB,
V});
6126 if (
Record.size() % 2 == 0) {
6127 assert(isa<FPMathOperator>(
I) &&
"Unexpected phi type");
6130 I->setFastMathFlags(FMF);
6142 return error(
"Invalid record");
6146 return error(
"Invalid record");
6149 Type *Ty = getTypeByID(ResTypeID);
6151 return error(
"Invalid record");
6153 Value *PersFn =
nullptr;
6154 unsigned PersFnTypeID;
6155 if (getValueTypePair(
Record,
Idx, NextValueNo, PersFn, PersFnTypeID,
6157 return error(
"Invalid record");
6159 if (!
F->hasPersonalityFn())
6160 F->setPersonalityFn(cast<Constant>(PersFn));
6161 else if (
F->getPersonalityFn() != cast<Constant>(PersFn))
6162 return error(
"Personality function mismatch");
6169 for (
unsigned J = 0; J != NumClauses; ++J) {
6175 if (getValueTypePair(
Record,
Idx, NextValueNo, Val, ValTypeID,
6178 return error(
"Invalid record");
6182 !isa<ArrayType>(Val->
getType())) &&
6183 "Catch clause has a invalid type!");
6185 isa<ArrayType>(Val->
getType())) &&
6186 "Filter clause has invalid type!");
6197 return error(
"Invalid record");
6200 const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
6201 const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
6202 unsigned TyID =
Record[0];
6203 Type *Ty = getTypeByID(TyID);
6204 if (!Bitfield::get<APV::ExplicitType>(Rec)) {
6205 TyID = getContainedTypeID(TyID);
6206 Ty = getTypeByID(TyID);
6208 return error(
"Missing element type for old-style alloca");
6210 unsigned OpTyID =
Record[1];
6211 Type *OpTy = getTypeByID(OpTyID);
6215 Bitfield::get<APV::AlignLower>(Rec) |
6216 (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
6217 if (
Error Err = parseAlignmentValue(AlignExp,
Align)) {
6221 return error(
"Invalid record");
6224 unsigned AS =
Record.size() == 5 ?
Record[4] :
DL.getAllocaAddrSpace();
6228 return error(
"alloca of unsized type");
6230 Align =
DL.getPrefTypeAlign(Ty);
6232 if (!
Size->getType()->isIntegerTy())
6233 return error(
"alloca element count must have integer type");
6239 ResTypeID = getVirtualTypeID(AI->
getType(), TyID);
6247 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6248 (OpNum + 2 !=
Record.size() && OpNum + 3 !=
Record.size()))
6249 return error(
"Invalid record");
6251 if (!isa<PointerType>(
Op->getType()))
6252 return error(
"Load operand is not a pointer type");
6255 if (OpNum + 3 ==
Record.size()) {
6256 ResTypeID =
Record[OpNum++];
6257 Ty = getTypeByID(ResTypeID);
6259 ResTypeID = getContainedTypeID(OpTypeID);
6260 Ty = getTypeByID(ResTypeID);
6264 return error(
"Missing load type");
6266 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6274 return error(
"load of unsized type");
6276 Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6286 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB) ||
6287 (OpNum + 4 !=
Record.size() && OpNum + 5 !=
Record.size()))
6288 return error(
"Invalid record");
6290 if (!isa<PointerType>(
Op->getType()))
6291 return error(
"Load operand is not a pointer type");
6294 if (OpNum + 5 ==
Record.size()) {
6295 ResTypeID =
Record[OpNum++];
6296 Ty = getTypeByID(ResTypeID);
6298 ResTypeID = getContainedTypeID(OpTypeID);
6299 Ty = getTypeByID(ResTypeID);
6303 return error(
"Missing atomic load type");
6305 if (
Error Err = typeCheckLoadStoreInst(Ty,
Op->getType()))
6309 if (Ordering == AtomicOrdering::NotAtomic ||
6310 Ordering == AtomicOrdering::Release ||
6311 Ordering == AtomicOrdering::AcquireRelease)
6312 return error(
"Invalid record");
6313 if (Ordering != AtomicOrdering::NotAtomic &&
Record[OpNum] == 0)
6314 return error(
"Invalid record");
6321 return error(
"Alignment missing from atomic load");
6330 unsigned PtrTypeID, ValTypeID;
6331 if (getValueTypePair(
Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6332 return error(
"Invalid record");
6335 if (getValueTypePair(
Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6336 return error(
"Invalid record");
6338 ValTypeID = getContainedTypeID(PtrTypeID);
6339 if (popValue(
Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6340 ValTypeID, Val, CurBB))
6341 return error(
"Invalid record");
6344 if (OpNum + 2 !=
Record.size())
6345 return error(
"Invalid record");
6347 if (
Error Err = typeCheckLoadStoreInst(Val->
getType(),
Ptr->getType()))
6354 return error(
"store of unsized type");
6356 Align = TheModule->getDataLayout().getABITypeAlign(Val->
getType());
6366 unsigned PtrTypeID, ValTypeID;
6367 if (getValueTypePair(
Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB) ||
6368 !isa<PointerType>(
Ptr->getType()))
6369 return error(
"Invalid record");
6371 if (getValueTypePair(
Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6372 return error(
"Invalid record");
6374 ValTypeID = getContainedTypeID(PtrTypeID);
6375 if (popValue(
Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6376 ValTypeID, Val, CurBB))
6377 return error(
"Invalid record");
6380 if (OpNum + 4 !=
Record.size())
6381 return error(
"Invalid record");
6383 if (
Error Err = typeCheckLoadStoreInst(Val->
getType(),
Ptr->getType()))
6386 if (Ordering == AtomicOrdering::NotAtomic ||
6387 Ordering == AtomicOrdering::Acquire ||
6388 Ordering == AtomicOrdering::AcquireRelease)
6389 return error(
"Invalid record");
6391 if (Ordering != AtomicOrdering::NotAtomic &&
Record[OpNum] == 0)
6392 return error(
"Invalid record");
6398 return error(
"Alignment missing from atomic store");
6406 const size_t NumRecords =
Record.size();
6410 if (getValueTypePair(
Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6411 return error(
"Invalid record");
6413 if (!isa<PointerType>(
Ptr->getType()))
6414 return error(
"Cmpxchg operand is not a pointer type");
6417 unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6418 if (popValue(
Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6419 CmpTypeID, Cmp, CurBB))
6420 return error(
"Invalid record");
6423 if (popValue(
Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID,
6425 NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6426 return error(
"Invalid record");
6430 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6431 SuccessOrdering == AtomicOrdering::Unordered)
6432 return error(
"Invalid record");
6436 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(),
Ptr->getType()))
6444 if (FailureOrdering == AtomicOrdering::NotAtomic ||
6445 FailureOrdering == AtomicOrdering::Unordered)
6446 return error(
"Invalid record");
6448 const Align Alignment(
6449 TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6452 FailureOrdering, SSID);
6453 cast<AtomicCmpXchgInst>(
I)->setVolatile(
Record[OpNum]);
6455 if (NumRecords < 8) {
6459 I->insertInto(CurBB, CurBB->
end());
6461 ResTypeID = CmpTypeID;
6463 cast<AtomicCmpXchgInst>(
I)->setWeak(
Record[OpNum + 4]);
6465 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6474 const size_t NumRecords =
Record.size();
6478 if (getValueTypePair(
Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6479 return error(
"Invalid record");
6481 if (!isa<PointerType>(
Ptr->getType()))
6482 return error(
"Cmpxchg operand is not a pointer type");
6486 if (getValueTypePair(
Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6487 return error(
"Invalid record");
6489 Value *Val =
nullptr;
6490 if (popValue(
Record, OpNum, NextValueNo,
Cmp->getType(), CmpTypeID, Val,
6492 return error(
"Invalid record");
6494 if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6495 return error(
"Invalid record");
6497 const bool IsVol =
Record[OpNum];
6502 return error(
"Invalid cmpxchg success ordering");
6506 if (
Error Err = typeCheckLoadStoreInst(
Cmp->getType(),
Ptr->getType()))
6512 return error(
"Invalid cmpxchg failure ordering");
6514 const bool IsWeak =
Record[OpNum + 4];
6518 if (NumRecords == (OpNum + 6)) {
6519 if (
Error Err = parseAlignmentValue(
Record[OpNum + 5], Alignment))
6524 Align(TheModule->getDataLayout().getTypeStoreSize(
Cmp->getType()));
6527 FailureOrdering, SSID);
6528 cast<AtomicCmpXchgInst>(
I)->setVolatile(IsVol);
6529 cast<AtomicCmpXchgInst>(
I)->setWeak(IsWeak);
6532 ResTypeID = getVirtualTypeID(
I->getType(), {CmpTypeID, I1TypeID});
6541 const size_t NumRecords =
Record.size();
6546 if (getValueTypePair(
Record, OpNum, NextValueNo,
Ptr, PtrTypeID, CurBB))
6547 return error(
"Invalid record");
6549 if (!isa<PointerType>(
Ptr->getType()))
6550 return error(
"Invalid record");
6552 Value *Val =
nullptr;
6553 unsigned ValTypeID = InvalidTypeID;
6555 ValTypeID = getContainedTypeID(PtrTypeID);
6556 if (popValue(
Record, OpNum, NextValueNo,
6557 getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6558 return error(
"Invalid record");
6560 if (getValueTypePair(
Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6561 return error(
"Invalid record");
6564 if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6565 return error(
"Invalid record");
6571 return error(
"Invalid record");
6573 const bool IsVol =
Record[OpNum + 1];
6576 if (Ordering == AtomicOrdering::NotAtomic ||
6577 Ordering == AtomicOrdering::Unordered)
6578 return error(
"Invalid record");
6584 if (NumRecords == (OpNum + 5)) {
6585 if (
Error Err = parseAlignmentValue(
Record[OpNum + 4], Alignment))
6591 Align(TheModule->getDataLayout().getTypeStoreSize(Val->
getType()));
6594 ResTypeID = ValTypeID;
6595 cast<AtomicRMWInst>(
I)->setVolatile(IsVol);
6602 return error(
"Invalid record");
6604 if (Ordering == AtomicOrdering::NotAtomic ||
6605 Ordering == AtomicOrdering::Unordered ||
6606 Ordering == AtomicOrdering::Monotonic)
6607 return error(
"Invalid record");
6616 SeenDebugRecord =
true;
6619 return error(
"Invalid dbg record: missing instruction");
6622 Inst->
getParent()->insertDbgRecordBefore(
6632 SeenDebugRecord =
true;
6635 return error(
"Invalid dbg record: missing instruction");
6651 cast<DILocalVariable>(getFnMetadataByID(
Record[Slot++]));
6653 cast<DIExpression>(getFnMetadataByID(
Record[Slot++]));
6665 unsigned SlotBefore =
Slot;
6666 if (getValueTypePair(
Record, Slot, NextValueNo, V, TyID, CurBB))
6667 return error(
"Invalid dbg record: invalid value");
6669 assert((SlotBefore == Slot - 1) &&
"unexpected fwd ref");
6672 RawLocation = getFnMetadataByID(
Record[Slot++]);
6680 DbgVariableRecord::LocationType::Value);
6684 DbgVariableRecord::LocationType::Declare);
6689 cast<DIExpression>(getFnMetadataByID(
Record[Slot++]));
6704 return error(
"Invalid record");
6708 unsigned CCInfo =
Record[OpNum++];
6714 return error(
"Fast math flags indicator set for call with no FMF");
6717 unsigned FTyID = InvalidTypeID;
6721 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6723 return error(
"Explicit call type is not a function type");
6727 unsigned CalleeTypeID;
6728 if (getValueTypePair(
Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6730 return error(
"Invalid record");
6734 return error(
"Callee is not a pointer type");
6736 FTyID = getContainedTypeID(CalleeTypeID);
6737 FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6739 return error(
"Callee is not of pointer to function type");
6741 if (
Record.size() < FTy->getNumParams() + OpNum)
6742 return error(
"Insufficient operands to call");
6747 for (
unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6748 unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6749 if (FTy->getParamType(i)->isLabelTy())
6750 Args.push_back(getBasicBlock(
Record[OpNum]));
6752 Args.push_back(getValue(
Record, OpNum, NextValueNo,
6753 FTy->getParamType(i), ArgTyID, CurBB));
6756 return error(
"Invalid record");
6760 if (!FTy->isVarArg()) {
6761 if (OpNum !=
Record.size())
6762 return error(
"Invalid record");
6764 while (OpNum !=
Record.size()) {
6767 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6768 return error(
"Invalid record");
6775 if (!OperandBundles.empty())
6779 ResTypeID = getContainedTypeID(FTyID);
6780 OperandBundles.clear();
6782 cast<CallInst>(
I)->setCallingConv(
6791 cast<CallInst>(
I)->setTailCallKind(TCK);
6792 cast<CallInst>(
I)->setAttributes(PAL);
6793 if (isa<DbgInfoIntrinsic>(
I))
6794 SeenDebugIntrinsic =
true;
6795 if (
Error Err = propagateAttributeTypes(cast<CallBase>(
I), ArgTyIDs)) {
6800 if (!isa<FPMathOperator>(
I))
6801 return error(
"Fast-math-flags specified for call without "
6802 "floating-point scalar or vector return type");
6803 I->setFastMathFlags(FMF);
6809 return error(
"Invalid record");
6810 unsigned OpTyID =
Record[0];
6811 Type *OpTy = getTypeByID(OpTyID);
6812 Value *
Op = getValue(
Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6814 Type *ResTy = getTypeByID(ResTypeID);
6815 if (!OpTy || !
Op || !ResTy)
6816 return error(
"Invalid record");
6828 return error(
"Invalid record");
6830 std::vector<Value *> Inputs;
6833 while (OpNum !=
Record.size()) {
6835 if (getValueOrMetadata(
Record, OpNum, NextValueNo,
Op, CurBB))
6836 return error(
"Invalid record");
6837 Inputs.push_back(
Op);
6840 OperandBundles.emplace_back(BundleTags[
Record[0]], std::move(Inputs));
6848 if (getValueTypePair(
Record, OpNum, NextValueNo,
Op, OpTypeID, CurBB))
6849 return error(
"Invalid record");
6850 if (OpNum !=
Record.size())
6851 return error(
"Invalid record");
6854 ResTypeID = OpTypeID;
6864 return error(
"Invalid instruction with no BB");
6866 if (!OperandBundles.empty()) {
6868 return error(
"Operand bundles found with no consumer");
6870 I->insertInto(CurBB, CurBB->
end());
6873 if (
I->isTerminator()) {
6875 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
6879 if (!
I->getType()->isVoidTy()) {
6880 assert(
I->getType() == getTypeByID(ResTypeID) &&
6881 "Incorrect result type ID");
6889 if (!OperandBundles.empty())
6890 return error(
"Operand bundles found with no consumer");
6894 if (!
A->getParent()) {
6896 for (
unsigned i = ModuleValueListSize, e = ValueList.
size(); i != e; ++i){
6897 if ((
A = dyn_cast_or_null<Argument>(ValueList[i])) && !
A->getParent()) {
6902 return error(
"Never resolved value found in function");
6907 if (MDLoader->hasFwdRefs())
6908 return error(
"Invalid function metadata: outgoing forward refs");
6913 for (
const auto &Pair : ConstExprEdgeBBs) {
6918 From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
6924 ValueList.
shrinkTo(ModuleValueListSize);
6925 MDLoader->shrinkTo(ModuleMDLoaderSize);
6926 std::vector<BasicBlock*>().swap(FunctionBBs);
6931Error BitcodeReader::findFunctionInStream(
6934 while (DeferredFunctionInfoIterator->second == 0) {
6939 assert(VSTOffset == 0 || !
F->hasName());
6942 if (
Error Err = rememberAndSkipFunctionBodies())
6948SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
6951 if (Val >= SSIDs.
size())
6963 if (!
F || !
F->isMaterializable())
6967 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
6970 if (DFII->second == 0)
6971 if (
Error Err = findFunctionInStream(
F, DFII))
6975 if (
Error Err = materializeMetadata())
6979 if (
Error JumpFailed = Stream.JumpToBit(DFII->second))
6984 F->IsNewDbgInfoFormat =
true;
6986 if (
Error Err = parseFunctionBody(
F))
6988 F->setIsMaterializable(
false);
6992 if (SeenDebugIntrinsic && SeenDebugRecord)
6993 return error(
"Mixed debug intrinsics and debug records in bitcode module!");
6995 bool SeenAnyDebugInfo = SeenDebugIntrinsic || SeenDebugRecord;
6996 bool NewDbgInfoFormatDesired =
6997 SeenAnyDebugInfo ? SeenDebugRecord :
F->getParent()->IsNewDbgInfoFormat;
6998 if (SeenAnyDebugInfo) {
7007 if (NewDbgInfoFormatDesired !=
F->getParent()->IsNewDbgInfoFormat)
7008 F->getParent()->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired);
7010 F->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired);
7018 bool ModuleIsNewDbgInfoFormat =
F->getParent()->IsNewDbgInfoFormat;
7019 if (ModuleIsNewDbgInfoFormat || !SeenDebugRecord)
7020 F->setNewDbgInfoFormatFlag(ModuleIsNewDbgInfoFormat);
7022 F->setIsNewDbgInfoFormat(ModuleIsNewDbgInfoFormat);
7029 for (
auto &
I : UpgradedIntrinsics) {
7031 if (
CallInst *CI = dyn_cast<CallInst>(U))
7036 if (
DISubprogram *SP = MDLoader->lookupSubprogramForFunction(
F))
7037 F->setSubprogram(SP);
7040 if (!MDLoader->isStrippingTBAA()) {
7042 MDNode *TBAA =
I.getMetadata(LLVMContext::MD_tbaa);
7045 MDLoader->setStripTBAA(
true);
7052 if (
auto *MD =
I.getMetadata(LLVMContext::MD_prof)) {
7053 if (MD->getOperand(0) !=
nullptr && isa<MDString>(MD->getOperand(0))) {
7054 MDString *MDS = cast<MDString>(MD->getOperand(0));
7057 if (ProfName !=
"branch_weights")
7059 unsigned ExpectedNumOperands = 0;
7061 ExpectedNumOperands = BI->getNumSuccessors();
7062 else if (
SwitchInst *SI = dyn_cast<SwitchInst>(&
I))
7063 ExpectedNumOperands =
SI->getNumSuccessors();
7064 else if (isa<CallInst>(&
I))
7065 ExpectedNumOperands = 1;
7068 else if (isa<SelectInst>(&
I))
7069 ExpectedNumOperands = 2;
7076 if (MD->getNumOperands() !=
Offset + ExpectedNumOperands)
7077 I.setMetadata(LLVMContext::MD_prof,
nullptr);
7082 if (
auto *CI = dyn_cast<CallBase>(&
I)) {
7084 CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7086 for (
unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7088 CI->getArgOperand(ArgNo)->getType(),
7089 CI->getParamAttributes(ArgNo)));
7098 return materializeForwardReferencedFunctions();
7101Error BitcodeReader::materializeModule() {
7102 if (
Error Err = materializeMetadata())
7106 WillMaterializeAllForwardRefs =
true;
7111 if (
Error Err = materialize(&
F))
7117 if (LastFunctionBlockBit || NextUnreadBit)
7119 ? LastFunctionBlockBit
7125 if (!BasicBlockFwdRefs.
empty())
7126 return error(
"Never resolved function from blockaddress");
7132 for (
auto &
I : UpgradedIntrinsics) {
7133 for (
auto *U :
I.first->users()) {
7134 if (
CallInst *CI = dyn_cast<CallInst>(U))
7137 if (!
I.first->use_empty())
7138 I.first->replaceAllUsesWith(
I.second);
7139 I.first->eraseFromParent();
7141 UpgradedIntrinsics.clear();
7152std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
7153 return IdentifiedStructTypes;
7156ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7159 : BitcodeReaderBase(
std::
move(Cursor), Strtab), TheIndex(TheIndex),
7160 ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7162void ModuleSummaryIndexBitcodeReader::addThisModule() {
7167ModuleSummaryIndexBitcodeReader::getThisModule() {
7171template <
bool AllowNullValueInfo>
7172std::pair<ValueInfo, GlobalValue::GUID>
7173ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
7174 auto VGI = ValueIdToValueInfoMap[ValueId];
7179 assert(AllowNullValueInfo || std::get<0>(VGI));
7183void ModuleSummaryIndexBitcodeReader::setValueGUID(
7186 std::string GlobalId =
7189 auto OriginalNameID = ValueGUID;
7193 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
7199 ValueIdToValueInfoMap[ValueID] = std::make_pair(
7208Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7217 if (!MaybeCurrentBit)
7235 switch (
Entry.Kind) {
7238 return error(
"Malformed block");
7241 if (
Error JumpFailed = Stream.JumpToBit(CurrentBit))
7254 switch (MaybeRecord.
get()) {
7259 return error(
"Invalid record");
7260 unsigned ValueID =
Record[0];
7262 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7263 assert(VLI != ValueIdToLinkageMap.
end() &&
7264 "No linkage found for VST entry?");
7266 setValueGUID(ValueID,
ValueName, Linkage, SourceFileName);
7273 return error(
"Invalid record");
7274 unsigned ValueID =
Record[0];
7276 auto VLI = ValueIdToLinkageMap.
find(ValueID);
7277 assert(VLI != ValueIdToLinkageMap.
end() &&
7278 "No linkage found for VST entry?");
7280 setValueGUID(ValueID,
ValueName, Linkage, SourceFileName);
7286 unsigned ValueID =
Record[0];
7290 ValueIdToValueInfoMap[ValueID] =
7301Error ModuleSummaryIndexBitcodeReader::parseModule() {
7307 unsigned ValueId = 0;
7316 switch (
Entry.Kind) {
7318 return error(
"Malformed block");
7325 if (
Error Err = Stream.SkipBlock())
7330 if (
Error Err = readBlockInfo())
7336 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7337 !SeenGlobalValSummary) &&
7338 "Expected early VST parse via VSTOffset record");
7339 if (
Error Err = Stream.SkipBlock())
7345 if (!SourceFileName.
empty())
7347 assert(!SeenValueSymbolTable &&
7348 "Already read VST when parsing summary block?");
7353 if (VSTOffset > 0) {
7354 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7356 SeenValueSymbolTable =
true;
7358 SeenGlobalValSummary =
true;
7359 if (
Error Err = parseEntireSummary(
Entry.ID))
7363 if (
Error Err = parseModuleStringTable())
7374 switch (MaybeBitCode.
get()) {
7378 if (
Error Err = parseVersionRecord(
Record).takeError())
7386 return error(
"Invalid record");
7394 auto &Hash = getThisModule()->second;
7396 for (
auto &Val :
Record) {
7397 assert(!(Val >> 32) &&
"Unexpected high bits set");
7405 return error(
"Invalid record");
7409 VSTOffset =
Record[0] - 1;
7420 std::tie(
Name, GVRecord) = readNameFromStrtab(
Record);
7421 if (GVRecord.
size() <= 3)
7422 return error(
"Invalid record");
7426 ValueIdToLinkageMap[ValueId++] =
Linkage;
7430 setValueGUID(ValueId++,
Name, Linkage, SourceFileName);
7445 Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7451 bool IsOldProfileFormat,
7452 bool HasProfile,
bool HasRelBF) {
7456 if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7461 for (
unsigned I = 0, E =
Record.size();
I != E; ++
I) {
7463 bool HasTailCall =
false;
7466 if (IsOldProfileFormat) {
7470 }
else if (HasProfile)
7471 std::tie(Hotness, HasTailCall) =
7504 static_cast<size_t>(
Record[Slot + 1])};
7527 while (Slot <
Record.size())
7531std::vector<FunctionSummary::ParamAccess>
7533 auto ReadRange = [&]() {
7535 BitcodeReader::decodeSignRotatedValue(
Record.front()));
7538 BitcodeReader::decodeSignRotatedValue(
Record.front()));
7546 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7547 while (!
Record.empty()) {
7548 PendingParamAccesses.emplace_back();
7552 ParamAccess.
Use = ReadRange();
7555 for (
auto &Call : ParamAccess.
Calls) {
7558 Call.Callee = std::get<0>(getValueInfoFromValueId(
Record.front()));
7560 Call.Offsets = ReadRange();
7563 return PendingParamAccesses;
7566void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7574void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7580 static_cast<size_t>(
Record[Slot + 1])});
7583 while (Slot <
Record.size())
7584 parseTypeIdCompatibleVtableInfo(
Record, Slot, TypeId);
7593 if (RadixArray.empty()) {
7594 unsigned NumStackEntries =
Record[
I++];
7596 StackIdList.
reserve(NumStackEntries);
7597 for (
unsigned J = 0; J < NumStackEntries; J++) {
7603 unsigned RadixIndex =
Record[
I++];
7609 assert(RadixIndex < RadixArray.size());
7610 unsigned NumStackIds = RadixArray[RadixIndex++];
7611 StackIdList.
reserve(NumStackIds);
7612 while (NumStackIds--) {
7613 assert(RadixIndex < RadixArray.size());
7614 unsigned Elem = RadixArray[RadixIndex];
7615 if (
static_cast<std::make_signed_t<unsigned>
>(Elem) < 0) {
7616 RadixIndex = RadixIndex - Elem;
7617 assert(RadixIndex < RadixArray.size());
7618 Elem = RadixArray[RadixIndex];
7620 assert(
static_cast<std::make_signed_t<unsigned>
>(Elem) >= 0);
7633 unsigned FirstWORef = Refs.
size() - WOCnt;
7634 unsigned RefNo = FirstWORef - ROCnt;
7635 for (; RefNo < FirstWORef; ++RefNo)
7636 Refs[RefNo].setReadOnly();
7637 for (; RefNo < Refs.
size(); ++RefNo)
7638 Refs[RefNo].setWriteOnly();
7643Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
7644 if (
Error Err = Stream.EnterSubBlock(
ID))
7656 return error(
"Invalid Summary Block: record for version expected");
7661 return error(
"Invalid Summary Block: version expected");
7664 const bool IsOldProfileFormat =
Version == 1;
7666 return error(
"Invalid summary version " +
Twine(Version) +
7667 ". Version should be in the range [1-" +
7680 std::vector<GlobalValue::GUID> PendingTypeTests;
7681 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7682 PendingTypeCheckedLoadVCalls;
7683 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7684 PendingTypeCheckedLoadConstVCalls;
7685 std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7687 std::vector<CallsiteInfo> PendingCallsites;
7688 std::vector<AllocInfo> PendingAllocs;
7689 std::vector<uint64_t> PendingContextIds;
7697 switch (
Entry.Kind) {
7700 return error(
"Malformed block");
7719 switch (
unsigned BitCode = MaybeBitCode.
get()) {
7729 if (Version >= 11) {
7734 ValueIdToValueInfoMap[ValueID] =
7750 unsigned ValueID =
Record[0];
7752 unsigned InstCount =
Record[2];
7754 unsigned NumRefs =
Record[3];
7755 unsigned NumRORefs = 0, NumWORefs = 0;
7756 int RefListStartIndex = 4;
7760 RefListStartIndex = 5;
7763 RefListStartIndex = 6;
7766 RefListStartIndex = 7;
7777 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7779 "Record size inconsistent with number of references");
7786 IsOldProfileFormat, HasProfile, HasRelBF);
7788 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7794 !IsPrevailing(VIAndOriginalGUID.first.getGUID())) {
7795 PendingCallsites.clear();
7796 PendingAllocs.clear();
7798 auto FS = std::make_unique<FunctionSummary>(
7800 std::move(Calls), std::move(PendingTypeTests),
7801 std::move(PendingTypeTestAssumeVCalls),
7802 std::move(PendingTypeCheckedLoadVCalls),
7803 std::move(PendingTypeTestAssumeConstVCalls),
7804 std::move(PendingTypeCheckedLoadConstVCalls),
7805 std::move(PendingParamAccesses), std::move(PendingCallsites),
7806 std::move(PendingAllocs));
7807 FS->setModulePath(getThisModule()->first());
7808 FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7817 unsigned ValueID =
Record[0];
7819 unsigned AliaseeID =
Record[2];
7821 auto AS = std::make_unique<AliasSummary>(Flags);
7827 AS->setModulePath(getThisModule()->first());
7829 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7831 if (!AliaseeInModule)
7832 return error(
"Alias expects aliasee summary to be parsed");
7833 AS->setAliasee(AliaseeVI, AliaseeInModule);
7835 auto GUID = getValueInfoFromValueId(ValueID);
7836 AS->setOriginalName(std::get<1>(GUID));
7842 unsigned ValueID =
Record[0];
7844 unsigned RefArrayStart = 2;
7857 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7858 FS->setModulePath(getThisModule()->first());
7859 auto GUID = getValueInfoFromValueId(ValueID);
7860 FS->setOriginalName(std::get<1>(GUID));
7868 unsigned ValueID =
Record[0];
7871 unsigned NumRefs =
Record[3];
7872 unsigned RefListStartIndex = 4;
7873 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7878 for (
unsigned I = VTableListStartIndex, E =
Record.size();
I != E; ++
I) {
7884 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7885 VS->setModulePath(getThisModule()->first());
7886 VS->setVTableFuncs(VTableFuncs);
7887 auto GUID = getValueInfoFromValueId(ValueID);
7888 VS->setOriginalName(std::get<1>(GUID));
7900 unsigned ValueID =
Record[0];
7903 unsigned InstCount =
Record[3];
7905 unsigned NumRefs =
Record[4];
7906 unsigned NumRORefs = 0, NumWORefs = 0;
7907 int RefListStartIndex = 5;
7911 RefListStartIndex = 6;
7912 size_t NumRefsIndex = 5;
7914 unsigned NumRORefsOffset = 1;
7915 RefListStartIndex = 7;
7918 RefListStartIndex = 8;
7920 RefListStartIndex = 9;
7922 NumRORefsOffset = 2;
7925 NumRORefs =
Record[RefListStartIndex - NumRORefsOffset];
7927 NumRefs =
Record[NumRefsIndex];
7931 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7933 "Record size inconsistent with number of references");
7939 IsOldProfileFormat, HasProfile,
false);
7940 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7942 auto FS = std::make_unique<FunctionSummary>(
7944 std::move(Edges), std::move(PendingTypeTests),
7945 std::move(PendingTypeTestAssumeVCalls),
7946 std::move(PendingTypeCheckedLoadVCalls),
7947 std::move(PendingTypeTestAssumeConstVCalls),
7948 std::move(PendingTypeCheckedLoadConstVCalls),
7949 std::move(PendingParamAccesses), std::move(PendingCallsites),
7950 std::move(PendingAllocs));
7951 LastSeenSummary =
FS.get();
7952 LastSeenGUID =
VI.getGUID();
7953 FS->setModulePath(ModuleIdMap[ModuleId]);
7961 unsigned ValueID =
Record[0];
7964 unsigned AliaseeValueId =
Record[3];
7966 auto AS = std::make_unique<AliasSummary>(Flags);
7967 LastSeenSummary = AS.get();
7968 AS->setModulePath(ModuleIdMap[ModuleId]);
7970 auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
7972 AS->setAliasee(AliaseeVI, AliaseeInModule);
7974 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7975 LastSeenGUID =
VI.getGUID();
7981 unsigned ValueID =
Record[0];
7984 unsigned RefArrayStart = 3;
7997 std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7998 LastSeenSummary =
FS.get();
7999 FS->setModulePath(ModuleIdMap[ModuleId]);
8000 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8001 LastSeenGUID =
VI.getGUID();
8008 if (!LastSeenSummary)
8009 return error(
"Name attachment that does not follow a combined record");
8013 LastSeenSummary =
nullptr;
8018 assert(PendingTypeTests.empty());
8023 assert(PendingTypeTestAssumeVCalls.empty());
8024 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8025 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8029 assert(PendingTypeCheckedLoadVCalls.empty());
8030 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8031 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8035 PendingTypeTestAssumeConstVCalls.push_back(
8040 PendingTypeCheckedLoadConstVCalls.push_back(
8045 std::set<std::string, std::less<>> &CfiFunctionDefs =
8047 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8048 CfiFunctionDefs.insert(
8049 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
8054 std::set<std::string, std::less<>> &CfiFunctionDecls =
8056 for (
unsigned I = 0;
I !=
Record.size();
I += 2)
8057 CfiFunctionDecls.insert(
8058 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
8067 parseTypeIdCompatibleVtableSummaryRecord(
Record);
8075 PendingParamAccesses = parseParamAccesses(
Record);
8082 if (Version <= 11) {
8089 StackIds.reserve(
Record.size() / 2);
8090 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8091 StackIds.push_back(*R << 32 | *(R + 1));
8101 unsigned ValueID =
Record[0];
8103 for (
auto R =
Record.begin() + 1; R !=
Record.end(); R++) {
8104 assert(*R < StackIds.size());
8107 ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8108 PendingCallsites.push_back(
CallsiteInfo({
VI, std::move(StackIdList)}));
8113 auto RecordIter =
Record.begin();
8114 unsigned ValueID = *RecordIter++;
8115 unsigned NumStackIds = *RecordIter++;
8116 unsigned NumVersions = *RecordIter++;
8117 assert(
Record.size() == 3 + NumStackIds + NumVersions);
8119 for (
unsigned J = 0; J < NumStackIds; J++) {
8120 assert(*RecordIter < StackIds.size());
8125 for (
unsigned J = 0; J < NumVersions; J++)
8128 getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8129 PendingCallsites.push_back(
8130 CallsiteInfo({
VI, std::move(Versions), std::move(StackIdList)}));
8138 PendingContextIds.reserve(
Record.size() / 2);
8139 for (
auto R =
Record.begin(); R !=
Record.end(); R += 2)
8140 PendingContextIds.push_back(*R << 32 | *(R + 1));
8146 std::vector<MIBInfo> MIBs;
8147 unsigned NumMIBs = 0;
8150 unsigned MIBsRead = 0;
8151 while ((Version >= 10 && MIBsRead++ < NumMIBs) ||
8152 (Version < 10 &&
I <
Record.size())) {
8155 auto StackIdList = parseAllocInfoContext(
Record,
I);
8162 std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8164 assert(!PendingContextIds.empty() &&
8165 "Missing context ids for alloc sizes");
8166 unsigned ContextIdIndex = 0;
8172 while (MIBsRead++ < NumMIBs) {
8174 unsigned NumContextSizeInfoEntries =
Record[
I++];
8176 std::vector<ContextTotalSize> ContextSizes;
8177 ContextSizes.reserve(NumContextSizeInfoEntries);
8178 for (
unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8179 assert(ContextIdIndex < PendingContextIds.size());
8182 ContextSizes.push_back(
8183 {PendingContextIds[ContextIdIndex++],
Record[
I++]});
8185 AllContextSizes.push_back(std::move(ContextSizes));
8187 PendingContextIds.clear();
8189 PendingAllocs.push_back(
AllocInfo(std::move(MIBs)));
8190 if (!AllContextSizes.empty()) {
8191 assert(PendingAllocs.back().MIBs.size() == AllContextSizes.size());
8192 PendingAllocs.back().ContextSizeInfos = std::move(AllContextSizes);
8199 std::vector<MIBInfo> MIBs;
8200 unsigned NumMIBs =
Record[
I++];
8201 unsigned NumVersions =
Record[
I++];
8202 unsigned MIBsRead = 0;
8203 while (MIBsRead++ < NumMIBs) {
8206 auto StackIdList = parseAllocInfoContext(
Record,
I);
8211 for (
unsigned J = 0; J < NumVersions; J++)
8214 PendingAllocs.push_back(
AllocInfo(std::move(Versions), std::move(MIBs)));
8224Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8239 switch (
Entry.Kind) {
8242 return error(
"Malformed block");
8254 switch (MaybeRecord.
get()) {
8262 return error(
"Invalid record");
8264 LastSeenModule = TheIndex.
addModule(ModulePath);
8265 ModuleIdMap[ModuleId] = LastSeenModule->
first();
8274 if (!LastSeenModule)
8275 return error(
"Invalid hash that does not follow a module path");
8277 for (
auto &Val :
Record) {
8278 assert(!(Val >> 32) &&
"Unexpected high bits set");
8279 LastSeenModule->
second[Pos++] = Val;
8282 LastSeenModule =
nullptr;
8295class BitcodeErrorCategoryType :
public std::error_category {
8296 const char *
name()
const noexcept
override {
8297 return "llvm.bitcode";
8300 std::string message(
int IE)
const override {
8303 case BitcodeError::CorruptedBitcode:
8304 return "Corrupted bitcode";
8313 static BitcodeErrorCategoryType ErrorCategory;
8314 return ErrorCategory;
8318 unsigned Block,
unsigned RecordID) {
8320 return std::move(Err);
8329 switch (Entry.Kind) {
8334 return error(
"Malformed block");
8338 return std::move(Err);
8348 if (MaybeRecord.
get() == RecordID)
8363 return FOrErr.takeError();
8364 return std::move(FOrErr->Mods);
8389 switch (Entry.Kind) {
8392 return error(
"Malformed block");
8395 uint64_t IdentificationBit = -1ull;
8399 return std::move(Err);
8405 Entry = MaybeEntry.
get();
8410 return error(
"Malformed block");
8416 return std::move(Err);
8435 if (!
I.Strtab.empty())
8442 if (!
F.Symtab.empty() &&
F.StrtabForSymtab.empty())
8443 F.StrtabForSymtab = *Strtab;
8459 if (
F.Symtab.empty())
8460 F.Symtab = *SymtabOrErr;
8465 return std::move(Err);
8470 return std::move(E);
8485BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
8486 bool ShouldLazyLoadMetadata,
bool IsImporting,
8490 std::string ProducerIdentification;
8491 if (IdentificationBit != -1ull) {
8492 if (
Error JumpFailed = Stream.JumpToBit(IdentificationBit))
8493 return std::move(JumpFailed);
8496 return std::move(E);
8499 if (
Error JumpFailed = Stream.JumpToBit(ModuleBit))
8500 return std::move(JumpFailed);
8501 auto *
R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8504 std::unique_ptr<Module>
M =
8505 std::make_unique<Module>(ModuleIdentifier, Context);
8506 M->setMaterializer(R);
8509 if (
Error Err =
R->parseBitcodeInto(
M.get(), ShouldLazyLoadMetadata,
8510 IsImporting, Callbacks))
8511 return std::move(Err);
8513 if (MaterializeAll) {
8515 if (
Error Err =
M->materializeAll())
8516 return std::move(Err);
8519 if (
Error Err =
R->materializeForwardReferencedFunctions())
8520 return std::move(Err);
8523 return std::move(M);
8529 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting,
8544 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8545 ModulePath, IsPrevailing);
8546 return R.parseModule();
8553 return std::move(JumpFailed);
8555 auto Index = std::make_unique<ModuleSummaryIndex>(
false);
8556 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8557 ModuleIdentifier, 0);
8559 if (
Error Err = R.parseModule())
8560 return std::move(Err);
8562 return std::move(Index);
8570 return std::move(Err);
8575 std::pair<bool, bool> Result = {
false,
false};
8577 return std::move(E);
8579 switch (Entry.Kind) {
8582 return error(
"Malformed block");
8597 switch (MaybeBitCode.
get()) {
8603 assert(Flags <= 0x2ff &&
"Unexpected bits in flag");
8605 bool EnableSplitLTOUnit = Flags & 0x8;
8606 bool UnifiedLTO = Flags & 0x200;
8607 Result = {EnableSplitLTOUnit, UnifiedLTO};
8620 return std::move(JumpFailed);
8623 return std::move(Err);
8628 return std::move(E);
8630 switch (Entry.Kind) {
8632 return error(
"Malformed block");
8643 return Flags.takeError();
8655 return Flags.takeError();
8664 return std::move(Err);
8671 return StreamFailed.takeError();
8681 if (MsOrErr->size() != 1)
8682 return error(
"Expected a single module");
8684 return (*MsOrErr)[0];
8689 bool ShouldLazyLoadMetadata,
bool IsImporting,
8695 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8700 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
8701 bool ShouldLazyLoadMetadata,
bool IsImporting,
ParserCallbacks Callbacks) {
8703 IsImporting, Callbacks);
8705 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8711 return getModuleImpl(Context,
true,
false,
false, Callbacks);
8723 return BM->parseModule(Context, Callbacks);
8756 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8765 return BM->getSummary();
8773 return BM->getLTOInfo();
8778 bool IgnoreEmptyThinLTOIndexFile) {
8783 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
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)
cl::opt< cl::boolOrDefault > PreserveInputDbgFormat
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...
cl::opt< bool > WriteNewDbgInfoFormat
static void parseTypeIdSummaryRecord(ArrayRef< uint64_t > Record, StringRef Strtab, ModuleSummaryIndex &TheIndex)
cl::opt< cl::boolOrDefault > LoadBitcodeIntoNewDbgInfoFormat("load-bitcode-into-experimental-debuginfo-iterators", cl::Hidden, cl::desc("Load bitcode directly into the new debug info format (regardless " "of input format)"))
Load bitcode directly into RemoveDIs format (use debug records instead of debug intrinsics).
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
bool WriteNewDbgInfoFormatToBitcode
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)
cl::opt< bool > UseNewDbgInfoFormat
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
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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.
@ Min
*p = old <signed v ? old : v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ 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.
AttributeSet getFnAttrs() const
The function attributes are returned.
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute > > Attrs)
Create an AttributeList with the specified parameters in it.
static Attribute getWithStructRetType(LLVMContext &Context, Type *Ty)
static 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 Attribute getWithInAllocaType(LLVMContext &Context, Type *Ty)
static bool isIntAttrKind(AttrKind Kind)
static bool isConstantRangeListAttrKind(AttrKind Kind)
static 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.
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.
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 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.
Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO,...
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.
Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context, ParserCallbacks Callbacks={})
Read the entire bitcode module and return it.
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.
Expected< unsigned > readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
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.
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 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.
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 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 bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
static CatchPadInst * Create(Value *CatchSwitch, ArrayRef< Value * > Args, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CatchReturnInst * Create(Value *CatchPad, BasicBlock *BB, InsertPosition InsertBefore=nullptr)
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupPadInst * Create(Value *ParentPad, ArrayRef< Value * > Args={}, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
static 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 Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static 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 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 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 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 Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static 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 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 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 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 ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc)
Return a pointer signed with the specified parameters.
static bool isOrderedRanges(ArrayRef< ConstantRange > RangesRef)
This class represents a range of values.
bool isUpperSignWrapped() const
Return true if the (exclusive) upper bound wraps around the signed domain.
bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
static Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static 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 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 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 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 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...
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
void setComdat(Comdat *C)
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 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.
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
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)
void setSanitizerMetadata(SanitizerMetadata Meta)
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e....
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.
void setPartition(StringRef Part)
void setAttributes(AttributeSet A)
Set attribute list for this global.
void setCodeModel(CodeModel::Model CM)
Change the code model for this global.
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
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 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
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 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.
void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
static 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...
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.
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 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 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)
void setFlags(uint64_t Flags)
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.
std::set< std::string, std::less<> > & cfiFunctionDefs()
static constexpr uint64_t BitcodeSummaryVersion
std::set< std::string, std::less<> > & cfiFunctionDecls()
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.
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
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.
void addOperand(MDNode *M)
static 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 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.
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 StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
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...
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.
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 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.
TrailingObjects()=default
Triple - Helper class for working with autoconf configuration names.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
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 Type * getHalfTy(LLVMContext &C)
Type * getStructElementType(unsigned N) const
static Type * getDoubleTy(LLVMContext &C)
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
static Type * getX86_FP80Ty(LLVMContext &C)
bool isLabelTy() const
Return true if this is 'label'.
static Type * getBFloatTy(LLVMContext &C)
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 IntegerType * getInt1Ty(LLVMContext &C)
Type * getArrayElementType() const
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
static Type * getX86_AMXTy(LLVMContext &C)
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
static Type * getMetadataTy(LLVMContext &C)
unsigned getStructNumElements() const
uint64_t getArrayNumElements() const
TypeID
Definitions of all of the base types for the Type system.
static Type * getVoidTy(LLVMContext &C)
static Type * getLabelTy(LLVMContext &C)
bool isStructTy() const
True if this is an instance of StructType.
static Type * getFP128Ty(LLVMContext &C)
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 Type * getTokenTy(LLVMContext &C)
bool isFunctionTy() const
True if this is an instance of FunctionType.
static IntegerType * getInt32Ty(LLVMContext &C)
static Type * getFloatTy(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
static Type * getPPC_FP128Ty(LLVMContext &C)
bool isVoidTy() const
Return true if this is 'void'.
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 UnaryOperator * Create(UnaryOps Op, Value *S, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a unary instruction, given the opcode and an operand.
static 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.
void setName(const Twine &Name)
Change the name of the value.
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.
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.
@ 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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
constexpr uint8_t RecordLength
Length of the parts of a physical GOFF record.
AttributeList getAttributes(LLVMContext &C, ID id)
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_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_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.
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...
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.
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
unsigned getBranchWeightOffset(const MDNode *ProfileData)
Return the offset to the first branch weight data.
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)
bool stripDebugInfo(Function &F)
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...
bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn, bool CanUpgradeDebugIntrinsicsToRecords=true)
This is a more granular function that simply checks an intrinsic function for upgrading,...
void UpgradeAttributes(AttrBuilder &B)
Upgrade attributes that changed format or kind.
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
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.
Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
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...
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
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.
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.
Constant * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
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.
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)
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)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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.
Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
GlobalVariable * UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
AtomicOrdering
Atomic ordering for LLVM's memory model.
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)
APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
void UpgradeFunctionAttributes(Function &F)
Correct any IR that is relying on old function attribute behavior.
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...
void UpgradeARCRuntime(Module &M)
Convert calls to ARC runtime functions to intrinsic calls and upgrade the old retain release marker t...
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,...
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.
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.
Represents the EMUL and EEW of a MachineOperand.
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.
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