84 #include <system_error>
94 "Print the global id for each value when reading the module summary"));
99 SWITCH_INST_MAGIC = 0x4B5
103 return make_error<StringError>(
111 Stream.
Read(8) !=
'B' ||
112 Stream.
Read(8) !=
'C' ||
113 Stream.
Read(4) != 0x0 ||
114 Stream.
Read(4) != 0xC ||
115 Stream.
Read(4) != 0xE ||
116 Stream.
Read(4) != 0xD)
122 const unsigned char *BufPtr = (
const unsigned char *)Buffer.
getBufferStart();
123 const unsigned char *BufEnd = BufPtr + Buffer.
getBufferSize();
126 return error(
"Invalid bitcode signature");
132 return error(
"Invalid bitcode wrapper header");
135 if (!hasValidBitcodeHeader(Stream))
136 return error(
"Invalid bitcode signature");
138 return std::move(Stream);
142 template <
typename StrTy>
145 if (Idx > Record.
size())
148 for (
unsigned i = Idx, e = Record.
size(); i != e; ++i)
149 Result += (
char)Record[i];
154 void stripTBAA(
Module *M) {
156 if (
F.isMaterializable())
167 return error(
"Invalid record");
172 std::string ProducerIdentification;
177 switch (Entry.
Kind) {
180 return error(
"Malformed block");
182 return ProducerIdentification;
193 return error(
"Invalid value");
195 convertToString(Record, 0, ProducerIdentification);
198 unsigned epoch = (
unsigned)Record[0];
201 Twine(
"Incompatible epoch: Bitcode '") +
Twine(epoch) +
217 switch (Entry.
Kind) {
220 return error(
"Malformed block");
224 return readIdentificationBlock(Stream);
228 return error(
"Malformed block");
239 return error(
"Invalid record");
247 switch (Entry.
Kind) {
250 return error(
"Malformed block");
264 if (convertToString(Record, 0, S))
265 return error(
"Invalid record");
267 if (S.find(
"__DATA, __objc_catlist") != std::string::npos ||
268 S.find(
"__OBJC,__category") != std::string::npos)
284 switch (Entry.
Kind) {
286 return error(
"Malformed block");
292 return hasObjCCategoryInModule(Stream);
296 return error(
"Malformed block");
308 return error(
"Invalid record");
318 switch (Entry.
Kind) {
321 return error(
"Malformed block");
334 if (convertToString(Record, 0, S))
335 return error(
"Invalid record");
351 switch (Entry.
Kind) {
353 return error(
"Malformed block");
359 return readModuleTriple(Stream);
363 return error(
"Malformed block");
373 class BitcodeReaderBase {
376 : Stream(std::move(Stream)), Strtab(Strtab) {
386 bool UseStrtab =
false;
393 std::pair<StringRef, ArrayRef<uint64_t>>
396 bool readBlockInfo();
399 std::string ProducerIdentification;
405 std::string FullMsg = Message.
str();
406 if (!ProducerIdentification.empty())
407 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
408 LLVM_VERSION_STRING
"')";
414 if (Record.
size() < 1)
415 return error(
"Invalid record");
416 unsigned ModuleVersion = Record[0];
417 if (ModuleVersion > 2)
418 return error(
"Invalid value");
419 UseStrtab = ModuleVersion >= 2;
420 return ModuleVersion;
423 std::pair<StringRef, ArrayRef<uint64_t>>
428 if (Record[0] + Record[1] > Strtab.
size())
430 return {
StringRef(Strtab.data() + Record[0], Record[1]), Record.
slice(2)};
433 class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
435 Module *TheModule =
nullptr;
437 uint64_t NextUnreadBit = 0;
439 uint64_t LastFunctionBlockBit = 0;
440 bool SeenValueSymbolTable =
false;
441 uint64_t VSTOffset = 0;
443 std::vector<std::string> SectionTable;
444 std::vector<std::string> GCTable;
446 std::vector<Type*> TypeList;
449 std::vector<Comdat *> ComdatList;
452 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
453 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
454 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
455 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
456 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
460 std::vector<AttributeList> MAttributes;
463 std::map<unsigned, AttributeList> MAttributeGroups;
467 std::vector<BasicBlock*> FunctionBBs;
471 std::vector<Function*> FunctionsWithBodies;
476 UpdatedIntrinsicMap UpgradedIntrinsics;
478 UpdatedIntrinsicMap RemangledIntrinsics;
483 bool SeenFirstFunctionBody =
false;
492 std::vector<uint64_t> DeferredMetadataInfo;
498 std::deque<Function *> BasicBlockFwdRefQueue;
506 bool UseRelativeIDs =
false;
510 bool WillMaterializeAllForwardRefs =
false;
515 std::vector<std::string> BundleTags;
522 Error materializeForwardReferencedFunctions();
525 Error materializeModule()
override;
526 std::vector<StructType *> getIdentifiedStructTypes()
const override;
530 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata =
false,
531 bool IsImporting =
false);
533 static uint64_t decodeSignRotatedValue(uint64_t V);
536 Error materializeMetadata()
override;
538 void setStripDebugInfo()
override;
541 std::vector<StructType *> IdentifiedStructTypes;
545 Type *getTypeByID(
unsigned ID);
550 return ValueList.getValueFwdRef(ID, Ty);
553 Metadata *getFnMetadataByID(
unsigned ID) {
554 return MDLoader->getMetadataFwdRefOrLoad(ID);
557 BasicBlock *getBasicBlock(
unsigned ID)
const {
558 if (ID >= FunctionBBs.size())
return nullptr;
559 return FunctionBBs[
ID];
563 if (i-1 < MAttributes.size())
564 return MAttributes[i-1];
572 unsigned InstNum,
Value *&ResVal) {
573 if (Slot == Record.
size())
return true;
574 unsigned ValNo = (
unsigned)Record[Slot++];
577 ValNo = InstNum - ValNo;
578 if (ValNo < InstNum) {
581 ResVal = getFnValueByID(ValNo,
nullptr);
582 return ResVal ==
nullptr;
584 if (Slot == Record.
size())
587 unsigned TypeNo = (
unsigned)Record[Slot++];
588 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
589 return ResVal ==
nullptr;
596 unsigned InstNum,
Type *Ty,
Value *&ResVal) {
597 if (getValue(Record, Slot, InstNum, Ty, ResVal))
606 unsigned InstNum,
Type *Ty,
Value *&ResVal) {
607 ResVal = getValue(Record, Slot, InstNum, Ty);
608 return ResVal ==
nullptr;
614 unsigned InstNum,
Type *Ty) {
615 if (Slot == Record.
size())
return nullptr;
616 unsigned ValNo = (
unsigned)Record[Slot];
619 ValNo = InstNum - ValNo;
620 return getFnValueByID(ValNo, Ty);
625 unsigned InstNum,
Type *Ty) {
626 if (Slot == Record.
size())
return nullptr;
627 unsigned ValNo = (
unsigned)decodeSignRotatedValue(Record[Slot]);
630 ValNo = InstNum - ValNo;
631 return getFnValueByID(ValNo, Ty);
637 Error parseAlignmentValue(uint64_t
Exponent,
unsigned &Alignment);
639 Error parseModule(uint64_t ResumeBit,
bool ShouldLazyLoadMetadata =
false);
644 Error parseGlobalIndirectSymbolRecord(
unsigned BitCode,
647 Error parseAttributeBlock();
648 Error parseAttributeGroupBlock();
649 Error parseTypeTable();
650 Error parseTypeTableBody();
651 Error parseOperandBundleTags();
652 Error parseSyncScopeNames();
655 unsigned NameIndex, Triple &TT);
656 void setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
Function *
F,
659 Error parseGlobalValueSymbolTable();
660 Error parseConstants();
661 Error rememberAndSkipFunctionBodies();
662 Error rememberAndSkipFunctionBody();
664 Error rememberAndSkipMetadata();
667 Error globalCleanup();
668 Error resolveGlobalAndIndirectSymbolInits();
669 Error parseUseLists();
670 Error findFunctionInStream(
679 class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
685 bool SeenGlobalValSummary =
false;
688 bool SeenValueSymbolTable =
false;
692 uint64_t VSTOffset = 0;
703 ValueIdToValueInfoMap;
712 std::string SourceFileName;
725 StringRef ModulePath,
unsigned ModuleId);
733 Error parseValueSymbolTable(
738 bool IsOldProfileFormat,
740 Error parseEntireSummary(
unsigned ID);
741 Error parseModuleStringTable();
743 std::pair<ValueInfo, GlobalValue::GUID>
744 getValueInfoFromValueId(
unsigned ValueId);
761 return std::error_code();
767 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
769 this->ProducerIdentification = ProducerIdentification;
772 Error BitcodeReader::materializeForwardReferencedFunctions() {
773 if (WillMaterializeAllForwardRefs)
777 WillMaterializeAllForwardRefs =
true;
779 while (!BasicBlockFwdRefQueue.empty()) {
780 Function *
F = BasicBlockFwdRefQueue.front();
781 BasicBlockFwdRefQueue.pop_front();
782 assert(F &&
"Expected valid function");
783 if (!BasicBlockFwdRefs.count(F))
792 return error(
"Never resolved function from blockaddress");
795 if (
Error Err = materialize(F))
798 assert(BasicBlockFwdRefs.empty() &&
"Function missing from queue");
801 WillMaterializeAllForwardRefs =
false;
825 return GlobalValue::ExternalLinkage;
827 return GlobalValue::AppendingLinkage;
829 return GlobalValue::InternalLinkage;
831 return GlobalValue::ExternalLinkage;
833 return GlobalValue::ExternalLinkage;
835 return GlobalValue::ExternalWeakLinkage;
837 return GlobalValue::CommonLinkage;
839 return GlobalValue::PrivateLinkage;
841 return GlobalValue::AvailableExternallyLinkage;
843 return GlobalValue::PrivateLinkage;
845 return GlobalValue::PrivateLinkage;
847 return GlobalValue::ExternalLinkage;
850 return GlobalValue::WeakAnyLinkage;
853 return GlobalValue::WeakODRLinkage;
856 return GlobalValue::LinkOnceAnyLinkage;
859 return GlobalValue::LinkOnceODRLinkage;
870 RawFlags = RawFlags >> 4;
871 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
875 bool Live = (RawFlags & 0x2) || Version < 3;
882 case 0:
return GlobalValue::DefaultVisibility;
883 case 1:
return GlobalValue::HiddenVisibility;
884 case 2:
return GlobalValue::ProtectedVisibility;
892 case 0:
return GlobalValue::DefaultStorageClass;
893 case 1:
return GlobalValue::DLLImportStorageClass;
894 case 2:
return GlobalValue::DLLExportStorageClass;
900 case 0:
return GlobalVariable::NotThreadLocal;
902 case 1:
return GlobalVariable::GeneralDynamicTLSModel;
903 case 2:
return GlobalVariable::LocalDynamicTLSModel;
904 case 3:
return GlobalVariable::InitialExecTLSModel;
905 case 4:
return GlobalVariable::LocalExecTLSModel;
913 case 1:
return GlobalVariable::UnnamedAddr::Global;
914 case 2:
return GlobalVariable::UnnamedAddr::Local;
949 return IsFP ? Instruction::FSub : Instruction::Sub;
951 return IsFP ? Instruction::FMul : Instruction::Mul;
953 return IsFP ? -1 : Instruction::UDiv;
955 return IsFP ? Instruction::FDiv : Instruction::SDiv;
957 return IsFP ? -1 : Instruction::URem;
959 return IsFP ? Instruction::FRem : Instruction::SRem;
961 return IsFP ? -1 : Instruction::Shl;
963 return IsFP ? -1 : Instruction::LShr;
965 return IsFP ? -1 : Instruction::AShr;
967 return IsFP ? -1 : Instruction::And;
969 return IsFP ? -1 : Instruction::Or;
971 return IsFP ? -1 : Instruction::Xor;
977 default:
return AtomicRMWInst::BAD_BINOP;
1011 return Comdat::ExactMatch;
1013 return Comdat::Largest;
1015 return Comdat::NoDuplicates;
1017 return Comdat::SameSize;
1023 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
1025 if (0 != (Val & FastMathFlags::NoNaNs))
1027 if (0 != (Val & FastMathFlags::NoInfs))
1029 if (0 != (Val & FastMathFlags::NoSignedZeros))
1031 if (0 != (Val & FastMathFlags::AllowReciprocal))
1033 if (0 != (Val & FastMathFlags::AllowContract))
1046 Type *BitcodeReader::getTypeByID(
unsigned ID) {
1048 if (ID >= TypeList.size())
1051 if (
Type *Ty = TypeList[ID])
1056 return TypeList[
ID] = createIdentifiedStructType(
Context);
1061 auto *
Ret = StructType::create(Context, Name);
1062 IdentifiedStructTypes.push_back(
Ret);
1067 auto *
Ret = StructType::create(Context);
1068 IdentifiedStructTypes.push_back(
Ret);
1078 case Attribute::EndAttrKinds:
1082 case Attribute::ZExt:
return 1 << 0;
1083 case Attribute::SExt:
return 1 << 1;
1084 case Attribute::NoReturn:
return 1 << 2;
1085 case Attribute::InReg:
return 1 << 3;
1086 case Attribute::StructRet:
return 1 << 4;
1087 case Attribute::NoUnwind:
return 1 << 5;
1089 case Attribute::ByVal:
return 1 << 7;
1090 case Attribute::Nest:
return 1 << 8;
1091 case Attribute::ReadNone:
return 1 << 9;
1092 case Attribute::ReadOnly:
return 1 << 10;
1093 case Attribute::NoInline:
return 1 << 11;
1094 case Attribute::AlwaysInline:
return 1 << 12;
1095 case Attribute::OptimizeForSize:
return 1 << 13;
1096 case Attribute::StackProtect:
return 1 << 14;
1097 case Attribute::StackProtectReq:
return 1 << 15;
1098 case Attribute::Alignment:
return 31 << 16;
1099 case Attribute::NoCapture:
return 1 << 21;
1100 case Attribute::NoRedZone:
return 1 << 22;
1101 case Attribute::NoImplicitFloat:
return 1 << 23;
1102 case Attribute::Naked:
return 1 << 24;
1103 case Attribute::InlineHint:
return 1 << 25;
1104 case Attribute::StackAlignment:
return 7 << 26;
1105 case Attribute::ReturnsTwice:
return 1 << 29;
1106 case Attribute::UWTable:
return 1 << 30;
1107 case Attribute::NonLazyBind:
return 1U << 31;
1108 case Attribute::SanitizeAddress:
return 1ULL << 32;
1109 case Attribute::MinSize:
return 1ULL << 33;
1110 case Attribute::NoDuplicate:
return 1ULL << 34;
1111 case Attribute::StackProtectStrong:
return 1ULL << 35;
1112 case Attribute::SanitizeThread:
return 1ULL << 36;
1113 case Attribute::SanitizeMemory:
return 1ULL << 37;
1114 case Attribute::NoBuiltin:
return 1ULL << 38;
1115 case Attribute::Returned:
return 1ULL << 39;
1117 case Attribute::Builtin:
return 1ULL << 41;
1118 case Attribute::OptimizeNone:
return 1ULL << 42;
1119 case Attribute::InAlloca:
return 1ULL << 43;
1120 case Attribute::NonNull:
return 1ULL << 44;
1123 case Attribute::SafeStack:
return 1ULL << 47;
1124 case Attribute::NoRecurse:
return 1ULL << 48;
1125 case Attribute::InaccessibleMemOnly:
return 1ULL << 49;
1126 case Attribute::InaccessibleMemOrArgMemOnly:
return 1ULL << 50;
1127 case Attribute::SwiftSelf:
return 1ULL << 51;
1128 case Attribute::SwiftError:
return 1ULL << 52;
1129 case Attribute::WriteOnly:
return 1ULL << 53;
1130 case Attribute::Speculatable:
return 1ULL << 54;
1131 case Attribute::Dereferenceable:
1134 case Attribute::DereferenceableOrNull:
1138 case Attribute::ArgMemOnly:
1141 case Attribute::AllocSize:
1153 if (
I == Attribute::Dereferenceable ||
1154 I == Attribute::DereferenceableOrNull ||
1155 I == Attribute::ArgMemOnly ||
1156 I == Attribute::AllocSize)
1159 if (
I == Attribute::Alignment)
1161 else if (
I == Attribute::StackAlignment)
1173 uint64_t EncodedAttrs) {
1178 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1180 "Alignment must be a power of two.");
1185 (EncodedAttrs & 0xffff));
1188 Error BitcodeReader::parseAttributeBlock() {
1190 return error(
"Invalid record");
1192 if (!MAttributes.empty())
1193 return error(
"Invalid multiple blocks");
1203 switch (Entry.
Kind) {
1204 case BitstreamEntry::SubBlock:
1206 return error(
"Malformed block");
1207 case BitstreamEntry::EndBlock:
1209 case BitstreamEntry::Record:
1221 if (Record.
size() & 1)
1222 return error(
"Invalid record");
1224 for (
unsigned i = 0, e = Record.
size(); i != e; i += 2) {
1227 Attrs.
push_back(AttributeList::get(Context, Record[i], B));
1230 MAttributes.push_back(AttributeList::get(Context, Attrs));
1235 for (
unsigned i = 0, e = Record.
size(); i != e; ++i)
1236 Attrs.
push_back(MAttributeGroups[Record[i]]);
1238 MAttributes.push_back(AttributeList::get(Context, Attrs));
1252 return Attribute::Alignment;
1254 return Attribute::AlwaysInline;
1256 return Attribute::ArgMemOnly;
1258 return Attribute::Builtin;
1260 return Attribute::ByVal;
1262 return Attribute::InAlloca;
1268 return Attribute::InaccessibleMemOnly;
1270 return Attribute::InaccessibleMemOrArgMemOnly;
1272 return Attribute::InlineHint;
1274 return Attribute::InReg;
1278 return Attribute::MinSize;
1280 return Attribute::Naked;
1282 return Attribute::Nest;
1286 return Attribute::NoBuiltin;
1288 return Attribute::NoCapture;
1290 return Attribute::NoDuplicate;
1292 return Attribute::NoImplicitFloat;
1294 return Attribute::NoInline;
1296 return Attribute::NoRecurse;
1298 return Attribute::NonLazyBind;
1300 return Attribute::NonNull;
1302 return Attribute::Dereferenceable;
1304 return Attribute::DereferenceableOrNull;
1306 return Attribute::AllocSize;
1308 return Attribute::NoRedZone;
1310 return Attribute::NoReturn;
1312 return Attribute::NoUnwind;
1314 return Attribute::OptimizeForSize;
1316 return Attribute::OptimizeNone;
1318 return Attribute::ReadNone;
1320 return Attribute::ReadOnly;
1322 return Attribute::Returned;
1324 return Attribute::ReturnsTwice;
1326 return Attribute::SExt;
1328 return Attribute::Speculatable;
1330 return Attribute::StackAlignment;
1332 return Attribute::StackProtect;
1334 return Attribute::StackProtectReq;
1336 return Attribute::StackProtectStrong;
1338 return Attribute::SafeStack;
1340 return Attribute::StructRet;
1342 return Attribute::SanitizeAddress;
1344 return Attribute::SanitizeThread;
1346 return Attribute::SanitizeMemory;
1348 return Attribute::SwiftError;
1350 return Attribute::SwiftSelf;
1352 return Attribute::UWTable;
1354 return Attribute::WriteOnly;
1356 return Attribute::ZExt;
1360 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1361 unsigned &Alignment) {
1364 if (Exponent > Value::MaxAlignmentExponent + 1)
1365 return error(
"Invalid alignment value");
1366 Alignment = (1 <<
static_cast<unsigned>(Exponent)) >> 1;
1373 return error(
"Unknown attribute kind (" +
Twine(Code) +
")");
1377 Error BitcodeReader::parseAttributeGroupBlock() {
1379 return error(
"Invalid record");
1381 if (!MAttributeGroups.empty())
1382 return error(
"Invalid multiple blocks");
1390 switch (Entry.
Kind) {
1391 case BitstreamEntry::SubBlock:
1393 return error(
"Malformed block");
1394 case BitstreamEntry::EndBlock:
1396 case BitstreamEntry::Record:
1407 if (Record.
size() < 3)
1408 return error(
"Invalid record");
1410 uint64_t GrpID = Record[0];
1411 uint64_t Idx = Record[1];
1414 for (
unsigned i = 2, e = Record.
size(); i != e; ++i) {
1415 if (Record[i] == 0) {
1421 }
else if (Record[i] == 1) {
1425 if (Kind == Attribute::Alignment)
1427 else if (Kind == Attribute::StackAlignment)
1429 else if (Kind == Attribute::Dereferenceable)
1431 else if (Kind == Attribute::DereferenceableOrNull)
1433 else if (Kind == Attribute::AllocSize)
1436 assert((Record[i] == 3 || Record[i] == 4) &&
1437 "Invalid attribute group entry");
1438 bool HasValue = (Record[i++] == 4);
1442 while (Record[i] != 0 && i != e)
1443 KindStr += Record[i++];
1444 assert(Record[i] == 0 &&
"Kind string not null terminated");
1449 while (Record[i] != 0 && i != e)
1450 ValStr += Record[i++];
1451 assert(Record[i] == 0 &&
"Value string not null terminated");
1458 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1465 Error BitcodeReader::parseTypeTable() {
1467 return error(
"Invalid record");
1469 return parseTypeTableBody();
1472 Error BitcodeReader::parseTypeTableBody() {
1473 if (!TypeList.empty())
1474 return error(
"Invalid multiple blocks");
1477 unsigned NumRecords = 0;
1485 switch (Entry.
Kind) {
1486 case BitstreamEntry::SubBlock:
1488 return error(
"Malformed block");
1489 case BitstreamEntry::EndBlock:
1490 if (NumRecords != TypeList.size())
1491 return error(
"Malformed block");
1493 case BitstreamEntry::Record:
1500 Type *ResultTy =
nullptr;
1503 return error(
"Invalid value");
1507 if (Record.
size() < 1)
1508 return error(
"Invalid record");
1509 TypeList.resize(Record[0]);
1512 ResultTy = Type::getVoidTy(Context);
1515 ResultTy = Type::getHalfTy(Context);
1518 ResultTy = Type::getFloatTy(Context);
1521 ResultTy = Type::getDoubleTy(Context);
1524 ResultTy = Type::getX86_FP80Ty(Context);
1527 ResultTy = Type::getFP128Ty(Context);
1530 ResultTy = Type::getPPC_FP128Ty(Context);
1533 ResultTy = Type::getLabelTy(Context);
1536 ResultTy = Type::getMetadataTy(Context);
1539 ResultTy = Type::getX86_MMXTy(Context);
1542 ResultTy = Type::getTokenTy(Context);
1545 if (Record.
size() < 1)
1546 return error(
"Invalid record");
1548 uint64_t NumBits = Record[0];
1549 if (NumBits < IntegerType::MIN_INT_BITS ||
1550 NumBits > IntegerType::MAX_INT_BITS)
1551 return error(
"Bitwidth for integer type out of range");
1552 ResultTy = IntegerType::get(Context, NumBits);
1557 if (Record.
size() < 1)
1558 return error(
"Invalid record");
1560 if (Record.
size() == 2)
1561 AddressSpace = Record[1];
1562 ResultTy = getTypeByID(Record[0]);
1565 return error(
"Invalid type");
1566 ResultTy = PointerType::get(ResultTy, AddressSpace);
1572 if (Record.
size() < 3)
1573 return error(
"Invalid record");
1575 for (
unsigned i = 3, e = Record.
size(); i != e; ++i) {
1576 if (
Type *
T = getTypeByID(Record[i]))
1582 ResultTy = getTypeByID(Record[2]);
1583 if (!ResultTy || ArgTys.
size() < Record.
size()-3)
1584 return error(
"Invalid type");
1586 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1591 if (Record.
size() < 2)
1592 return error(
"Invalid record");
1594 for (
unsigned i = 2, e = Record.
size(); i != e; ++i) {
1595 if (
Type *
T = getTypeByID(Record[i])) {
1596 if (!FunctionType::isValidArgumentType(
T))
1597 return error(
"Invalid function argument type");
1604 ResultTy = getTypeByID(Record[1]);
1605 if (!ResultTy || ArgTys.
size() < Record.
size()-2)
1606 return error(
"Invalid type");
1608 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1612 if (Record.
size() < 1)
1613 return error(
"Invalid record");
1615 for (
unsigned i = 1, e = Record.
size(); i != e; ++i) {
1616 if (
Type *
T = getTypeByID(Record[i]))
1621 if (EltTys.
size() != Record.
size()-1)
1622 return error(
"Invalid type");
1623 ResultTy = StructType::get(Context, EltTys, Record[0]);
1627 if (convertToString(Record, 0, TypeName))
1628 return error(
"Invalid record");
1632 if (Record.
size() < 1)
1633 return error(
"Invalid record");
1635 if (NumRecords >= TypeList.size())
1636 return error(
"Invalid TYPE table");
1639 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1642 TypeList[NumRecords] =
nullptr;
1644 Res = createIdentifiedStructType(Context, TypeName);
1648 for (
unsigned i = 1, e = Record.
size(); i != e; ++i) {
1649 if (
Type *
T = getTypeByID(Record[i]))
1654 if (EltTys.
size() != Record.
size()-1)
1655 return error(
"Invalid record");
1656 Res->
setBody(EltTys, Record[0]);
1661 if (Record.
size() != 1)
1662 return error(
"Invalid record");
1664 if (NumRecords >= TypeList.size())
1665 return error(
"Invalid TYPE table");
1668 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1671 TypeList[NumRecords] =
nullptr;
1673 Res = createIdentifiedStructType(Context, TypeName);
1679 if (Record.
size() < 2)
1680 return error(
"Invalid record");
1681 ResultTy = getTypeByID(Record[1]);
1683 return error(
"Invalid type");
1684 ResultTy = ArrayType::get(ResultTy, Record[0]);
1687 if (Record.
size() < 2)
1688 return error(
"Invalid record");
1690 return error(
"Invalid vector length");
1691 ResultTy = getTypeByID(Record[1]);
1693 return error(
"Invalid type");
1694 ResultTy = VectorType::get(ResultTy, Record[0]);
1698 if (NumRecords >= TypeList.size())
1699 return error(
"Invalid TYPE table");
1700 if (TypeList[NumRecords])
1702 "Invalid TYPE table: Only named structs can be forward referenced");
1703 assert(ResultTy &&
"Didn't read a type?");
1704 TypeList[NumRecords++] = ResultTy;
1708 Error BitcodeReader::parseOperandBundleTags() {
1710 return error(
"Invalid record");
1712 if (!BundleTags.empty())
1713 return error(
"Invalid multiple blocks");
1720 switch (Entry.
Kind) {
1721 case BitstreamEntry::SubBlock:
1723 return error(
"Malformed block");
1724 case BitstreamEntry::EndBlock:
1726 case BitstreamEntry::Record:
1734 return error(
"Invalid record");
1737 BundleTags.emplace_back();
1738 if (convertToString(Record, 0, BundleTags.
back()))
1739 return error(
"Invalid record");
1744 Error BitcodeReader::parseSyncScopeNames() {
1746 return error(
"Invalid record");
1749 return error(
"Invalid multiple synchronization scope names blocks");
1754 switch (Entry.
Kind) {
1755 case BitstreamEntry::SubBlock:
1757 return error(
"Malformed block");
1758 case BitstreamEntry::EndBlock:
1760 return error(
"Invalid empty synchronization scope names block");
1762 case BitstreamEntry::Record:
1771 return error(
"Invalid record");
1774 if (convertToString(Record, 0, SSN))
1775 return error(
"Invalid record");
1784 unsigned NameIndex, Triple &TT) {
1786 if (convertToString(Record, NameIndex, ValueName))
1787 return error(
"Invalid record");
1788 unsigned ValueID = Record[0];
1789 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1790 return error(
"Invalid record");
1791 Value *V = ValueList[ValueID];
1794 if (NameStr.find_first_of(0) != StringRef::npos)
1795 return error(
"Invalid value name");
1799 if (GO->getComdat() ==
reinterpret_cast<Comdat *
>(1)) {
1803 GO->setComdat(TheModule->getOrInsertComdat(V->
getName()));
1820 assert(Entry.
Kind == BitstreamEntry::SubBlock);
1830 void BitcodeReader::setDeferredFunctionInfo(
unsigned FuncBitcodeOffsetDelta,
1836 uint64_t FuncWordOffset = Record[1] - 1;
1837 uint64_t FuncBitOffset = FuncWordOffset * 32;
1838 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1842 if (FuncBitOffset > LastFunctionBlockBit)
1843 LastFunctionBlockBit = FuncBitOffset;
1847 Error BitcodeReader::parseGlobalValueSymbolTable() {
1848 unsigned FuncBitcodeOffsetDelta =
1852 return error(
"Invalid record");
1858 switch (Entry.
Kind) {
1859 case BitstreamEntry::SubBlock:
1861 return error(
"Malformed block");
1862 case BitstreamEntry::EndBlock:
1864 case BitstreamEntry::Record:
1871 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1872 cast<Function>(ValueList[Record[0]]), Record);
1880 Error BitcodeReader::parseValueSymbolTable(uint64_t
Offset) {
1881 uint64_t CurrentBit;
1889 if (
Error Err = parseGlobalValueSymbolTable())
1909 unsigned FuncBitcodeOffsetDelta =
1913 return error(
"Invalid record");
1917 Triple TT(TheModule->getTargetTriple());
1925 switch (Entry.
Kind) {
1926 case BitstreamEntry::SubBlock:
1928 return error(
"Malformed block");
1929 case BitstreamEntry::EndBlock:
1933 case BitstreamEntry::Record:
1959 if (
auto *F = dyn_cast<Function>(V))
1960 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
1964 if (convertToString(Record, 1, ValueName))
1965 return error(
"Invalid record");
1968 return error(
"Invalid record");
1980 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1990 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
1991 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1992 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
1993 IndirectSymbolInitWorklist;
1994 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1995 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1996 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
1998 GlobalInitWorklist.swap(GlobalInits);
1999 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2000 FunctionPrefixWorklist.swap(FunctionPrefixes);
2001 FunctionPrologueWorklist.swap(FunctionPrologues);
2002 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2004 while (!GlobalInitWorklist.empty()) {
2005 unsigned ValID = GlobalInitWorklist.back().second;
2006 if (ValID >= ValueList.size()) {
2008 GlobalInits.push_back(GlobalInitWorklist.back());
2010 if (
Constant *
C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2011 GlobalInitWorklist.back().first->setInitializer(
C);
2013 return error(
"Expected a constant");
2015 GlobalInitWorklist.pop_back();
2018 while (!IndirectSymbolInitWorklist.empty()) {
2019 unsigned ValID = IndirectSymbolInitWorklist.back().second;
2020 if (ValID >= ValueList.size()) {
2021 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2023 Constant *
C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2025 return error(
"Expected a constant");
2028 return error(
"Alias and aliasee types don't match");
2031 IndirectSymbolInitWorklist.pop_back();
2034 while (!FunctionPrefixWorklist.empty()) {
2035 unsigned ValID = FunctionPrefixWorklist.back().second;
2036 if (ValID >= ValueList.size()) {
2037 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2039 if (
Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2040 FunctionPrefixWorklist.back().first->setPrefixData(C);
2042 return error(
"Expected a constant");
2044 FunctionPrefixWorklist.pop_back();
2047 while (!FunctionPrologueWorklist.empty()) {
2048 unsigned ValID = FunctionPrologueWorklist.back().second;
2049 if (ValID >= ValueList.size()) {
2050 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2052 if (
Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2053 FunctionPrologueWorklist.back().first->setPrologueData(C);
2055 return error(
"Expected a constant");
2057 FunctionPrologueWorklist.pop_back();
2060 while (!FunctionPersonalityFnWorklist.empty()) {
2061 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2062 if (ValID >= ValueList.size()) {
2063 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2065 if (
Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2066 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2068 return error(
"Expected a constant");
2070 FunctionPersonalityFnWorklist.pop_back();
2079 BitcodeReader::decodeSignRotatedValue);
2081 return APInt(TypeBits, Words);
2084 Error BitcodeReader::parseConstants() {
2086 return error(
"Invalid record");
2091 Type *CurTy = Type::getInt32Ty(Context);
2092 unsigned NextCstNo = ValueList.size();
2097 switch (Entry.
Kind) {
2098 case BitstreamEntry::SubBlock:
2100 return error(
"Malformed block");
2101 case BitstreamEntry::EndBlock:
2102 if (NextCstNo != ValueList.size())
2103 return error(
"Invalid constant reference");
2107 ValueList.resolveConstantForwardRefs();
2109 case BitstreamEntry::Record:
2116 Type *VoidType = Type::getVoidTy(Context);
2118 unsigned BitCode = Stream.
readRecord(Entry.
ID, Record);
2122 V = UndefValue::get(CurTy);
2126 return error(
"Invalid record");
2127 if (Record[0] >= TypeList.
size() || !TypeList[Record[0]])
2128 return error(
"Invalid record");
2129 if (TypeList[Record[0]] == VoidType)
2130 return error(
"Invalid constant type");
2131 CurTy = TypeList[Record[0]];
2134 V = Constant::getNullValue(CurTy);
2138 return error(
"Invalid record");
2139 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2143 return error(
"Invalid record");
2147 V = ConstantInt::get(Context, VInt);
2153 return error(
"Invalid record");
2155 V = ConstantFP::get(Context,
APFloat(APFloat::IEEEhalf(),
2156 APInt(16, (uint16_t)Record[0])));
2158 V = ConstantFP::get(Context,
APFloat(APFloat::IEEEsingle(),
2161 V = ConstantFP::get(Context,
APFloat(APFloat::IEEEdouble(),
2162 APInt(64, Record[0])));
2165 uint64_t Rearrange[2];
2166 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2167 Rearrange[1] = Record[0] >> 48;
2168 V = ConstantFP::get(Context,
APFloat(APFloat::x87DoubleExtended(),
2169 APInt(80, Rearrange)));
2171 V = ConstantFP::get(Context,
APFloat(APFloat::IEEEquad(),
2172 APInt(128, Record)));
2174 V = ConstantFP::get(Context,
APFloat(APFloat::PPCDoubleDouble(),
2175 APInt(128, Record)));
2177 V = UndefValue::get(CurTy);
2183 return error(
"Invalid record");
2185 unsigned Size = Record.size();
2188 if (
StructType *STy = dyn_cast<StructType>(CurTy)) {
2189 for (
unsigned i = 0; i !=
Size; ++i)
2190 Elts.
push_back(ValueList.getConstantFwdRef(Record[i],
2191 STy->getElementType(i)));
2192 V = ConstantStruct::get(STy, Elts);
2193 }
else if (
ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2194 Type *EltTy = ATy->getElementType();
2195 for (
unsigned i = 0; i !=
Size; ++i)
2196 Elts.
push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2197 V = ConstantArray::get(ATy, Elts);
2198 }
else if (
VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2199 Type *EltTy = VTy->getElementType();
2200 for (
unsigned i = 0; i !=
Size; ++i)
2201 Elts.
push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2202 V = ConstantVector::get(Elts);
2204 V = UndefValue::get(CurTy);
2211 return error(
"Invalid record");
2214 V = ConstantDataArray::getString(Context, Elts,
2220 return error(
"Invalid record");
2222 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2225 if (isa<VectorType>(CurTy))
2226 V = ConstantDataVector::get(Context, Elts);
2228 V = ConstantDataArray::get(Context, Elts);
2231 if (isa<VectorType>(CurTy))
2232 V = ConstantDataVector::get(Context, Elts);
2234 V = ConstantDataArray::get(Context, Elts);
2237 if (isa<VectorType>(CurTy))
2238 V = ConstantDataVector::get(Context, Elts);
2240 V = ConstantDataArray::get(Context, Elts);
2243 if (isa<VectorType>(CurTy))
2244 V = ConstantDataVector::get(Context, Elts);
2246 V = ConstantDataArray::get(Context, Elts);
2249 if (isa<VectorType>(CurTy))
2250 V = ConstantDataVector::getFP(Context, Elts);
2252 V = ConstantDataArray::getFP(Context, Elts);
2255 if (isa<VectorType>(CurTy))
2256 V = ConstantDataVector::getFP(Context, Elts);
2258 V = ConstantDataArray::getFP(Context, Elts);
2261 if (isa<VectorType>(CurTy))
2262 V = ConstantDataVector::getFP(Context, Elts);
2264 V = ConstantDataArray::getFP(Context, Elts);
2266 return error(
"Invalid type for value");
2271 if (Record.size() < 3)
2272 return error(
"Invalid record");
2275 V = UndefValue::get(CurTy);
2277 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2278 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2280 if (Record.size() >= 4) {
2282 Opc == Instruction::Sub ||
2283 Opc == Instruction::Mul ||
2284 Opc == Instruction::Shl) {
2286 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2288 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2289 }
else if (Opc == Instruction::SDiv ||
2290 Opc == Instruction::UDiv ||
2291 Opc == Instruction::LShr ||
2292 Opc == Instruction::AShr) {
2294 Flags |= SDivOperator::IsExact;
2297 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2302 if (Record.size() < 3)
2303 return error(
"Invalid record");
2306 V = UndefValue::get(CurTy);
2308 Type *OpTy = getTypeByID(Record[1]);
2310 return error(
"Invalid record");
2311 Constant *
Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2313 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2322 Type *PointeeType =
nullptr;
2325 PointeeType = getTypeByID(Record[OpNum++]);
2327 bool InBounds =
false;
2330 uint64_t Op = Record[OpNum++];
2332 InRangeIndex = Op >> 1;
2337 while (OpNum != Record.size()) {
2338 Type *ElTy = getTypeByID(Record[OpNum++]);
2340 return error(
"Invalid record");
2341 Elts.
push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2346 cast<PointerType>(Elts[0]->
getType()->getScalarType())
2348 return error(
"Explicit gep operator type does not match pointee type "
2349 "of pointer operand");
2351 if (Elts.
size() < 1)
2352 return error(
"Invalid gep with no operands");
2355 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2356 InBounds, InRangeIndex);
2360 if (Record.size() < 3)
2361 return error(
"Invalid record");
2363 Type *SelectorTy = Type::getInt1Ty(Context);
2367 if (
VectorType *VTy = dyn_cast<VectorType>(CurTy))
2368 if (
Value *V = ValueList[Record[0]])
2369 if (SelectorTy != V->
getType())
2370 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2372 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2374 ValueList.getConstantFwdRef(Record[1],CurTy),
2375 ValueList.getConstantFwdRef(Record[2],CurTy));
2380 if (Record.size() < 3)
2381 return error(
"Invalid record");
2383 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2385 return error(
"Invalid record");
2386 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2388 if (Record.size() == 4) {
2389 Type *IdxTy = getTypeByID(Record[2]);
2391 return error(
"Invalid record");
2392 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2394 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2396 return error(
"Invalid record");
2397 V = ConstantExpr::getExtractElement(Op0, Op1);
2403 if (Record.size() < 3 || !OpTy)
2404 return error(
"Invalid record");
2405 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2406 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2409 if (Record.size() == 4) {
2410 Type *IdxTy = getTypeByID(Record[2]);
2412 return error(
"Invalid record");
2413 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2415 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2417 return error(
"Invalid record");
2418 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2423 if (Record.size() < 3 || !OpTy)
2424 return error(
"Invalid record");
2425 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2426 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2427 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2429 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2430 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2436 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2437 if (Record.size() < 4 || !RTy || !OpTy)
2438 return error(
"Invalid record");
2439 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2440 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2441 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2443 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2444 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2448 if (Record.size() < 4)
2449 return error(
"Invalid record");
2450 Type *OpTy = getTypeByID(Record[0]);
2452 return error(
"Invalid record");
2453 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2454 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2457 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2459 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2465 if (Record.size() < 2)
2466 return error(
"Invalid record");
2467 std::string AsmStr, ConstrStr;
2468 bool HasSideEffects = Record[0] & 1;
2469 bool IsAlignStack = Record[0] >> 1;
2470 unsigned AsmStrSize = Record[1];
2471 if (2+AsmStrSize >= Record.size())
2472 return error(
"Invalid record");
2473 unsigned ConstStrSize = Record[2+AsmStrSize];
2474 if (3+AsmStrSize+ConstStrSize > Record.size())
2475 return error(
"Invalid record");
2477 for (
unsigned i = 0; i != AsmStrSize; ++i)
2478 AsmStr += (
char)Record[2+i];
2479 for (
unsigned i = 0; i != ConstStrSize; ++i)
2480 ConstrStr += (
char)Record[3+AsmStrSize+i];
2483 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2489 if (Record.size() < 2)
2490 return error(
"Invalid record");
2491 std::string AsmStr, ConstrStr;
2492 bool HasSideEffects = Record[0] & 1;
2493 bool IsAlignStack = (Record[0] >> 1) & 1;
2494 unsigned AsmDialect = Record[0] >> 2;
2495 unsigned AsmStrSize = Record[1];
2496 if (2+AsmStrSize >= Record.size())
2497 return error(
"Invalid record");
2498 unsigned ConstStrSize = Record[2+AsmStrSize];
2499 if (3+AsmStrSize+ConstStrSize > Record.size())
2500 return error(
"Invalid record");
2502 for (
unsigned i = 0; i != AsmStrSize; ++i)
2503 AsmStr += (
char)Record[2+i];
2504 for (
unsigned i = 0; i != ConstStrSize; ++i)
2505 ConstrStr += (
char)Record[3+AsmStrSize+i];
2508 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2513 if (Record.size() < 3)
2514 return error(
"Invalid record");
2515 Type *FnTy = getTypeByID(Record[0]);
2517 return error(
"Invalid record");
2519 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2521 return error(
"Invalid record");
2526 unsigned BBID = Record[2];
2529 return error(
"Invalid ID");
2532 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
2534 return error(
"Invalid ID");
2541 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2543 BasicBlockFwdRefQueue.push_back(Fn);
2544 if (FwdBBs.size() < BBID + 1)
2545 FwdBBs.resize(BBID + 1);
2547 FwdBBs[BBID] = BasicBlock::Create(Context);
2550 V = BlockAddress::get(Fn, BB);
2555 ValueList.assignValue(V, NextCstNo);
2560 Error BitcodeReader::parseUseLists() {
2562 return error(
"Invalid record");
2570 switch (Entry.
Kind) {
2571 case BitstreamEntry::SubBlock:
2573 return error(
"Malformed block");
2574 case BitstreamEntry::EndBlock:
2576 case BitstreamEntry::Record:
2591 unsigned RecordLength = Record.
size();
2592 if (RecordLength < 3)
2594 return error(
"Invalid record");
2595 unsigned ID = Record.
back();
2600 assert(ID < FunctionBBs.size() &&
"Basic block not found");
2601 V = FunctionBBs[
ID];
2604 unsigned NumUses = 0;
2607 if (++NumUses > Record.
size())
2609 Order[&U] = Record[NumUses - 1];
2611 if (Order.
size() != Record.
size() || NumUses > Record.
size())
2627 Error BitcodeReader::rememberAndSkipMetadata() {
2630 DeferredMetadataInfo.push_back(CurBit);
2634 return error(
"Invalid record");
2638 Error BitcodeReader::materializeMetadata() {
2639 for (uint64_t BitPos : DeferredMetadataInfo) {
2642 if (
Error Err = MDLoader->parseModuleMetadata())
2648 if (
Metadata *Val = TheModule->getModuleFlag(
"Linker Options")) {
2650 TheModule->getOrInsertNamedMetadata(
"llvm.linker.options");
2651 for (
const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2652 LinkerOpts->
addOperand(cast<MDNode>(MDOptions));
2655 DeferredMetadataInfo.clear();
2659 void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
2663 Error BitcodeReader::rememberAndSkipFunctionBody() {
2665 if (FunctionsWithBodies.empty())
2666 return error(
"Insufficient function protos");
2669 FunctionsWithBodies.pop_back();
2674 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2675 "Mismatch between VST and scanned function offsets");
2676 DeferredFunctionInfo[Fn] = CurBit;
2680 return error(
"Invalid record");
2684 Error BitcodeReader::globalCleanup() {
2686 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
2688 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2689 return error(
"Malformed global initializer set");
2693 MDLoader->upgradeDebugIntrinsics(F);
2696 UpgradedIntrinsics[&
F] = NewFn;
2701 RemangledIntrinsics[&
F] = Remangled.getValue();
2710 std::vector<std::pair<GlobalVariable*, unsigned> >().
swap(GlobalInits);
2711 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().
swap(
2712 IndirectSymbolInits);
2720 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2724 return error(
"Could not find function in stream");
2726 if (!SeenFirstFunctionBody)
2727 return error(
"Trying to materialize functions before seeing function blocks");
2731 assert(SeenValueSymbolTable);
2737 switch (Entry.
Kind) {
2739 return error(
"Expect SubBlock");
2740 case BitstreamEntry::SubBlock:
2743 return error(
"Expect function block");
2745 if (
Error Err = rememberAndSkipFunctionBody())
2754 bool BitcodeReaderBase::readBlockInfo() {
2758 BlockInfo = std::move(*NewBlockInfo);
2766 std::tie(Name, Record) = readNameFromStrtab(Record);
2768 if (Record.
size() < 1)
2769 return error(
"Invalid record");
2771 std::string OldFormatName;
2773 if (Record.
size() < 2)
2774 return error(
"Invalid record");
2775 unsigned ComdatNameSize = Record[1];
2776 OldFormatName.reserve(ComdatNameSize);
2777 for (
unsigned i = 0; i != ComdatNameSize; ++i)
2778 OldFormatName += (
char)Record[2 + i];
2779 Name = OldFormatName;
2781 Comdat *C = TheModule->getOrInsertComdat(Name);
2783 ComdatList.push_back(C);
2793 std::tie(Name, Record) = readNameFromStrtab(Record);
2795 if (Record.
size() < 6)
2796 return error(
"Invalid record");
2797 Type *Ty = getTypeByID(Record[0]);
2799 return error(
"Invalid record");
2801 bool explicitType = Record[1] & 2;
2804 AddressSpace = Record[1] >> 2;
2807 return error(
"Invalid type for value");
2808 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2809 Ty = cast<PointerType>(Ty)->getElementType();
2812 uint64_t RawLinkage = Record[3];
2815 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
2819 if (Record[5] - 1 >= SectionTable.
size())
2820 return error(
"Invalid ID");
2821 Section = SectionTable[Record[5] - 1];
2825 if (Record.
size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2829 GlobalVariable::ThreadLocalMode
TLM = GlobalVariable::NotThreadLocal;
2830 if (Record.
size() > 7)
2834 if (Record.
size() > 8)
2837 bool ExternallyInitialized =
false;
2838 if (Record.
size() > 9)
2839 ExternallyInitialized = Record[9];
2842 new GlobalVariable(*TheModule, Ty, isConstant, Linkage,
nullptr, Name,
2843 nullptr, TLM, AddressSpace, ExternallyInitialized);
2845 if (!Section.empty())
2850 if (Record.
size() > 10)
2855 ValueList.push_back(NewGV);
2858 if (
unsigned InitID = Record[2])
2859 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2861 if (Record.
size() > 11) {
2862 if (
unsigned ComdatID = Record[11]) {
2863 if (ComdatID > ComdatList.size())
2864 return error(
"Invalid global variable comdat ID");
2865 NewGV->
setComdat(ComdatList[ComdatID - 1]);
2868 NewGV->
setComdat(reinterpret_cast<Comdat *>(1));
2871 if (Record.
size() > 12) {
2884 std::tie(Name, Record) = readNameFromStrtab(Record);
2886 if (Record.
size() < 8)
2887 return error(
"Invalid record");
2888 Type *Ty = getTypeByID(Record[0]);
2890 return error(
"Invalid record");
2891 if (
auto *PTy = dyn_cast<PointerType>(Ty))
2895 return error(
"Invalid type for value");
2898 return error(
"Invalid calling convention ID");
2901 Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule);
2904 bool isProto = Record[2];
2905 uint64_t RawLinkage = Record[3];
2910 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
2914 if (Record[6] - 1 >= SectionTable.
size())
2915 return error(
"Invalid ID");
2916 Func->
setSection(SectionTable[Record[6] - 1]);
2922 if (Record.
size() > 8 && Record[8]) {
2923 if (Record[8] - 1 >= GCTable.
size())
2924 return error(
"Invalid ID");
2925 Func->
setGC(GCTable[Record[8] - 1]);
2928 if (Record.
size() > 9)
2931 if (Record.
size() > 10 && Record[10] != 0)
2932 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
2934 if (Record.
size() > 11)
2939 if (Record.
size() > 12) {
2940 if (
unsigned ComdatID = Record[12]) {
2941 if (ComdatID > ComdatList.size())
2942 return error(
"Invalid function comdat ID");
2943 Func->
setComdat(ComdatList[ComdatID - 1]);
2946 Func->
setComdat(reinterpret_cast<Comdat *>(1));
2949 if (Record.
size() > 13 && Record[13] != 0)
2950 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
2952 if (Record.
size() > 14 && Record[14] != 0)
2953 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2955 ValueList.push_back(Func);
2961 FunctionsWithBodies.push_back(Func);
2962 DeferredFunctionInfo[Func] = 0;
2967 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
2976 std::tie(Name, Record) = readNameFromStrtab(Record);
2980 return error(
"Invalid record");
2982 Type *Ty = getTypeByID(Record[OpNum++]);
2984 return error(
"Invalid record");
2990 return error(
"Invalid type for value");
2994 AddrSpace = Record[OpNum++];
2997 auto Val = Record[OpNum++];
2998 auto Linkage = Record[OpNum++];
3006 nullptr, TheModule);
3009 if (OpNum != Record.
size()) {
3010 auto VisInd = OpNum++;
3015 if (OpNum != Record.
size())
3019 if (OpNum != Record.
size())
3021 if (OpNum != Record.
size())
3023 ValueList.push_back(NewGA);
3024 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3028 Error BitcodeReader::parseModule(uint64_t ResumeBit,
3029 bool ShouldLazyLoadMetadata) {
3033 return error(
"Invalid record");
3041 switch (Entry.
Kind) {
3043 return error(
"Malformed block");
3044 case BitstreamEntry::EndBlock:
3045 return globalCleanup();
3047 case BitstreamEntry::SubBlock:
3051 return error(
"Invalid record");
3054 if (readBlockInfo())
3055 return error(
"Malformed block");
3058 if (
Error Err = parseAttributeBlock())
3062 if (
Error Err = parseAttributeGroupBlock())
3066 if (
Error Err = parseTypeTable())
3070 if (!SeenValueSymbolTable) {
3076 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3077 if (
Error Err = parseValueSymbolTable())
3079 SeenValueSymbolTable =
true;
3085 return error(
"Invalid record");
3089 if (
Error Err = parseConstants())
3091 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
3095 if (ShouldLazyLoadMetadata) {
3096 if (
Error Err = rememberAndSkipMetadata())
3100 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
3101 if (
Error Err = MDLoader->parseModuleMetadata())
3105 if (
Error Err = MDLoader->parseMetadataKinds())
3111 if (!SeenFirstFunctionBody) {
3112 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3113 if (
Error Err = globalCleanup())
3115 SeenFirstFunctionBody =
true;
3118 if (VSTOffset > 0) {
3122 if (!SeenValueSymbolTable) {
3123 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3125 SeenValueSymbolTable =
true;
3138 return error(
"Invalid record");
3147 if (
Error Err = rememberAndSkipFunctionBody())
3154 if (SeenValueSymbolTable) {
3158 return globalCleanup();
3162 if (
Error Err = parseUseLists())
3166 if (
Error Err = parseOperandBundleTags())
3170 if (
Error Err = parseSyncScopeNames())
3176 case BitstreamEntry::Record:
3189 UseRelativeIDs = *VersionOrErr >= 1;
3194 if (convertToString(Record, 0, S))
3195 return error(
"Invalid record");
3196 TheModule->setTargetTriple(S);
3201 if (convertToString(Record, 0, S))
3202 return error(
"Invalid record");
3203 TheModule->setDataLayout(S);
3208 if (convertToString(Record, 0, S))
3209 return error(
"Invalid record");
3210 TheModule->setModuleInlineAsm(S);
3216 if (convertToString(Record, 0, S))
3217 return error(
"Invalid record");
3223 if (convertToString(Record, 0, S))
3224 return error(
"Invalid record");
3225 SectionTable.push_back(S);
3230 if (convertToString(Record, 0, S))
3231 return error(
"Invalid record");
3232 GCTable.push_back(S);
3236 if (
Error Err = parseComdatRecord(Record))
3241 if (
Error Err = parseGlobalVarRecord(Record))
3246 if (
Error Err = parseFunctionRecord(Record))
3253 if (
Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3259 if (Record.
size() < 1)
3260 return error(
"Invalid record");
3264 VSTOffset = Record[0] - 1;
3269 if (convertToString(Record, 0, ValueName))
3270 return error(
"Invalid record");
3271 TheModule->setSourceFileName(ValueName);
3278 Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
3282 [&](
unsigned ID) {
return getTypeByID(ID); });
3283 return parseModule(0, ShouldLazyLoadMetadata);
3288 if (!isa<PointerType>(PtrType))
3289 return error(
"Load/Store operand is not a pointer type");
3290 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3292 if (ValType && ValType != ElemType)
3293 return error(
"Explicit load/store type does not match pointee "
3294 "type of pointer operand");
3295 if (!PointerType::isLoadableOrStorableType(ElemType))
3296 return error(
"Cannot load/store from pointer");
3303 return error(
"Invalid record");
3306 if (MDLoader->hasFwdRefs())
3307 return error(
"Invalid function metadata: incoming forward references");
3309 InstructionList.clear();
3310 unsigned ModuleValueListSize = ValueList.size();
3311 unsigned ModuleMDLoaderSize = MDLoader->size();
3315 ValueList.push_back(&
I);
3317 unsigned NextValueNo = ValueList.size();
3319 unsigned CurBBNo = 0;
3322 auto getLastInstruction = [&]() ->
Instruction * {
3323 if (CurBB && !CurBB->
empty())
3324 return &CurBB->
back();
3325 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3326 !FunctionBBs[CurBBNo - 1]->empty())
3327 return &FunctionBBs[CurBBNo - 1]->back();
3331 std::vector<OperandBundleDef> OperandBundles;
3339 switch (Entry.
Kind) {
3341 return error(
"Malformed block");
3342 case BitstreamEntry::EndBlock:
3343 goto OutOfRecordLoop;
3345 case BitstreamEntry::SubBlock:
3349 return error(
"Invalid record");
3352 if (
Error Err = parseConstants())
3354 NextValueNo = ValueList.size();
3357 if (
Error Err = parseValueSymbolTable())
3361 if (
Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3365 assert(DeferredMetadataInfo.empty() &&
3366 "Must read all module-level metadata before function-level");
3367 if (
Error Err = MDLoader->parseFunctionMetadata())
3371 if (
Error Err = parseUseLists())
3377 case BitstreamEntry::Record:
3385 unsigned BitCode = Stream.
readRecord(Entry.
ID, Record);
3388 return error(
"Invalid value");
3390 if (Record.
size() < 1 || Record[0] == 0)
3391 return error(
"Invalid record");
3393 FunctionBBs.resize(Record[0]);
3396 auto BBFRI = BasicBlockFwdRefs.find(F);
3397 if (BBFRI == BasicBlockFwdRefs.end()) {
3398 for (
unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3399 FunctionBBs[i] = BasicBlock::Create(Context,
"", F);
3401 auto &BBRefs = BBFRI->second;
3403 if (BBRefs.size() > FunctionBBs.size())
3404 return error(
"Invalid ID");
3405 assert(!BBRefs.empty() &&
"Unexpected empty array");
3406 assert(!BBRefs.front() &&
"Invalid reference to entry block");
3407 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size(); I !=
E;
3409 if (I < RE && BBRefs[I]) {
3410 BBRefs[
I]->insertInto(F);
3411 FunctionBBs[
I] = BBRefs[
I];
3413 FunctionBBs[
I] = BasicBlock::Create(Context,
"", F);
3417 BasicBlockFwdRefs.erase(BBFRI);
3420 CurBB = FunctionBBs[0];
3427 I = getLastInstruction();
3430 return error(
"Invalid record");
3431 I->setDebugLoc(LastLoc);
3436 I = getLastInstruction();
3437 if (!I || Record.
size() < 4)
3438 return error(
"Invalid record");
3440 unsigned Line = Record[0], Col = Record[1];
3441 unsigned ScopeID = Record[2], IAID = Record[3];
3443 MDNode *Scope =
nullptr, *IA =
nullptr;
3445 Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
3447 return error(
"Invalid record");
3450 IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
3452 return error(
"Invalid record");
3454 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3455 I->setDebugLoc(LastLoc);
3463 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3464 popValue(Record, OpNum, NextValueNo, LHS->
getType(), RHS) ||
3465 OpNum+1 > Record.
size())
3466 return error(
"Invalid record");
3470 return error(
"Invalid record");
3472 InstructionList.push_back(I);
3473 if (OpNum < Record.
size()) {
3475 Opc == Instruction::Sub ||
3476 Opc == Instruction::Mul ||
3477 Opc == Instruction::Shl) {
3479 cast<BinaryOperator>(I)->setHasNoSignedWrap(
true);
3481 cast<BinaryOperator>(
I)->setHasNoUnsignedWrap(
true);
3482 }
else if (Opc == Instruction::SDiv ||
3483 Opc == Instruction::UDiv ||
3484 Opc == Instruction::LShr ||
3485 Opc == Instruction::AShr) {
3487 cast<BinaryOperator>(
I)->setIsExact(
true);
3488 }
else if (isa<FPMathOperator>(I)) {
3491 I->setFastMathFlags(FMF);
3500 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3501 OpNum+2 != Record.
size())
3502 return error(
"Invalid record");
3504 Type *ResTy = getTypeByID(Record[OpNum]);
3506 if (Opc == -1 || !ResTy)
3507 return error(
"Invalid record");
3511 InstructionList.push_back(Temp);
3516 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3517 return error(
"Invalid cast");
3518 I = CastInst::Create(CastOp, Op, ResTy);
3520 InstructionList.push_back(I);
3532 InBounds = Record[OpNum++];
3533 Ty = getTypeByID(Record[OpNum++]);
3540 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3541 return error(
"Invalid record");
3550 "Explicit gep type does not match pointee type of pointer operand");
3553 while (OpNum != Record.
size()) {
3555 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3556 return error(
"Invalid record");
3560 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3562 InstructionList.push_back(I);
3564 cast<GetElementPtrInst>(
I)->setIsInBounds(
true);
3572 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3573 return error(
"Invalid record");
3575 unsigned RecSize = Record.
size();
3576 if (OpNum == RecSize)
3577 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
3581 for (; OpNum != RecSize; ++OpNum) {
3584 uint64_t Index = Record[OpNum];
3586 if (!IsStruct && !IsArray)
3587 return error(
"EXTRACTVAL: Invalid type");
3588 if ((
unsigned)Index != Index)
3589 return error(
"Invalid value");
3590 if (IsStruct && Index >= CurTy->
subtypes().size())
3591 return error(
"EXTRACTVAL: Invalid struct index");
3593 return error(
"EXTRACTVAL: Invalid array index");
3594 EXTRACTVALIdx.
push_back((
unsigned)Index);
3602 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3603 InstructionList.push_back(I);
3611 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3612 return error(
"Invalid record");
3614 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3615 return error(
"Invalid record");
3617 unsigned RecSize = Record.
size();
3618 if (OpNum == RecSize)
3619 return error(
"INSERTVAL: Invalid instruction with 0 indices");
3623 for (; OpNum != RecSize; ++OpNum) {
3626 uint64_t Index = Record[OpNum];
3628 if (!IsStruct && !IsArray)
3629 return error(
"INSERTVAL: Invalid type");
3630 if ((
unsigned)Index != Index)
3631 return error(
"Invalid value");
3632 if (IsStruct && Index >= CurTy->
subtypes().size())
3633 return error(
"INSERTVAL: Invalid struct index");
3635 return error(
"INSERTVAL: Invalid array index");
3637 INSERTVALIdx.
push_back((
unsigned)Index);
3645 return error(
"Inserted value type doesn't match aggregate type");
3647 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3648 InstructionList.push_back(I);
3656 Value *TrueVal, *FalseVal, *Cond;
3657 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3658 popValue(Record, OpNum, NextValueNo, TrueVal->
getType(), FalseVal) ||
3659 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3660 return error(
"Invalid record");
3662 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3663 InstructionList.push_back(I);
3671 Value *TrueVal, *FalseVal, *Cond;
3672 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3673 popValue(Record, OpNum, NextValueNo, TrueVal->
getType(), FalseVal) ||
3674 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3675 return error(
"Invalid record");
3679 dyn_cast<VectorType>(Cond->
getType())) {
3681 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3682 return error(
"Invalid type for value");
3685 if (Cond->
getType() != Type::getInt1Ty(Context))
3686 return error(
"Invalid type for value");
3689 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3690 InstructionList.push_back(I);
3697 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3698 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3699 return error(
"Invalid record");
3701 return error(
"Invalid type for value");
3702 I = ExtractElementInst::Create(Vec, Idx);
3703 InstructionList.push_back(I);
3709 Value *Vec, *Elt, *Idx;
3710 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3711 return error(
"Invalid record");
3713 return error(
"Invalid type for value");
3714 if (popValue(Record, OpNum, NextValueNo,
3715 cast<VectorType>(Vec->
getType())->getElementType(), Elt) ||
3716 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3717 return error(
"Invalid record");
3718 I = InsertElementInst::Create(Vec, Elt, Idx);
3719 InstructionList.push_back(I);
3726 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3727 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec2))
3728 return error(
"Invalid record");
3730 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3731 return error(
"Invalid record");
3733 return error(
"Invalid type for value");
3735 InstructionList.push_back(I);
3748 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3749 popValue(Record, OpNum, NextValueNo, LHS->
getType(), RHS))
3750 return error(
"Invalid record");
3752 unsigned PredVal = Record[OpNum];
3755 if (IsFP && Record.
size() > OpNum+1)
3758 if (OpNum+1 != Record.
size())
3759 return error(
"Invalid record");
3767 I->setFastMathFlags(FMF);
3768 InstructionList.push_back(I);
3774 unsigned Size = Record.
size();
3776 I = ReturnInst::Create(Context);
3777 InstructionList.push_back(I);
3782 Value *Op =
nullptr;
3783 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3784 return error(
"Invalid record");
3785 if (OpNum != Record.
size())
3786 return error(
"Invalid record");
3788 I = ReturnInst::Create(Context, Op);
3789 InstructionList.push_back(I);
3793 if (Record.
size() != 1 && Record.
size() != 3)
3794 return error(
"Invalid record");
3795 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3797 return error(
"Invalid record");
3799 if (Record.
size() == 1) {
3800 I = BranchInst::Create(TrueDest);
3801 InstructionList.push_back(I);
3804 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3805 Value *Cond = getValue(Record, 2, NextValueNo,
3806 Type::getInt1Ty(Context));
3807 if (!FalseDest || !Cond)
3808 return error(
"Invalid record");
3809 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3810 InstructionList.push_back(I);
3815 if (Record.
size() != 1 && Record.
size() != 2)
3816 return error(
"Invalid record");
3819 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3821 return error(
"Invalid record");
3823 if (Record.
size() == 2) {
3824 UnwindDest = getBasicBlock(Record[Idx++]);
3826 return error(
"Invalid record");
3829 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
3830 InstructionList.push_back(I);
3834 if (Record.
size() != 2)
3835 return error(
"Invalid record");
3838 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3840 return error(
"Invalid record");
3841 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3843 return error(
"Invalid record");
3845 I = CatchReturnInst::Create(CatchPad, BB);
3846 InstructionList.push_back(I);
3851 if (Record.
size() < 2)
3852 return error(
"Invalid record");
3857 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3859 unsigned NumHandlers = Record[Idx++];
3862 for (
unsigned Op = 0; Op != NumHandlers; ++
Op) {
3863 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3865 return error(
"Invalid record");
3870 if (Idx + 1 == Record.
size()) {
3871 UnwindDest = getBasicBlock(Record[Idx++]);
3873 return error(
"Invalid record");
3876 if (Record.
size() != Idx)
3877 return error(
"Invalid record");
3880 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3882 CatchSwitch->addHandler(Handler);
3884 InstructionList.push_back(I);
3890 if (Record.
size() < 2)
3891 return error(
"Invalid record");
3896 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3898 unsigned NumArgOperands = Record[Idx++];
3901 for (
unsigned Op = 0; Op != NumArgOperands; ++
Op) {
3903 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3904 return error(
"Invalid record");
3908 if (Record.
size() != Idx)
3909 return error(
"Invalid record");
3912 I = CleanupPadInst::Create(ParentPad, Args);
3914 I = CatchPadInst::Create(ParentPad, Args);
3915 InstructionList.push_back(I);
3920 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3926 Type *OpTy = getTypeByID(Record[1]);
3927 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->
getBitWidth();
3929 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3931 if (!OpTy || !Cond || !Default)
3932 return error(
"Invalid record");
3934 unsigned NumCases = Record[4];
3936 SwitchInst *
SI = SwitchInst::Create(Cond, Default, NumCases);
3937 InstructionList.push_back(SI);
3939 unsigned CurIdx = 5;
3940 for (
unsigned i = 0; i != NumCases; ++i) {
3942 unsigned NumItems = Record[CurIdx++];
3943 for (
unsigned ci = 0; ci != NumItems; ++ci) {
3944 bool isSingleNumber = Record[CurIdx++];
3947 unsigned ActiveWords = 1;
3948 if (ValueBitWidth > 64)
3949 ActiveWords = Record[CurIdx++];
3952 CurIdx += ActiveWords;
3954 if (!isSingleNumber) {
3956 if (ValueBitWidth > 64)
3957 ActiveWords = Record[CurIdx++];
3959 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3960 CurIdx += ActiveWords;
3966 for ( ; Low.
ule(High); ++Low)
3967 CaseVals.
push_back(ConstantInt::get(Context, Low));
3969 CaseVals.
push_back(ConstantInt::get(Context, Low));
3971 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3973 cve = CaseVals.
end(); cvi != cve; ++cvi)
3982 if (Record.
size() < 3 || (Record.
size() & 1) == 0)
3983 return error(
"Invalid record");
3984 Type *OpTy = getTypeByID(Record[0]);
3985 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3986 BasicBlock *Default = getBasicBlock(Record[2]);
3987 if (!OpTy || !Cond || !Default)
3988 return error(
"Invalid record");
3989 unsigned NumCases = (Record.
size()-3)/2;
3990 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3991 InstructionList.push_back(SI);
3992 for (
unsigned i = 0, e = NumCases; i != e; ++i) {
3994 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3995 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3996 if (!CaseVal || !DestBB) {
3998 return error(
"Invalid record");
4006 if (Record.
size() < 2)
4007 return error(
"Invalid record");
4008 Type *OpTy = getTypeByID(Record[0]);
4009 Value *
Address = getValue(Record, 1, NextValueNo, OpTy);
4010 if (!OpTy || !Address)
4011 return error(
"Invalid record");
4012 unsigned NumDests = Record.
size()-2;
4014 InstructionList.push_back(IBI);
4015 for (
unsigned i = 0, e = NumDests; i != e; ++i) {
4016 if (
BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4020 return error(
"Invalid record");
4029 if (Record.
size() < 4)
4030 return error(
"Invalid record");
4033 unsigned CCInfo = Record[OpNum++];
4034 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4035 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4038 if (CCInfo >> 13 & 1 &&
4039 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4040 return error(
"Explicit invoke type is not a function type");
4043 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4044 return error(
"Invalid record");
4048 return error(
"Callee is not a pointer");
4052 return error(
"Callee is not of pointer to function type");
4054 return error(
"Explicit invoke type does not match pointee type of "
4057 return error(
"Insufficient operands to call");
4060 for (
unsigned i = 0, e = FTy->
getNumParams(); i != e; ++i, ++OpNum) {
4061 Ops.
push_back(getValue(Record, OpNum, NextValueNo,
4064 return error(
"Invalid record");
4068 if (Record.
size() != OpNum)
4069 return error(
"Invalid record");
4072 while (OpNum != Record.
size()) {
4074 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4075 return error(
"Invalid record");
4080 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4081 OperandBundles.clear();
4082 InstructionList.push_back(I);
4083 cast<InvokeInst>(
I)->setCallingConv(
4085 cast<InvokeInst>(
I)->setAttributes(PAL);
4090 Value *Val =
nullptr;
4091 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4092 return error(
"Invalid record");
4093 I = ResumeInst::Create(Val);
4094 InstructionList.push_back(I);
4099 InstructionList.push_back(I);
4102 if (Record.
size() < 1 || ((Record.
size()-1)&1))
4103 return error(
"Invalid record");
4104 Type *Ty = getTypeByID(Record[0]);
4106 return error(
"Invalid record");
4108 PHINode *PN = PHINode::Create(Ty, (Record.
size()-1)/2);
4109 InstructionList.push_back(PN);
4111 for (
unsigned i = 0, e = Record.
size()-1; i != e; i += 2) {
4117 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4119 V = getValue(Record, 1+i, NextValueNo, Ty);
4122 return error(
"Invalid record");
4134 if (Record.
size() < 3)
4135 return error(
"Invalid record");
4138 if (Record.
size() < 4)
4139 return error(
"Invalid record");
4141 Type *Ty = getTypeByID(Record[Idx++]);
4143 return error(
"Invalid record");
4145 Value *PersFn =
nullptr;
4146 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4147 return error(
"Invalid record");
4152 return error(
"Personality function mismatch");
4155 bool IsCleanup = !!Record[Idx++];
4156 unsigned NumClauses = Record[Idx++];
4159 for (
unsigned J = 0; J != NumClauses; ++J) {
4164 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4166 return error(
"Invalid record");
4169 assert((CT != LandingPadInst::Catch ||
4170 !isa<ArrayType>(Val->
getType())) &&
4171 "Catch clause has a invalid type!");
4172 assert((CT != LandingPadInst::Filter ||
4173 isa<ArrayType>(Val->
getType())) &&
4174 "Filter clause has invalid type!");
4179 InstructionList.push_back(I);
4184 if (Record.
size() != 4)
4185 return error(
"Invalid record");
4186 uint64_t AlignRecord = Record[3];
4187 const uint64_t InAllocaMask = uint64_t(1) << 5;
4188 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4189 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4190 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4192 bool InAlloca = AlignRecord & InAllocaMask;
4193 bool SwiftError = AlignRecord & SwiftErrorMask;
4194 Type *Ty = getTypeByID(Record[0]);
4195 if ((AlignRecord & ExplicitTypeMask) == 0) {
4196 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4198 return error(
"Old-style alloca with a non-pointer type");
4201 Type *OpTy = getTypeByID(Record[1]);
4202 Value *Size = getFnValueByID(Record[2], OpTy);
4204 if (
Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4208 return error(
"Invalid record");
4218 InstructionList.push_back(I);
4224 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4225 (OpNum + 2 != Record.
size() && OpNum + 3 != Record.
size()))
4226 return error(
"Invalid record");
4229 if (OpNum + 3 == Record.
size())
4230 Ty = getTypeByID(Record[OpNum++]);
4231 if (
Error Err = typeCheckLoadStoreInst(Ty, Op->
getType()))
4234 Ty = cast<PointerType>(Op->
getType())->getElementType();
4237 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4239 I =
new LoadInst(Ty, Op,
"", Record[OpNum + 1], Align);
4241 InstructionList.push_back(I);
4248 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4249 (OpNum + 4 != Record.
size() && OpNum + 5 != Record.
size()))
4250 return error(
"Invalid record");
4253 if (OpNum + 5 == Record.
size())
4254 Ty = getTypeByID(Record[OpNum++]);
4255 if (
Error Err = typeCheckLoadStoreInst(Ty, Op->
getType()))
4258 Ty = cast<PointerType>(Op->
getType())->getElementType();
4261 if (Ordering == AtomicOrdering::NotAtomic ||
4262 Ordering == AtomicOrdering::Release ||
4263 Ordering == AtomicOrdering::AcquireRelease)
4264 return error(
"Invalid record");
4265 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4266 return error(
"Invalid record");
4267 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4270 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4272 I =
new LoadInst(Op,
"", Record[OpNum+1], Align, Ordering, SSID);
4274 InstructionList.push_back(I);
4281 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4283 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4284 : popValue(Record, OpNum, NextValueNo,
4285 cast<PointerType>(Ptr->
getType())->getElementType(),
4287 OpNum + 2 != Record.
size())
4288 return error(
"Invalid record");
4293 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4295 I =
new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4296 InstructionList.push_back(I);
4304 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4305 !isa<PointerType>(Ptr->
getType()) ||
4307 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4308 : popValue(Record, OpNum, NextValueNo,
4309 cast<PointerType>(Ptr->
getType())->getElementType(),
4311 OpNum + 4 != Record.
size())
4312 return error(
"Invalid record");
4317 if (Ordering == AtomicOrdering::NotAtomic ||
4318 Ordering == AtomicOrdering::Acquire ||
4319 Ordering == AtomicOrdering::AcquireRelease)
4320 return error(
"Invalid record");
4321 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4322 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4323 return error(
"Invalid record");
4326 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4328 I =
new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
4329 InstructionList.push_back(I);
4338 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4340 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4341 : popValue(Record, OpNum, NextValueNo,
4342 cast<PointerType>(Ptr->
getType())->getElementType(),
4344 popValue(Record, OpNum, NextValueNo, Cmp->
getType(), New) ||
4345 Record.
size() < OpNum + 3 || Record.
size() > OpNum + 5)
4346 return error(
"Invalid record");
4348 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4349 SuccessOrdering == AtomicOrdering::Unordered)
4350 return error(
"Invalid record");
4351 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
4356 if (Record.
size() < 7)
4358 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4364 cast<AtomicCmpXchgInst>(
I)->setVolatile(Record[OpNum]);
4366 if (Record.
size() < 8) {
4371 I = ExtractValueInst::Create(I, 0);
4373 cast<AtomicCmpXchgInst>(
I)->setWeak(Record[OpNum+4]);
4376 InstructionList.push_back(I);
4383 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4384 !isa<PointerType>(Ptr->
getType()) ||
4385 popValue(Record, OpNum, NextValueNo,
4386 cast<PointerType>(Ptr->
getType())->getElementType(), Val) ||
4387 OpNum+4 != Record.
size())
4388 return error(
"Invalid record");
4390 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4391 Operation > AtomicRMWInst::LAST_BINOP)
4392 return error(
"Invalid record");
4394 if (Ordering == AtomicOrdering::NotAtomic ||
4395 Ordering == AtomicOrdering::Unordered)
4396 return error(
"Invalid record");
4397 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4399 cast<AtomicRMWInst>(
I)->setVolatile(Record[OpNum+1]);
4400 InstructionList.push_back(I);
4404 if (2 != Record.
size())
4405 return error(
"Invalid record");
4407 if (Ordering == AtomicOrdering::NotAtomic ||
4408 Ordering == AtomicOrdering::Unordered ||
4409 Ordering == AtomicOrdering::Monotonic)
4410 return error(
"Invalid record");
4412 I =
new FenceInst(Context, Ordering, SSID);
4413 InstructionList.push_back(I);
4418 if (Record.
size() < 3)
4419 return error(
"Invalid record");
4423 unsigned CCInfo = Record[OpNum++];
4429 return error(
"Fast math flags indicator set for call with no FMF");
4434 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4435 return error(
"Explicit call type is not a function type");
4438 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4439 return error(
"Invalid record");
4443 return error(
"Callee is not a pointer type");
4447 return error(
"Callee is not of pointer to function type");
4449 return error(
"Explicit call type does not match pointee type of "
4452 return error(
"Insufficient operands to call");
4456 for (
unsigned i = 0, e = FTy->
getNumParams(); i != e; ++i, ++OpNum) {
4458 Args.
push_back(getBasicBlock(Record[OpNum]));
4460 Args.
push_back(getValue(Record, OpNum, NextValueNo,
4463 return error(
"Invalid record");
4468 if (OpNum != Record.
size())
4469 return error(
"Invalid record");
4471 while (OpNum != Record.
size()) {
4473 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4474 return error(
"Invalid record");
4479 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4480 OperandBundles.clear();
4481 InstructionList.push_back(I);
4482 cast<CallInst>(
I)->setCallingConv(
4486 TCK = CallInst::TCK_Tail;
4488 TCK = CallInst::TCK_MustTail;
4490 TCK = CallInst::TCK_NoTail;
4491 cast<CallInst>(
I)->setTailCallKind(TCK);
4492 cast<CallInst>(
I)->setAttributes(PAL);
4494 if (!isa<FPMathOperator>(I))
4495 return error(
"Fast-math-flags specified for call without "
4496 "floating-point scalar or vector return type");
4497 I->setFastMathFlags(FMF);
4502 if (Record.
size() < 3)
4503 return error(
"Invalid record");
4504 Type *OpTy = getTypeByID(Record[0]);
4505 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4506 Type *ResTy = getTypeByID(Record[2]);
4507 if (!OpTy || !Op || !ResTy)
4508 return error(
"Invalid record");
4510 InstructionList.push_back(I);
4519 if (Record.
size() < 1 || Record[0] >= BundleTags.
size())
4520 return error(
"Invalid record");
4522 std::vector<Value *> Inputs;
4525 while (OpNum != Record.
size()) {
4527 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4528 return error(
"Invalid record");
4529 Inputs.push_back(Op);
4532 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4541 return error(
"Invalid instruction with no BB");
4543 if (!OperandBundles.empty()) {
4545 return error(
"Operand bundles found with no consumer");
4550 if (isa<TerminatorInst>(I)) {
4552 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
4556 if (I && !I->getType()->isVoidTy())
4557 ValueList.assignValue(I, NextValueNo++);
4562 if (!OperandBundles.empty())
4563 return error(
"Operand bundles found with no consumer");
4566 if (
Argument *
A = dyn_cast<Argument>(ValueList.back())) {
4567 if (!
A->getParent()) {
4569 for (
unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4570 if ((
A = dyn_cast_or_null<Argument>(ValueList[i])) && !
A->getParent()) {
4571 A->replaceAllUsesWith(UndefValue::get(
A->getType()));
4575 return error(
"Never resolved value found in function");
4580 if (MDLoader->hasFwdRefs())
4581 return error(
"Invalid function metadata: outgoing forward refs");
4584 ValueList.shrinkTo(ModuleValueListSize);
4585 MDLoader->shrinkTo(ModuleMDLoaderSize);
4586 std::vector<BasicBlock*>().
swap(FunctionBBs);
4591 Error BitcodeReader::findFunctionInStream(
4594 while (DeferredFunctionInfoIterator->second == 0) {
4602 if (
Error Err = rememberAndSkipFunctionBodies())
4608 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(
unsigned Val) {
4611 if (Val >= SSIDs.size())
4627 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
4630 if (DFII->second == 0)
4631 if (
Error Err = findFunctionInStream(F, DFII))
4635 if (
Error Err = materializeMetadata())
4641 if (
Error Err = parseFunctionBody(F))
4649 for (
auto &I : UpgradedIntrinsics) {
4650 for (
auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4654 if (
CallInst *CI = dyn_cast<CallInst>(U))
4660 for (
auto &I : RemangledIntrinsics)
4661 for (
auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4667 if (
DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
4671 if (!MDLoader->isStrippingTBAA()) {
4673 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4674 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4676 MDLoader->setStripTBAA(
true);
4683 return materializeForwardReferencedFunctions();
4686 Error BitcodeReader::materializeModule() {
4687 if (
Error Err = materializeMetadata())
4691 WillMaterializeAllForwardRefs =
true;
4696 if (
Error Err = materialize(&F))
4702 if (LastFunctionBlockBit || NextUnreadBit)
4703 if (
Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4704 ? LastFunctionBlockBit
4710 if (!BasicBlockFwdRefs.empty())
4711 return error(
"Never resolved function from blockaddress");
4717 for (
auto &I : UpgradedIntrinsics) {
4718 for (
auto *U : I.first->
users()) {
4719 if (
CallInst *CI = dyn_cast<CallInst>(U))
4722 if (!I.first->use_empty())
4723 I.first->replaceAllUsesWith(I.second);
4724 I.first->eraseFromParent();
4726 UpgradedIntrinsics.clear();
4728 for (
auto &I : RemangledIntrinsics) {
4729 I.first->replaceAllUsesWith(I.second);
4730 I.first->eraseFromParent();
4732 RemangledIntrinsics.clear();
4740 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
4741 return IdentifiedStructTypes;
4744 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4746 StringRef ModulePath,
unsigned ModuleId)
4747 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4748 ModulePath(ModulePath), ModuleId(ModuleId) {}
4751 ModuleSummaryIndexBitcodeReader::addThisModule() {
4752 return TheIndex.addModule(ModulePath, ModuleId);
4755 std::pair<ValueInfo, GlobalValue::GUID>
4756 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(
unsigned ValueId) {
4757 auto VGI = ValueIdToValueInfoMap[ValueId];
4762 void ModuleSummaryIndexBitcodeReader::setValueGUID(
4765 std::string GlobalId =
4766 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4767 auto ValueGUID = GlobalValue::getGUID(GlobalId);
4768 auto OriginalNameID = ValueGUID;
4769 if (GlobalValue::isLocalLinkage(Linkage))
4770 OriginalNameID = GlobalValue::getGUID(ValueName);
4772 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
4773 << ValueName <<
"\n";
4774 ValueIdToValueInfoMap[ValueID] =
4775 std::make_pair(TheIndex.getOrInsertValueInfo(ValueGUID), OriginalNameID);
4781 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
4788 assert(Offset > 0 &&
"Expected non-zero VST offset");
4792 return error(
"Invalid record");
4802 switch (Entry.
Kind) {
4803 case BitstreamEntry::SubBlock:
4805 return error(
"Malformed block");
4806 case BitstreamEntry::EndBlock:
4810 case BitstreamEntry::Record:
4821 if (convertToString(Record, 1, ValueName))
4822 return error(
"Invalid record");
4823 unsigned ValueID = Record[0];
4825 auto VLI = ValueIdToLinkageMap.
find(ValueID);
4826 assert(VLI != ValueIdToLinkageMap.
end() &&
4827 "No linkage found for VST entry?");
4828 auto Linkage = VLI->second;
4829 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4835 if (convertToString(Record, 2, ValueName))
4836 return error(
"Invalid record");
4837 unsigned ValueID = Record[0];
4839 auto VLI = ValueIdToLinkageMap.
find(ValueID);
4840 assert(VLI != ValueIdToLinkageMap.
end() &&
4841 "No linkage found for VST entry?");
4842 auto Linkage = VLI->second;
4843 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4849 unsigned ValueID = Record[0];
4853 ValueIdToValueInfoMap[ValueID] =
4854 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
4864 Error ModuleSummaryIndexBitcodeReader::parseModule() {
4866 return error(
"Invalid record");
4870 unsigned ValueId = 0;
4876 switch (Entry.
Kind) {
4878 return error(
"Malformed block");
4879 case BitstreamEntry::EndBlock:
4882 case BitstreamEntry::SubBlock:
4886 return error(
"Invalid record");
4890 if (readBlockInfo())
4891 return error(
"Malformed block");
4896 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4897 !SeenGlobalValSummary) &&
4898 "Expected early VST parse via VSTOffset record");
4900 return error(
"Invalid record");
4904 assert(!SeenValueSymbolTable &&
4905 "Already read VST when parsing summary block?");
4910 if (VSTOffset > 0) {
4911 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4913 SeenValueSymbolTable =
true;
4915 SeenGlobalValSummary =
true;
4916 if (
Error Err = parseEntireSummary(Entry.
ID))
4920 if (
Error Err = parseModuleStringTable())
4926 case BitstreamEntry::Record: {
4933 if (
Error Err = parseVersionRecord(Record).takeError())
4940 if (convertToString(Record, 0, ValueName))
4941 return error(
"Invalid record");
4942 SourceFileName = ValueName.
c_str();
4947 if (Record.
size() != 5)
4948 return error(
"Invalid hash length " +
Twine(Record.
size()).str());
4949 auto &
Hash = addThisModule()->second.second;
4951 for (
auto &Val : Record) {
4952 assert(!(Val >> 32) &&
"Unexpected high bits set");
4959 if (Record.size() < 1)
4960 return error(
"Invalid record");
4964 VSTOffset = Record[0] - 1;
4975 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
4976 if (GVRecord.
size() <= 3)
4977 return error(
"Invalid record");
4978 uint64_t RawLinkage = GVRecord[3];
4981 ValueIdToLinkageMap[ValueId++] = Linkage;
4985 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
4995 std::vector<ValueInfo>
4997 std::vector<ValueInfo>
Ret;
4998 Ret.reserve(Record.
size());
4999 for (uint64_t RefValueId : Record)
5000 Ret.push_back(getValueInfoFromValueId(RefValueId).
first);
5004 std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
5006 std::vector<FunctionSummary::EdgeTy>
Ret;
5007 Ret.reserve(Record.
size());
5008 for (
unsigned I = 0,
E = Record.
size(); I !=
E; ++
I) {
5010 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
5011 if (IsOldProfileFormat) {
5015 }
else if (HasProfile)
5024 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
unsigned ID) {
5026 return error(
"Invalid record");
5032 if (Entry.
Kind != BitstreamEntry::Record)
5033 return error(
"Invalid Summary Block: record for version expected");
5035 return error(
"Invalid Summary Block: version expected");
5037 const uint64_t
Version = Record[0];
5038 const bool IsOldProfileFormat = Version == 1;
5039 if (Version < 1 || Version > 3)
5040 return error(
"Invalid summary version " +
Twine(Version) +
5041 ", 1, 2 or 3 expected");
5052 std::vector<GlobalValue::GUID> PendingTypeTests;
5053 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5054 PendingTypeCheckedLoadVCalls;
5055 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5056 PendingTypeCheckedLoadConstVCalls;
5061 switch (Entry.
Kind) {
5062 case BitstreamEntry::SubBlock:
5064 return error(
"Malformed block");
5065 case BitstreamEntry::EndBlock:
5067 case BitstreamEntry::Record:
5085 uint64_t ValueID = Record[0];
5087 ValueIdToValueInfoMap[ValueID] =
5088 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5098 unsigned ValueID = Record[0];
5099 uint64_t RawFlags = Record[1];
5100 unsigned InstCount = Record[2];
5101 unsigned NumRefs = Record[3];
5108 static int RefListStartIndex = 4;
5109 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5110 assert(Record.
size() >= RefListStartIndex + NumRefs &&
5111 "Record size inconsistent with number of references");
5112 std::vector<ValueInfo> Refs = makeRefList(
5115 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5117 IsOldProfileFormat, HasProfile);
5118 auto FS = llvm::make_unique<FunctionSummary>(
5119 Flags, InstCount, std::move(Refs), std::move(Calls),
5120 std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls),
5121 std::move(PendingTypeCheckedLoadVCalls),
5122 std::move(PendingTypeTestAssumeConstVCalls),
5123 std::move(PendingTypeCheckedLoadConstVCalls));
5124 PendingTypeTests.clear();
5125 PendingTypeTestAssumeVCalls.clear();
5126 PendingTypeCheckedLoadVCalls.clear();
5127 PendingTypeTestAssumeConstVCalls.clear();
5128 PendingTypeCheckedLoadConstVCalls.clear();
5129 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
5130 FS->setModulePath(addThisModule()->
first());
5131 FS->setOriginalName(VIAndOriginalGUID.second);
5132 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
5139 unsigned ValueID = Record[0];
5140 uint64_t RawFlags = Record[1];
5141 unsigned AliaseeID = Record[2];
5144 llvm::make_unique<AliasSummary>(
Flags, std::vector<ValueInfo>{});
5150 AS->setModulePath(addThisModule()->
first());
5153 getValueInfoFromValueId(AliaseeID).first.getGUID();
5154 auto AliaseeInModule =
5155 TheIndex.findSummaryInModule(AliaseeGUID, ModulePath);
5156 if (!AliaseeInModule)
5157 return error(
"Alias expects aliasee summary to be parsed");
5158 AS->setAliasee(AliaseeInModule);
5160 auto GUID = getValueInfoFromValueId(ValueID);
5161 AS->setOriginalName(GUID.second);
5162 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
5167 unsigned ValueID = Record[0];
5168 uint64_t RawFlags = Record[1];
5170 std::vector<ValueInfo> Refs =
5172 auto FS = llvm::make_unique<GlobalVarSummary>(
Flags, std::move(Refs));
5173 FS->setModulePath(addThisModule()->
first());
5174 auto GUID = getValueInfoFromValueId(ValueID);
5175 FS->setOriginalName(GUID.second);
5176 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
5185 unsigned ValueID = Record[0];
5186 uint64_t ModuleId = Record[1];
5187 uint64_t RawFlags = Record[2];
5188 unsigned InstCount = Record[3];
5189 unsigned NumRefs = Record[4];
5191 static int RefListStartIndex = 5;
5192 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5193 assert(Record.
size() >= RefListStartIndex + NumRefs &&
5194 "Record size inconsistent with number of references");
5195 std::vector<ValueInfo> Refs = makeRefList(
5198 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5200 IsOldProfileFormat, HasProfile);
5201 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5202 auto FS = llvm::make_unique<FunctionSummary>(
5203 Flags, InstCount, std::move(Refs), std::move(Edges),
5204 std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls),
5205 std::move(PendingTypeCheckedLoadVCalls),
5206 std::move(PendingTypeTestAssumeConstVCalls),
5207 std::move(PendingTypeCheckedLoadConstVCalls));
5208 PendingTypeTests.clear();
5209 PendingTypeTestAssumeVCalls.clear();
5210 PendingTypeCheckedLoadVCalls.clear();
5211 PendingTypeTestAssumeConstVCalls.clear();
5212 PendingTypeCheckedLoadConstVCalls.clear();
5213 LastSeenSummary =
FS.get();
5215 FS->setModulePath(ModuleIdMap[ModuleId]);
5216 TheIndex.addGlobalValueSummary(VI, std::move(FS));
5223 unsigned ValueID = Record[0];
5224 uint64_t ModuleId = Record[1];
5225 uint64_t RawFlags = Record[2];
5226 unsigned AliaseeValueId = Record[3];
5228 auto AS = llvm::make_unique<AliasSummary>(
Flags, std::vector<ValueInfo>{});
5229 LastSeenSummary = AS.get();
5230 AS->setModulePath(ModuleIdMap[ModuleId]);
5233 getValueInfoFromValueId(AliaseeValueId).first.getGUID();
5234 auto AliaseeInModule =
5235 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
5236 if (!AliaseeInModule)
5237 return error(
"Alias expects aliasee summary to be parsed");
5238 AS->setAliasee(AliaseeInModule);
5240 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5242 TheIndex.addGlobalValueSummary(VI, std::move(AS));
5247 unsigned ValueID = Record[0];
5248 uint64_t ModuleId = Record[1];
5249 uint64_t RawFlags = Record[2];
5251 std::vector<ValueInfo> Refs =
5253 auto FS = llvm::make_unique<GlobalVarSummary>(
Flags, std::move(Refs));
5254 LastSeenSummary =
FS.get();
5255 FS->setModulePath(ModuleIdMap[ModuleId]);
5256 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5258 TheIndex.addGlobalValueSummary(VI, std::move(FS));
5263 uint64_t OriginalName = Record[0];
5264 if (!LastSeenSummary)
5265 return error(
"Name attachment that does not follow a combined record");
5266 LastSeenSummary->setOriginalName(OriginalName);
5267 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
5269 LastSeenSummary =
nullptr;
5274 assert(PendingTypeTests.empty());
5275 PendingTypeTests.insert(PendingTypeTests.end(), Record.
begin(),
5280 assert(PendingTypeTestAssumeVCalls.empty());
5281 for (
unsigned I = 0; I != Record.
size(); I += 2)
5282 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5286 assert(PendingTypeCheckedLoadVCalls.empty());
5287 for (
unsigned I = 0; I != Record.
size(); I += 2)
5288 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5292 PendingTypeTestAssumeConstVCalls.push_back(
5293 {{Record[0], Record[1]}, {Record.
begin() + 2, Record.
end()}});
5297 PendingTypeCheckedLoadConstVCalls.push_back(
5298 {{Record[0], Record[1]}, {Record.
begin() + 2, Record.
end()}});
5302 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
5303 for (
unsigned I = 0; I != Record.
size(); I += 2)
5304 CfiFunctionDefs.insert(
5305 {Strtab.data() + Record[
I],
static_cast<size_t>(Record[I + 1])});
5309 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
5310 for (
unsigned I = 0; I != Record.
size(); I += 2)
5311 CfiFunctionDecls.insert(
5312 {Strtab.data() + Record[
I],
static_cast<size_t>(Record[I + 1])});
5322 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5324 return error(
"Invalid record");
5334 switch (Entry.
Kind) {
5335 case BitstreamEntry::SubBlock:
5337 return error(
"Malformed block");
5338 case BitstreamEntry::EndBlock:
5340 case BitstreamEntry::Record:
5351 uint64_t ModuleId = Record[0];
5353 if (convertToString(Record, 1, ModulePath))
5354 return error(
"Invalid record");
5356 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
5357 ModuleIdMap[ModuleId] = LastSeenModule->first();
5364 if (Record.
size() != 5)
5365 return error(
"Invalid hash length " +
Twine(Record.
size()).str());
5366 if (!LastSeenModule)
5367 return error(
"Invalid hash that does not follow a module path");
5369 for (
auto &Val : Record) {
5370 assert(!(Val >> 32) &&
"Unexpected high bits set");
5371 LastSeenModule->second.second[Pos++] = Val;
5374 LastSeenModule =
nullptr;
5388 const char *
name()
const noexcept
override {
5389 return "llvm.bitcode";
5391 std::string message(
int IE)
const override {
5394 case BitcodeError::CorruptedBitcode:
5395 return "Corrupted bitcode";
5410 unsigned Block,
unsigned RecordID) {
5412 return error(
"Invalid record");
5417 switch (Entry.
Kind) {
5418 case BitstreamEntry::EndBlock:
5422 return error(
"Malformed block");
5424 case BitstreamEntry::SubBlock:
5426 return error(
"Malformed block");
5429 case BitstreamEntry::Record:
5432 if (Stream.
readRecord(Entry.
ID, Record, &Blob) == RecordID)
5447 return FOrErr.takeError();
5448 return std::move(FOrErr->Mods);
5469 switch (Entry.
Kind) {
5470 case BitstreamEntry::EndBlock:
5472 return error(
"Malformed block");
5474 case BitstreamEntry::SubBlock: {
5475 uint64_t IdentificationBit = -1ull;
5479 return error(
"Malformed block");
5482 if (Entry.
Kind != BitstreamEntry::SubBlock ||
5484 return error(
"Malformed block");
5490 return error(
"Malformed block");
5508 for (
auto I = F.
Mods.rbegin(),
E = F.
Mods.rend(); I !=
E; ++
I) {
5509 if (!I->Strtab.empty())
5511 I->Strtab = *Strtab;
5539 return error(
"Malformed block");
5542 case BitstreamEntry::Record:
5558 BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
5559 bool ShouldLazyLoadMetadata,
bool IsImporting) {
5562 std::string ProducerIdentification;
5563 if (IdentificationBit != -1ull) {
5566 readIdentificationBlock(Stream);
5567 if (!ProducerIdentificationOrErr)
5568 return ProducerIdentificationOrErr.
takeError();
5570 ProducerIdentification = *ProducerIdentificationOrErr;
5574 auto *R =
new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5577 std::unique_ptr<Module> M =
5578 llvm::make_unique<Module>(ModuleIdentifier,
Context);
5583 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5584 return std::move(Err);
5586 if (MaterializeAll) {
5588 if (
Error Err = M->materializeAll())
5589 return std::move(Err);
5592 if (
Error Err = R->materializeForwardReferencedFunctions())
5593 return std::move(Err);
5595 return std::move(M);
5601 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting);
5609 StringRef ModulePath, uint64_t ModuleId) {
5613 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
5614 ModulePath, ModuleId);
5615 return R.parseModule();
5623 auto Index = llvm::make_unique<ModuleSummaryIndex>();
5624 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
5625 ModuleIdentifier, 0);
5627 if (
Error Err = R.parseModule())
5628 return std::move(Err);
5630 return std::move(Index);
5639 return error(
"Invalid record");
5644 switch (Entry.
Kind) {
5646 return error(
"Malformed block");
5659 return error(
"Malformed block");
5674 if (MsOrErr->size() != 1)
5675 return error(
"Expected a single module");
5677 return (*MsOrErr)[0];
5682 bool ShouldLazyLoadMetadata,
bool IsImporting) {
5687 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
5691 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
5692 bool ShouldLazyLoadMetadata,
bool IsImporting) {
5696 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5702 return getModuleImpl(Context,
true,
false,
false);
5713 return BM->parseModule(Context);
5721 return readTriple(*StreamOrErr);
5737 return readIdentificationCode(*StreamOrErr);
5742 uint64_t ModuleId) {
5747 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
5756 return BM->getSummary();
5764 return BM->getLTOInfo();
5769 bool IgnoreEmptyThinLTOIndexFile) {
5774 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
void setVisibility(VisibilityTypes V)
static AtomicOrdering getDecodedOrdering(unsigned Val)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
void sortUseList(Compare Cmp)
Sort the use-list.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
std::error_code getError() const
Tracking metadata reference owned by Metadata.
static APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
Represents either an error or a value T.
static bool isConstant(const MachineInstr &MI)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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...
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
This class represents an incoming formal argument to a Function.
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
const Instruction & back() const
Atomic ordering constants.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
A Module instance is used to store all the information related to an LLVM module. ...
Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
void setNoNaNs()
Flag setters.
An instruction for ordering other memory operations.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
void setAllowContract(bool B)
void setMaterializer(GVMaterializer *GVM)
Sets the GVMaterializer to GVM.
void addOperand(MDNode *M)
Error readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, uint64_t ModuleId)
Parse the specified bitcode buffer and merge its module summary index into CombinedIndex.
This class represents a function call, abstracting a target machine's calling convention.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID...
void setGC(std::string Str)
Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
This instruction constructs a fixed permutation of two input vectors.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
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...
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
static uint64_t jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
const char * getBufferStart() const
AttrBuilder & addDereferenceableAttr(uint64_t Bytes)
This turns the number of dereferenceable bytes into the form used internally in Attribute.
The two locations do not alias at all.
bool stripDebugInfo(Function &F)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
An instruction for reading from memory.
ELFYAML::ELF_STV Visibility
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Error takeError()
Take ownership of the stored error.
Type * getElementType() const
void UpgradeIntrinsicCall(CallInst *CI, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
void setAlignment(unsigned Align)
Base class for error info classes.
void setBlockInfo(BitstreamBlockInfo *BI)
Set the block info to be used by this BitstreamCursor to interpret abbreviated records.
word_t Read(unsigned NumBits)
StringRef StrtabForSymtab
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
uint64_t getArrayNumElements() const
StringRef getName() const
Return a constant reference to the value's name.
ArrayRef< uint8_t > getBitcodeBytes() const
void setIndirectSymbol(Constant *Symbol)
These methods set and retrieve indirect symbol.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
std::string str() const
Return the twine contents as a std::string.
Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
AttrBuilder & addDereferenceableOrNullAttr(uint64_t Bytes)
This turns the number of dereferenceable_or_null bytes into the form used internally in Attribute...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Expected< BitcodeLTOInfo > getLTOInfo()
Returns information about the module to be used for LTO: whether to compile with ThinLTO, and whether it has a summary.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
bool canSkipToPos(size_t pos) const
void setThreadLocalMode(ThreadLocalMode Val)
Constant * getPersonalityFn() const
Get the personality function associated with this function.
std::error_code make_error_code(BitcodeError E)
This file contains the simple types necessary to represent the attributes associated with functions a...
void setName(const Twine &Name)
Change the name of the value.
Tagged union holding either a T or a Error.
void setDLLStorageClass(DLLStorageClassTypes C)
This file implements a class to represent arbitrary precision integral constant values and operations...
LLVM_NODISCARD bool empty() const
AtomicOrdering
Atomic ordering for LLVM's memory model.
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
static Expected< StringRef > readBlobInRecord(BitstreamCursor &Stream, unsigned Block, unsigned RecordID)
AttributeList getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
llvm::Optional< Function * > remangleIntrinsicFunction(Function *F)
Class to represent function types.
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
const BasicBlock & back() const
BinOp
This enumeration lists the possible modifications atomicrmw can make.
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Class to represent array types.
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Basic information extracted from a bitcode module to be used for LTO.
This instruction compares its operands according to the predicate given to the constructor.
void setComdat(Comdat *C)
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn)
This is a more granular function that simply checks an intrinsic function for upgrading, and returns true if it requires upgrading.
An instruction for storing to memory.
bool isArrayTy() const
True if this is an instance of ArrayType.
BitstreamEntry advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
ModulePathStringTableTy::value_type ModuleInfo
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
AttrBuilder & addAllocSizeAttrFromRawRepr(uint64_t RawAllocSizeRepr)
Add an allocsize attribute, using the representation returned by Attribute.getIntValue().
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Type * getElementType() const
size_t size() const
size - Get the array size.
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
void setIsMaterializable(bool V)
const std::error_category & BitcodeErrorCategory()
Class to represent pointers.
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
iterator find(const_arg_type_t< KeyT > Val)
Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information...
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
void setCallingConv(CallingConv::ID CC)
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Type * getParamType(unsigned i) const
Parameter type accessors.
initializer< Ty > init(const Ty &Val)
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
bool isVectorTy() const
True if this is an instance of VectorType.
This function has undefined behavior.
This is an important base class in LLVM.
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
static bool hasImplicitComdat(size_t Val)
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Indirect Branch Instruction.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
Class to accumulate and hold information about a callee.
iterator_range< use_iterator > materialized_uses()
bool hasPersonalityFn() const
Check whether this function has a personality function.
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
unsigned getAllocaAddrSpace() const
uint64_t getCurrentByteNo() const
static ManagedStatic< _object_error_category > error_category
This file declares a class to represent arbitrary precision floating point values and provide a varie...
const InstListType & getInstList() const
Return the underlying instruction list container.
Select target instructions out of generic instructions
This instruction compares its operands according to the predicate given to the constructor.
uint64_t getNumElements() const
void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
DLLStorageClassTypes
Storage classes of global values for PE targets.
Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex, uint64_t ModuleId)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
Expected< BitcodeFileContents > getBitcodeFileContents(MemoryBufferRef Buffer)
Returns the contents of a bitcode file.
Function and variable summary information to aid decisions and implementation of importing.
void JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
bool isFP128Ty() const
Return true if this is 'fp128'.
bool isPointerTy() const
True if this is an instance of PointerType.
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static Attribute::AttrKind parseAttrKind(StringRef Kind)
bool SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block...
static wasm::ValType getType(const TargetRegisterClass *RC)
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
Triple - Helper class for working with autoconf configuration names.
size_t getBufferSize() const
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
Struct that holds a reference to a particular GUID in a global value summary.
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...
Synchronized with respect to all concurrently executing threads.
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
Iterator for intrusive lists based on ilist_node.
Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it...
static bool hasObjCCategory(StringRef Name)
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
This is the shared class of boolean and integer constants.
void setSelectionKind(SelectionKind Val)
bool isMaterializable() const
void setAllowReciprocal()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
bool UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
unsigned readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
This class maintains the abbreviations read from a block info block.
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
reference get()
Returns a reference to the stored T value.
bool any() const
Whether any flag is set.
AttributeSet getFnAttributes() const
The function attributes are returned.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
void setLinkage(LinkageTypes LT)
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class to represent vector types.
unsigned skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
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...
Class for arbitrary precision integers.
static int getDecodedCastOpcode(unsigned Val)
void push_back(pointer val)
Synchronized with respect to signal handlers executing in the same thread.
StringRef str() const
Explicit conversion to StringRef.
LinkageTypes
An enumeration for the kinds of linkage for global values.
enum llvm::BitstreamEntry::@128 Kind
bool isIntegerTy() const
True if this is an instance of IntegerType.
iterator_range< user_iterator > users()
Optional< BitstreamBlockInfo > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
void setAttributes(AttributeSet A)
Set attribute list for this global.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
bool isStructTy() const
True if this is an instance of StructType.
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
static std::vector< std::string > Flags
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...
Expected< BitcodeLTOInfo > getBitcodeLTOInfo(MemoryBufferRef Buffer)
Returns LTO information for the specified bitcode file.
PointerType * getType() const
Global values are always pointers.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val)
bool isX86_FP80Ty() const
Return true if this is x86 long double.
ValID - Represents a reference of a definition of some sort with no type.
pointer data()
Return a pointer to the vector's buffer, even if empty().
void setUnnamedAddr(UnnamedAddr Val)
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 EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true if the block has an error...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
static bool isValidElementType(Type *Ty)
Predicate for the element types that the SLP vectorizer supports.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
StringMapEntry< Value * > ValueName
GlobalValue::GUID getGUID() const
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
bool hasLocalLinkage() const
void addDestination(BasicBlock *Dest)
Add a destination.
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful...
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
StringRef getBufferIdentifier() const
std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
bool isLabelTy() const
Return true if this is 'label'.
Module * getParent()
Get the module that this global value is contained inside of...
Verify that the TBAA Metadatas are valid.
LLVM Value Representation.
Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Lightweight error class with error context and mandatory checking.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
AttrBuilder & addStackAlignmentAttr(unsigned Align)
This turns an int stack alignment (which must be a power of 2) into the form used internally in Attri...
The highest possible calling convention ID. Must be some 2^k - 1.
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"))
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting)
Read the bitcode module and prepare for lazy deserialization of function bodies.
virtual std::string message() const
Return the error message as a string.
std::string Hash(const Unit &U)
Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context)
Read the entire bitcode module and return it.
BitstreamEntry advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Convenience struct for specifying and reasoning about fast-math flags.
StringRef - Represent a constant reference to a string, i.e.
inst_range instructions(Function *F)
static ManagedStatic< BitcodeErrorCategoryType > ErrorCategory
AttrBuilder & addAlignmentAttr(unsigned Align)
This turns an int alignment (which must be a power of 2) into the form used internally in Attribute...
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
void setPersonalityFn(Constant *Fn)
Value * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
unsigned getAbbrevIDWidth() const
Return the number of bits used to encode an abbrev #.
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
Decode the flags for GlobalValue in the summary.
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
void setSection(StringRef S)
Change the section for this global.
void setCalledFunction(Value *V)
Set the callee to the specified value.
iterator_range< arg_iterator > args()
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
std::vector< BitcodeModule > Mods
ArrayRef< Type * > subtypes() const
an instruction to allocate memory on the stack
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results...
bool isMetadataTy() const
Return true if this is 'metadata'.
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)