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 {
375 BitcodeReaderBase(
BitstreamCursor Stream) : Stream(std::move(Stream)) {
382 bool readBlockInfo();
385 std::string ProducerIdentification;
391 std::string FullMsg = Message.
str();
392 if (!ProducerIdentification.empty())
393 FullMsg +=
" (Producer: '" + ProducerIdentification +
"' Reader: 'LLVM " +
394 LLVM_VERSION_STRING
"')";
398 class BitcodeReader :
public BitcodeReaderBase,
public GVMaterializer {
400 Module *TheModule =
nullptr;
402 uint64_t NextUnreadBit = 0;
404 uint64_t LastFunctionBlockBit = 0;
405 bool SeenValueSymbolTable =
false;
406 uint64_t VSTOffset = 0;
408 std::vector<Type*> TypeList;
411 std::vector<Comdat *> ComdatList;
414 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
415 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
416 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
417 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
418 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
422 std::vector<AttributeSet> MAttributes;
425 std::map<unsigned, AttributeSet> MAttributeGroups;
429 std::vector<BasicBlock*> FunctionBBs;
433 std::vector<Function*> FunctionsWithBodies;
438 UpdatedIntrinsicMap UpgradedIntrinsics;
440 UpdatedIntrinsicMap RemangledIntrinsics;
445 bool SeenFirstFunctionBody =
false;
454 std::vector<uint64_t> DeferredMetadataInfo;
460 std::deque<Function *> BasicBlockFwdRefQueue;
468 bool UseRelativeIDs =
false;
472 bool WillMaterializeAllForwardRefs =
false;
477 std::vector<std::string> BundleTags;
483 Error materializeForwardReferencedFunctions();
486 Error materializeModule()
override;
487 std::vector<StructType *> getIdentifiedStructTypes()
const override;
491 Error parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata =
false,
492 bool IsImporting =
false);
494 static uint64_t decodeSignRotatedValue(uint64_t V);
497 Error materializeMetadata()
override;
499 void setStripDebugInfo()
override;
502 std::vector<StructType *> IdentifiedStructTypes;
506 Type *getTypeByID(
unsigned ID);
511 return ValueList.getValueFwdRef(ID, Ty);
514 Metadata *getFnMetadataByID(
unsigned ID) {
515 return MDLoader->getMetadataFwdRefOrLoad(ID);
518 BasicBlock *getBasicBlock(
unsigned ID)
const {
519 if (ID >= FunctionBBs.size())
return nullptr;
520 return FunctionBBs[
ID];
524 if (i-1 < MAttributes.size())
525 return MAttributes[i-1];
533 unsigned InstNum,
Value *&ResVal) {
534 if (Slot == Record.
size())
return true;
535 unsigned ValNo = (
unsigned)Record[Slot++];
538 ValNo = InstNum - ValNo;
539 if (ValNo < InstNum) {
542 ResVal = getFnValueByID(ValNo,
nullptr);
543 return ResVal ==
nullptr;
545 if (Slot == Record.
size())
548 unsigned TypeNo = (
unsigned)Record[Slot++];
549 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
550 return ResVal ==
nullptr;
557 unsigned InstNum,
Type *Ty,
Value *&ResVal) {
558 if (getValue(Record, Slot, InstNum, Ty, ResVal))
567 unsigned InstNum,
Type *Ty,
Value *&ResVal) {
568 ResVal = getValue(Record, Slot, InstNum, Ty);
569 return ResVal ==
nullptr;
575 unsigned InstNum,
Type *Ty) {
576 if (Slot == Record.
size())
return nullptr;
577 unsigned ValNo = (
unsigned)Record[Slot];
580 ValNo = InstNum - ValNo;
581 return getFnValueByID(ValNo, Ty);
586 unsigned InstNum,
Type *Ty) {
587 if (Slot == Record.
size())
return nullptr;
588 unsigned ValNo = (
unsigned)decodeSignRotatedValue(Record[Slot]);
591 ValNo = InstNum - ValNo;
592 return getFnValueByID(ValNo, Ty);
598 Error parseAlignmentValue(uint64_t
Exponent,
unsigned &Alignment);
600 Error parseModule(uint64_t ResumeBit,
bool ShouldLazyLoadMetadata =
false);
601 Error parseAttributeBlock();
602 Error parseAttributeGroupBlock();
603 Error parseTypeTable();
604 Error parseTypeTableBody();
605 Error parseOperandBundleTags();
608 unsigned NameIndex, Triple &TT);
610 Error parseConstants();
611 Error rememberAndSkipFunctionBodies();
612 Error rememberAndSkipFunctionBody();
614 Error rememberAndSkipMetadata();
617 Error globalCleanup();
618 Error resolveGlobalAndIndirectSymbolInits();
619 Error parseUseLists();
620 Error findFunctionInStream(
627 class ModuleSummaryIndexBitcodeReader :
public BitcodeReaderBase {
633 bool SeenGlobalValSummary =
false;
636 bool SeenValueSymbolTable =
false;
640 uint64_t VSTOffset = 0;
650 ValueIdToCallGraphGUIDMap;
659 std::string SourceFileName;
662 ModuleSummaryIndexBitcodeReader(
668 Error parseValueSymbolTable(
673 bool IsOldProfileFormat,
676 Error parseModuleStringTable();
678 std::pair<GlobalValue::GUID, GlobalValue::GUID>
679 getGUIDFromValueId(
unsigned ValueId);
694 return std::error_code();
700 : BitcodeReaderBase(std::move(Stream)), Context(Context),
702 this->ProducerIdentification = ProducerIdentification;
705 Error BitcodeReader::materializeForwardReferencedFunctions() {
706 if (WillMaterializeAllForwardRefs)
710 WillMaterializeAllForwardRefs =
true;
712 while (!BasicBlockFwdRefQueue.empty()) {
713 Function *
F = BasicBlockFwdRefQueue.front();
714 BasicBlockFwdRefQueue.pop_front();
715 assert(F &&
"Expected valid function");
716 if (!BasicBlockFwdRefs.count(F))
725 return error(
"Never resolved function from blockaddress");
728 if (
Error Err = materialize(F))
731 assert(BasicBlockFwdRefs.empty() &&
"Function missing from queue");
734 WillMaterializeAllForwardRefs =
false;
758 return GlobalValue::ExternalLinkage;
760 return GlobalValue::AppendingLinkage;
762 return GlobalValue::InternalLinkage;
764 return GlobalValue::ExternalLinkage;
766 return GlobalValue::ExternalLinkage;
768 return GlobalValue::ExternalWeakLinkage;
770 return GlobalValue::CommonLinkage;
772 return GlobalValue::PrivateLinkage;
774 return GlobalValue::AvailableExternallyLinkage;
776 return GlobalValue::PrivateLinkage;
778 return GlobalValue::PrivateLinkage;
780 return GlobalValue::ExternalLinkage;
783 return GlobalValue::WeakAnyLinkage;
786 return GlobalValue::WeakODRLinkage;
789 return GlobalValue::LinkOnceAnyLinkage;
792 return GlobalValue::LinkOnceODRLinkage;
803 RawFlags = RawFlags >> 4;
804 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
808 bool LiveRoot = (RawFlags & 0x2) || Version < 3;
815 case 0:
return GlobalValue::DefaultVisibility;
816 case 1:
return GlobalValue::HiddenVisibility;
817 case 2:
return GlobalValue::ProtectedVisibility;
825 case 0:
return GlobalValue::DefaultStorageClass;
826 case 1:
return GlobalValue::DLLImportStorageClass;
827 case 2:
return GlobalValue::DLLExportStorageClass;
833 case 0:
return GlobalVariable::NotThreadLocal;
835 case 1:
return GlobalVariable::GeneralDynamicTLSModel;
836 case 2:
return GlobalVariable::LocalDynamicTLSModel;
837 case 3:
return GlobalVariable::InitialExecTLSModel;
838 case 4:
return GlobalVariable::LocalExecTLSModel;
882 return IsFP ? Instruction::FSub : Instruction::Sub;
884 return IsFP ? Instruction::FMul : Instruction::Mul;
886 return IsFP ? -1 : Instruction::UDiv;
888 return IsFP ? Instruction::FDiv : Instruction::SDiv;
890 return IsFP ? -1 : Instruction::URem;
892 return IsFP ? Instruction::FRem : Instruction::SRem;
894 return IsFP ? -1 : Instruction::Shl;
896 return IsFP ? -1 : Instruction::LShr;
898 return IsFP ? -1 : Instruction::AShr;
910 default:
return AtomicRMWInst::BAD_BINOP;
952 return Comdat::ExactMatch;
954 return Comdat::Largest;
956 return Comdat::NoDuplicates;
958 return Comdat::SameSize;
964 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
966 if (0 != (Val & FastMathFlags::NoNaNs))
968 if (0 != (Val & FastMathFlags::NoInfs))
970 if (0 != (Val & FastMathFlags::NoSignedZeros))
972 if (0 != (Val & FastMathFlags::AllowReciprocal))
985 Type *BitcodeReader::getTypeByID(
unsigned ID) {
987 if (ID >= TypeList.size())
990 if (
Type *Ty = TypeList[ID])
995 return TypeList[
ID] = createIdentifiedStructType(
Context);
1000 auto *
Ret = StructType::create(Context, Name);
1001 IdentifiedStructTypes.push_back(
Ret);
1006 auto *
Ret = StructType::create(Context);
1007 IdentifiedStructTypes.push_back(
Ret);
1017 case Attribute::EndAttrKinds:
1021 case Attribute::ZExt:
return 1 << 0;
1022 case Attribute::SExt:
return 1 << 1;
1023 case Attribute::NoReturn:
return 1 << 2;
1024 case Attribute::InReg:
return 1 << 3;
1025 case Attribute::StructRet:
return 1 << 4;
1026 case Attribute::NoUnwind:
return 1 << 5;
1028 case Attribute::ByVal:
return 1 << 7;
1029 case Attribute::Nest:
return 1 << 8;
1030 case Attribute::ReadNone:
return 1 << 9;
1032 case Attribute::NoInline:
return 1 << 11;
1033 case Attribute::AlwaysInline:
return 1 << 12;
1034 case Attribute::OptimizeForSize:
return 1 << 13;
1035 case Attribute::StackProtect:
return 1 << 14;
1036 case Attribute::StackProtectReq:
return 1 << 15;
1037 case Attribute::Alignment:
return 31 << 16;
1038 case Attribute::NoCapture:
return 1 << 21;
1039 case Attribute::NoRedZone:
return 1 << 22;
1040 case Attribute::NoImplicitFloat:
return 1 << 23;
1041 case Attribute::Naked:
return 1 << 24;
1042 case Attribute::InlineHint:
return 1 << 25;
1043 case Attribute::StackAlignment:
return 7 << 26;
1044 case Attribute::ReturnsTwice:
return 1 << 29;
1045 case Attribute::UWTable:
return 1 << 30;
1046 case Attribute::NonLazyBind:
return 1U << 31;
1047 case Attribute::SanitizeAddress:
return 1ULL << 32;
1048 case Attribute::MinSize:
return 1ULL << 33;
1049 case Attribute::NoDuplicate:
return 1ULL << 34;
1050 case Attribute::StackProtectStrong:
return 1ULL << 35;
1051 case Attribute::SanitizeThread:
return 1ULL << 36;
1052 case Attribute::SanitizeMemory:
return 1ULL << 37;
1053 case Attribute::NoBuiltin:
return 1ULL << 38;
1054 case Attribute::Returned:
return 1ULL << 39;
1056 case Attribute::Builtin:
return 1ULL << 41;
1057 case Attribute::OptimizeNone:
return 1ULL << 42;
1058 case Attribute::InAlloca:
return 1ULL << 43;
1059 case Attribute::NonNull:
return 1ULL << 44;
1062 case Attribute::SafeStack:
return 1ULL << 47;
1063 case Attribute::NoRecurse:
return 1ULL << 48;
1064 case Attribute::InaccessibleMemOnly:
return 1ULL << 49;
1065 case Attribute::InaccessibleMemOrArgMemOnly:
return 1ULL << 50;
1066 case Attribute::SwiftSelf:
return 1ULL << 51;
1067 case Attribute::SwiftError:
return 1ULL << 52;
1069 case Attribute::Dereferenceable:
1072 case Attribute::DereferenceableOrNull:
1076 case Attribute::ArgMemOnly:
1079 case Attribute::AllocSize:
1091 if (
I == Attribute::Dereferenceable ||
1092 I == Attribute::DereferenceableOrNull ||
1093 I == Attribute::ArgMemOnly ||
1094 I == Attribute::AllocSize)
1097 if (
I == Attribute::Alignment)
1099 else if (
I == Attribute::StackAlignment)
1111 uint64_t EncodedAttrs) {
1116 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1118 "Alignment must be a power of two.");
1123 (EncodedAttrs & 0xffff));
1126 Error BitcodeReader::parseAttributeBlock() {
1128 return error(
"Invalid record");
1130 if (!MAttributes.empty())
1131 return error(
"Invalid multiple blocks");
1141 switch (Entry.
Kind) {
1142 case BitstreamEntry::SubBlock:
1144 return error(
"Malformed block");
1145 case BitstreamEntry::EndBlock:
1147 case BitstreamEntry::Record:
1159 if (Record.
size() & 1)
1160 return error(
"Invalid record");
1162 for (
unsigned i = 0, e = Record.
size(); i != e; i += 2) {
1165 Attrs.
push_back(AttributeSet::get(Context, Record[i], B));
1168 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1173 for (
unsigned i = 0, e = Record.
size(); i != e; ++
i)
1174 Attrs.
push_back(MAttributeGroups[Record[i]]);
1176 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1190 return Attribute::Alignment;
1192 return Attribute::AlwaysInline;
1194 return Attribute::ArgMemOnly;
1196 return Attribute::Builtin;
1198 return Attribute::ByVal;
1200 return Attribute::InAlloca;
1206 return Attribute::InaccessibleMemOnly;
1208 return Attribute::InaccessibleMemOrArgMemOnly;
1210 return Attribute::InlineHint;
1212 return Attribute::InReg;
1216 return Attribute::MinSize;
1218 return Attribute::Naked;
1220 return Attribute::Nest;
1224 return Attribute::NoBuiltin;
1226 return Attribute::NoCapture;
1228 return Attribute::NoDuplicate;
1230 return Attribute::NoImplicitFloat;
1232 return Attribute::NoInline;
1234 return Attribute::NoRecurse;
1236 return Attribute::NonLazyBind;
1238 return Attribute::NonNull;
1240 return Attribute::Dereferenceable;
1242 return Attribute::DereferenceableOrNull;
1244 return Attribute::AllocSize;
1246 return Attribute::NoRedZone;
1248 return Attribute::NoReturn;
1250 return Attribute::NoUnwind;
1252 return Attribute::OptimizeForSize;
1254 return Attribute::OptimizeNone;
1256 return Attribute::ReadNone;
1260 return Attribute::Returned;
1262 return Attribute::ReturnsTwice;
1264 return Attribute::SExt;
1266 return Attribute::StackAlignment;
1268 return Attribute::StackProtect;
1270 return Attribute::StackProtectReq;
1272 return Attribute::StackProtectStrong;
1274 return Attribute::SafeStack;
1276 return Attribute::StructRet;
1278 return Attribute::SanitizeAddress;
1280 return Attribute::SanitizeThread;
1282 return Attribute::SanitizeMemory;
1284 return Attribute::SwiftError;
1286 return Attribute::SwiftSelf;
1288 return Attribute::UWTable;
1292 return Attribute::ZExt;
1296 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1297 unsigned &Alignment) {
1300 if (Exponent > Value::MaxAlignmentExponent + 1)
1301 return error(
"Invalid alignment value");
1302 Alignment = (1 <<
static_cast<unsigned>(Exponent)) >> 1;
1309 return error(
"Unknown attribute kind (" +
Twine(Code) +
")");
1313 Error BitcodeReader::parseAttributeGroupBlock() {
1315 return error(
"Invalid record");
1317 if (!MAttributeGroups.empty())
1318 return error(
"Invalid multiple blocks");
1326 switch (Entry.
Kind) {
1327 case BitstreamEntry::SubBlock:
1329 return error(
"Malformed block");
1330 case BitstreamEntry::EndBlock:
1332 case BitstreamEntry::Record:
1343 if (Record.
size() < 3)
1344 return error(
"Invalid record");
1346 uint64_t GrpID = Record[0];
1347 uint64_t Idx = Record[1];
1350 for (
unsigned i = 2, e = Record.
size(); i != e; ++
i) {
1351 if (Record[i] == 0) {
1357 }
else if (Record[i] == 1) {
1361 if (Kind == Attribute::Alignment)
1363 else if (Kind == Attribute::StackAlignment)
1365 else if (Kind == Attribute::Dereferenceable)
1367 else if (Kind == Attribute::DereferenceableOrNull)
1369 else if (Kind == Attribute::AllocSize)
1372 assert((Record[i] == 3 || Record[i] == 4) &&
1373 "Invalid attribute group entry");
1374 bool HasValue = (Record[i++] == 4);
1378 while (Record[i] != 0 && i != e)
1379 KindStr += Record[i++];
1380 assert(Record[i] == 0 &&
"Kind string not null terminated");
1385 while (Record[i] != 0 && i != e)
1386 ValStr += Record[i++];
1387 assert(Record[i] == 0 &&
"Value string not null terminated");
1394 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1401 Error BitcodeReader::parseTypeTable() {
1403 return error(
"Invalid record");
1405 return parseTypeTableBody();
1408 Error BitcodeReader::parseTypeTableBody() {
1409 if (!TypeList.empty())
1410 return error(
"Invalid multiple blocks");
1413 unsigned NumRecords = 0;
1421 switch (Entry.
Kind) {
1422 case BitstreamEntry::SubBlock:
1424 return error(
"Malformed block");
1425 case BitstreamEntry::EndBlock:
1426 if (NumRecords != TypeList.size())
1427 return error(
"Malformed block");
1429 case BitstreamEntry::Record:
1436 Type *ResultTy =
nullptr;
1439 return error(
"Invalid value");
1443 if (Record.
size() < 1)
1444 return error(
"Invalid record");
1445 TypeList.resize(Record[0]);
1448 ResultTy = Type::getVoidTy(Context);
1451 ResultTy = Type::getHalfTy(Context);
1454 ResultTy = Type::getFloatTy(Context);
1457 ResultTy = Type::getDoubleTy(Context);
1460 ResultTy = Type::getX86_FP80Ty(Context);
1463 ResultTy = Type::getFP128Ty(Context);
1466 ResultTy = Type::getPPC_FP128Ty(Context);
1469 ResultTy = Type::getLabelTy(Context);
1472 ResultTy = Type::getMetadataTy(Context);
1475 ResultTy = Type::getX86_MMXTy(Context);
1478 ResultTy = Type::getTokenTy(Context);
1481 if (Record.
size() < 1)
1482 return error(
"Invalid record");
1484 uint64_t NumBits = Record[0];
1485 if (NumBits < IntegerType::MIN_INT_BITS ||
1486 NumBits > IntegerType::MAX_INT_BITS)
1487 return error(
"Bitwidth for integer type out of range");
1488 ResultTy = IntegerType::get(Context, NumBits);
1493 if (Record.
size() < 1)
1494 return error(
"Invalid record");
1496 if (Record.
size() == 2)
1497 AddressSpace = Record[1];
1498 ResultTy = getTypeByID(Record[0]);
1501 return error(
"Invalid type");
1502 ResultTy = PointerType::get(ResultTy, AddressSpace);
1508 if (Record.
size() < 3)
1509 return error(
"Invalid record");
1511 for (
unsigned i = 3, e = Record.
size(); i != e; ++
i) {
1512 if (
Type *
T = getTypeByID(Record[i]))
1518 ResultTy = getTypeByID(Record[2]);
1519 if (!ResultTy || ArgTys.
size() < Record.
size()-3)
1520 return error(
"Invalid type");
1522 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1527 if (Record.
size() < 2)
1528 return error(
"Invalid record");
1530 for (
unsigned i = 2, e = Record.
size(); i != e; ++
i) {
1531 if (
Type *
T = getTypeByID(Record[i])) {
1532 if (!FunctionType::isValidArgumentType(
T))
1533 return error(
"Invalid function argument type");
1540 ResultTy = getTypeByID(Record[1]);
1541 if (!ResultTy || ArgTys.
size() < Record.
size()-2)
1542 return error(
"Invalid type");
1544 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1548 if (Record.
size() < 1)
1549 return error(
"Invalid record");
1551 for (
unsigned i = 1, e = Record.
size(); i != e; ++
i) {
1552 if (
Type *
T = getTypeByID(Record[i]))
1557 if (EltTys.
size() != Record.
size()-1)
1558 return error(
"Invalid type");
1559 ResultTy = StructType::get(Context, EltTys, Record[0]);
1563 if (convertToString(Record, 0, TypeName))
1564 return error(
"Invalid record");
1568 if (Record.
size() < 1)
1569 return error(
"Invalid record");
1571 if (NumRecords >= TypeList.size())
1572 return error(
"Invalid TYPE table");
1575 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1578 TypeList[NumRecords] =
nullptr;
1580 Res = createIdentifiedStructType(Context, TypeName);
1584 for (
unsigned i = 1, e = Record.
size(); i != e; ++
i) {
1585 if (
Type *
T = getTypeByID(Record[i]))
1590 if (EltTys.
size() != Record.
size()-1)
1591 return error(
"Invalid record");
1592 Res->
setBody(EltTys, Record[0]);
1597 if (Record.
size() != 1)
1598 return error(
"Invalid record");
1600 if (NumRecords >= TypeList.size())
1601 return error(
"Invalid TYPE table");
1604 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1607 TypeList[NumRecords] =
nullptr;
1609 Res = createIdentifiedStructType(Context, TypeName);
1615 if (Record.
size() < 2)
1616 return error(
"Invalid record");
1617 ResultTy = getTypeByID(Record[1]);
1619 return error(
"Invalid type");
1620 ResultTy = ArrayType::get(ResultTy, Record[0]);
1623 if (Record.
size() < 2)
1624 return error(
"Invalid record");
1626 return error(
"Invalid vector length");
1627 ResultTy = getTypeByID(Record[1]);
1629 return error(
"Invalid type");
1630 ResultTy = VectorType::get(ResultTy, Record[0]);
1634 if (NumRecords >= TypeList.size())
1635 return error(
"Invalid TYPE table");
1636 if (TypeList[NumRecords])
1638 "Invalid TYPE table: Only named structs can be forward referenced");
1639 assert(ResultTy &&
"Didn't read a type?");
1640 TypeList[NumRecords++] = ResultTy;
1644 Error BitcodeReader::parseOperandBundleTags() {
1646 return error(
"Invalid record");
1648 if (!BundleTags.empty())
1649 return error(
"Invalid multiple blocks");
1656 switch (Entry.
Kind) {
1657 case BitstreamEntry::SubBlock:
1659 return error(
"Malformed block");
1660 case BitstreamEntry::EndBlock:
1662 case BitstreamEntry::Record:
1670 return error(
"Invalid record");
1673 BundleTags.emplace_back();
1674 if (convertToString(Record, 0, BundleTags.
back()))
1675 return error(
"Invalid record");
1682 unsigned NameIndex, Triple &TT) {
1684 if (convertToString(Record, NameIndex, ValueName))
1685 return error(
"Invalid record");
1686 unsigned ValueID = Record[0];
1687 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1688 return error(
"Invalid record");
1689 Value *V = ValueList[ValueID];
1692 if (NameStr.find_first_of(0) != StringRef::npos)
1693 return error(
"Invalid value name");
1697 if (GO->getComdat() ==
reinterpret_cast<Comdat *
>(1)) {
1701 GO->setComdat(TheModule->getOrInsertComdat(V->
getName()));
1718 assert(Entry.
Kind == BitstreamEntry::SubBlock);
1730 Error BitcodeReader::parseValueSymbolTable(uint64_t
Offset) {
1731 uint64_t CurrentBit;
1749 unsigned FuncBitcodeOffsetDelta =
1753 return error(
"Invalid record");
1757 Triple TT(TheModule->getTargetTriple());
1765 switch (Entry.
Kind) {
1766 case BitstreamEntry::SubBlock:
1768 return error(
"Malformed block");
1769 case BitstreamEntry::EndBlock:
1773 case BitstreamEntry::Record:
1810 uint64_t FuncWordOffset = Record[1] - 1;
1813 uint64_t FuncBitOffset = FuncWordOffset * 32;
1814 DeferredFunctionInfo[
F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1818 if (FuncBitOffset > LastFunctionBlockBit)
1819 LastFunctionBlockBit = FuncBitOffset;
1823 if (convertToString(Record, 1, ValueName))
1824 return error(
"Invalid record");
1827 return error(
"Invalid record");
1839 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1849 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
1850 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1851 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
1852 IndirectSymbolInitWorklist;
1853 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1854 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1855 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
1857 GlobalInitWorklist.swap(GlobalInits);
1858 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
1859 FunctionPrefixWorklist.swap(FunctionPrefixes);
1860 FunctionPrologueWorklist.swap(FunctionPrologues);
1861 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
1863 while (!GlobalInitWorklist.empty()) {
1864 unsigned ValID = GlobalInitWorklist.back().second;
1865 if (ValID >= ValueList.size()) {
1867 GlobalInits.push_back(GlobalInitWorklist.back());
1869 if (
Constant *
C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1870 GlobalInitWorklist.back().first->setInitializer(
C);
1872 return error(
"Expected a constant");
1874 GlobalInitWorklist.pop_back();
1877 while (!IndirectSymbolInitWorklist.empty()) {
1878 unsigned ValID = IndirectSymbolInitWorklist.back().second;
1879 if (ValID >= ValueList.size()) {
1880 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
1882 Constant *
C = dyn_cast_or_null<Constant>(ValueList[ValID]);
1884 return error(
"Expected a constant");
1887 return error(
"Alias and aliasee types don't match");
1890 IndirectSymbolInitWorklist.pop_back();
1893 while (!FunctionPrefixWorklist.empty()) {
1894 unsigned ValID = FunctionPrefixWorklist.back().second;
1895 if (ValID >= ValueList.size()) {
1896 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1898 if (
Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1899 FunctionPrefixWorklist.back().first->setPrefixData(C);
1901 return error(
"Expected a constant");
1903 FunctionPrefixWorklist.pop_back();
1906 while (!FunctionPrologueWorklist.empty()) {
1907 unsigned ValID = FunctionPrologueWorklist.back().second;
1908 if (ValID >= ValueList.size()) {
1909 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1911 if (
Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1912 FunctionPrologueWorklist.back().first->setPrologueData(C);
1914 return error(
"Expected a constant");
1916 FunctionPrologueWorklist.pop_back();
1919 while (!FunctionPersonalityFnWorklist.empty()) {
1920 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
1921 if (ValID >= ValueList.size()) {
1922 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
1924 if (
Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1925 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
1927 return error(
"Expected a constant");
1929 FunctionPersonalityFnWorklist.pop_back();
1938 BitcodeReader::decodeSignRotatedValue);
1940 return APInt(TypeBits, Words);
1943 Error BitcodeReader::parseConstants() {
1945 return error(
"Invalid record");
1950 Type *CurTy = Type::getInt32Ty(Context);
1951 unsigned NextCstNo = ValueList.size();
1956 switch (Entry.
Kind) {
1957 case BitstreamEntry::SubBlock:
1959 return error(
"Malformed block");
1960 case BitstreamEntry::EndBlock:
1961 if (NextCstNo != ValueList.size())
1962 return error(
"Invalid constant reference");
1966 ValueList.resolveConstantForwardRefs();
1968 case BitstreamEntry::Record:
1975 Type *VoidType = Type::getVoidTy(Context);
1977 unsigned BitCode = Stream.
readRecord(Entry.
ID, Record);
1981 V = UndefValue::get(CurTy);
1985 return error(
"Invalid record");
1986 if (Record[0] >= TypeList.
size() || !TypeList[Record[0]])
1987 return error(
"Invalid record");
1988 if (TypeList[Record[0]] == VoidType)
1989 return error(
"Invalid constant type");
1990 CurTy = TypeList[Record[0]];
1993 V = Constant::getNullValue(CurTy);
1997 return error(
"Invalid record");
1998 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2002 return error(
"Invalid record");
2006 V = ConstantInt::get(Context, VInt);
2012 return error(
"Invalid record");
2014 V = ConstantFP::get(Context,
APFloat(APFloat::IEEEhalf(),
2015 APInt(16, (uint16_t)Record[0])));
2017 V = ConstantFP::get(Context,
APFloat(APFloat::IEEEsingle(),
2020 V = ConstantFP::get(Context,
APFloat(APFloat::IEEEdouble(),
2021 APInt(64, Record[0])));
2024 uint64_t Rearrange[2];
2025 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2026 Rearrange[1] = Record[0] >> 48;
2027 V = ConstantFP::get(Context,
APFloat(APFloat::x87DoubleExtended(),
2028 APInt(80, Rearrange)));
2030 V = ConstantFP::get(Context,
APFloat(APFloat::IEEEquad(),
2031 APInt(128, Record)));
2033 V = ConstantFP::get(Context,
APFloat(APFloat::PPCDoubleDouble(),
2034 APInt(128, Record)));
2036 V = UndefValue::get(CurTy);
2042 return error(
"Invalid record");
2044 unsigned Size = Record.size();
2047 if (
StructType *STy = dyn_cast<StructType>(CurTy)) {
2048 for (
unsigned i = 0; i != Size; ++
i)
2049 Elts.
push_back(ValueList.getConstantFwdRef(Record[i],
2050 STy->getElementType(i)));
2051 V = ConstantStruct::get(STy, Elts);
2052 }
else if (
ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2053 Type *EltTy = ATy->getElementType();
2054 for (
unsigned i = 0; i != Size; ++
i)
2055 Elts.
push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2056 V = ConstantArray::get(ATy, Elts);
2057 }
else if (
VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2058 Type *EltTy = VTy->getElementType();
2059 for (
unsigned i = 0; i != Size; ++
i)
2060 Elts.
push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2061 V = ConstantVector::get(Elts);
2063 V = UndefValue::get(CurTy);
2070 return error(
"Invalid record");
2073 V = ConstantDataArray::getString(Context, Elts,
2079 return error(
"Invalid record");
2081 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2084 if (isa<VectorType>(CurTy))
2085 V = ConstantDataVector::get(Context, Elts);
2087 V = ConstantDataArray::get(Context, Elts);
2090 if (isa<VectorType>(CurTy))
2091 V = ConstantDataVector::get(Context, Elts);
2093 V = ConstantDataArray::get(Context, Elts);
2096 if (isa<VectorType>(CurTy))
2097 V = ConstantDataVector::get(Context, Elts);
2099 V = ConstantDataArray::get(Context, Elts);
2102 if (isa<VectorType>(CurTy))
2103 V = ConstantDataVector::get(Context, Elts);
2105 V = ConstantDataArray::get(Context, Elts);
2108 if (isa<VectorType>(CurTy))
2109 V = ConstantDataVector::getFP(Context, Elts);
2111 V = ConstantDataArray::getFP(Context, Elts);
2114 if (isa<VectorType>(CurTy))
2115 V = ConstantDataVector::getFP(Context, Elts);
2117 V = ConstantDataArray::getFP(Context, Elts);
2120 if (isa<VectorType>(CurTy))
2121 V = ConstantDataVector::getFP(Context, Elts);
2123 V = ConstantDataArray::getFP(Context, Elts);
2125 return error(
"Invalid type for value");
2130 if (Record.size() < 3)
2131 return error(
"Invalid record");
2134 V = UndefValue::get(CurTy);
2136 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2137 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2139 if (Record.size() >= 4) {
2141 Opc == Instruction::Sub ||
2142 Opc == Instruction::Mul ||
2143 Opc == Instruction::Shl) {
2145 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2147 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2148 }
else if (Opc == Instruction::SDiv ||
2149 Opc == Instruction::UDiv ||
2150 Opc == Instruction::LShr ||
2151 Opc == Instruction::AShr) {
2153 Flags |= SDivOperator::IsExact;
2156 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2161 if (Record.size() < 3)
2162 return error(
"Invalid record");
2165 V = UndefValue::get(CurTy);
2167 Type *OpTy = getTypeByID(Record[1]);
2169 return error(
"Invalid record");
2170 Constant *
Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2172 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2181 Type *PointeeType =
nullptr;
2184 PointeeType = getTypeByID(Record[OpNum++]);
2186 bool InBounds =
false;
2189 uint64_t Op = Record[OpNum++];
2191 InRangeIndex = Op >> 1;
2196 while (OpNum != Record.size()) {
2197 Type *ElTy = getTypeByID(Record[OpNum++]);
2199 return error(
"Invalid record");
2200 Elts.
push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2205 cast<PointerType>(Elts[0]->
getType()->getScalarType())
2207 return error(
"Explicit gep operator type does not match pointee type "
2208 "of pointer operand");
2210 if (Elts.
size() < 1)
2211 return error(
"Invalid gep with no operands");
2214 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2215 InBounds, InRangeIndex);
2219 if (Record.size() < 3)
2220 return error(
"Invalid record");
2222 Type *SelectorTy = Type::getInt1Ty(Context);
2226 if (
VectorType *VTy = dyn_cast<VectorType>(CurTy))
2227 if (
Value *V = ValueList[Record[0]])
2228 if (SelectorTy != V->
getType())
2229 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2231 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2233 ValueList.getConstantFwdRef(Record[1],CurTy),
2234 ValueList.getConstantFwdRef(Record[2],CurTy));
2239 if (Record.size() < 3)
2240 return error(
"Invalid record");
2242 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2244 return error(
"Invalid record");
2245 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2247 if (Record.size() == 4) {
2248 Type *IdxTy = getTypeByID(Record[2]);
2250 return error(
"Invalid record");
2251 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2253 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2255 return error(
"Invalid record");
2256 V = ConstantExpr::getExtractElement(Op0, Op1);
2262 if (Record.size() < 3 || !OpTy)
2263 return error(
"Invalid record");
2264 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2265 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2268 if (Record.size() == 4) {
2269 Type *IdxTy = getTypeByID(Record[2]);
2271 return error(
"Invalid record");
2272 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2274 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2276 return error(
"Invalid record");
2277 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2282 if (Record.size() < 3 || !OpTy)
2283 return error(
"Invalid record");
2284 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2285 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2286 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2288 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2289 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2295 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2296 if (Record.size() < 4 || !RTy || !OpTy)
2297 return error(
"Invalid record");
2298 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2299 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2300 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2302 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2303 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2307 if (Record.size() < 4)
2308 return error(
"Invalid record");
2309 Type *OpTy = getTypeByID(Record[0]);
2311 return error(
"Invalid record");
2312 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2313 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2316 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2318 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2324 if (Record.size() < 2)
2325 return error(
"Invalid record");
2326 std::string AsmStr, ConstrStr;
2327 bool HasSideEffects = Record[0] & 1;
2328 bool IsAlignStack = Record[0] >> 1;
2329 unsigned AsmStrSize = Record[1];
2330 if (2+AsmStrSize >= Record.size())
2331 return error(
"Invalid record");
2332 unsigned ConstStrSize = Record[2+AsmStrSize];
2333 if (3+AsmStrSize+ConstStrSize > Record.size())
2334 return error(
"Invalid record");
2336 for (
unsigned i = 0; i != AsmStrSize; ++
i)
2337 AsmStr += (
char)Record[2+
i];
2338 for (
unsigned i = 0; i != ConstStrSize; ++
i)
2339 ConstrStr += (
char)Record[3+AsmStrSize+
i];
2342 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2348 if (Record.size() < 2)
2349 return error(
"Invalid record");
2350 std::string AsmStr, ConstrStr;
2351 bool HasSideEffects = Record[0] & 1;
2352 bool IsAlignStack = (Record[0] >> 1) & 1;
2353 unsigned AsmDialect = Record[0] >> 2;
2354 unsigned AsmStrSize = Record[1];
2355 if (2+AsmStrSize >= Record.size())
2356 return error(
"Invalid record");
2357 unsigned ConstStrSize = Record[2+AsmStrSize];
2358 if (3+AsmStrSize+ConstStrSize > Record.size())
2359 return error(
"Invalid record");
2361 for (
unsigned i = 0; i != AsmStrSize; ++
i)
2362 AsmStr += (
char)Record[2+
i];
2363 for (
unsigned i = 0; i != ConstStrSize; ++
i)
2364 ConstrStr += (
char)Record[3+AsmStrSize+
i];
2367 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2372 if (Record.size() < 3)
2373 return error(
"Invalid record");
2374 Type *FnTy = getTypeByID(Record[0]);
2376 return error(
"Invalid record");
2378 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2380 return error(
"Invalid record");
2385 unsigned BBID = Record[2];
2388 return error(
"Invalid ID");
2391 for (
size_t I = 0,
E = BBID;
I !=
E; ++
I) {
2393 return error(
"Invalid ID");
2400 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2402 BasicBlockFwdRefQueue.push_back(Fn);
2403 if (FwdBBs.size() < BBID + 1)
2404 FwdBBs.resize(BBID + 1);
2406 FwdBBs[BBID] = BasicBlock::Create(Context);
2409 V = BlockAddress::get(Fn, BB);
2414 ValueList.assignValue(V, NextCstNo);
2419 Error BitcodeReader::parseUseLists() {
2421 return error(
"Invalid record");
2429 switch (Entry.
Kind) {
2430 case BitstreamEntry::SubBlock:
2432 return error(
"Malformed block");
2433 case BitstreamEntry::EndBlock:
2435 case BitstreamEntry::Record:
2450 unsigned RecordLength = Record.
size();
2451 if (RecordLength < 3)
2453 return error(
"Invalid record");
2454 unsigned ID = Record.
back();
2459 assert(ID < FunctionBBs.size() &&
"Basic block not found");
2460 V = FunctionBBs[
ID];
2463 unsigned NumUses = 0;
2466 if (++NumUses > Record.
size())
2468 Order[&U] = Record[NumUses - 1];
2470 if (Order.
size() != Record.
size() || NumUses > Record.
size())
2486 Error BitcodeReader::rememberAndSkipMetadata() {
2489 DeferredMetadataInfo.push_back(CurBit);
2493 return error(
"Invalid record");
2497 Error BitcodeReader::materializeMetadata() {
2498 for (uint64_t BitPos : DeferredMetadataInfo) {
2501 if (
Error Err = MDLoader->parseModuleMetadata())
2504 DeferredMetadataInfo.clear();
2508 void BitcodeReader::setStripDebugInfo() {
StripDebugInfo =
true; }
2512 Error BitcodeReader::rememberAndSkipFunctionBody() {
2514 if (FunctionsWithBodies.empty())
2515 return error(
"Insufficient function protos");
2518 FunctionsWithBodies.pop_back();
2523 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2524 "Mismatch between VST and scanned function offsets");
2525 DeferredFunctionInfo[Fn] = CurBit;
2529 return error(
"Invalid record");
2533 Error BitcodeReader::globalCleanup() {
2535 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
2537 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2538 return error(
"Malformed global initializer set");
2544 UpgradedIntrinsics[&F] = NewFn;
2549 RemangledIntrinsics[&F] = Remangled.getValue();
2558 std::vector<std::pair<GlobalVariable*, unsigned> >().
swap(GlobalInits);
2559 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().
swap(
2560 IndirectSymbolInits);
2568 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2572 return error(
"Could not find function in stream");
2574 if (!SeenFirstFunctionBody)
2575 return error(
"Trying to materialize functions before seeing function blocks");
2579 assert(SeenValueSymbolTable);
2585 switch (Entry.
Kind) {
2587 return error(
"Expect SubBlock");
2588 case BitstreamEntry::SubBlock:
2591 return error(
"Expect function block");
2593 if (
Error Err = rememberAndSkipFunctionBody())
2602 bool BitcodeReaderBase::readBlockInfo() {
2606 BlockInfo = std::move(*NewBlockInfo);
2610 Error BitcodeReader::parseModule(uint64_t ResumeBit,
2611 bool ShouldLazyLoadMetadata) {
2615 return error(
"Invalid record");
2618 std::vector<std::string> SectionTable;
2619 std::vector<std::string> GCTable;
2625 switch (Entry.
Kind) {
2627 return error(
"Malformed block");
2628 case BitstreamEntry::EndBlock:
2629 return globalCleanup();
2631 case BitstreamEntry::SubBlock:
2635 return error(
"Invalid record");
2638 if (readBlockInfo())
2639 return error(
"Malformed block");
2642 if (
Error Err = parseAttributeBlock())
2646 if (
Error Err = parseAttributeGroupBlock())
2650 if (
Error Err = parseTypeTable())
2654 if (!SeenValueSymbolTable) {
2660 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
2661 if (
Error Err = parseValueSymbolTable())
2663 SeenValueSymbolTable =
true;
2669 return error(
"Invalid record");
2673 if (
Error Err = parseConstants())
2675 if (
Error Err = resolveGlobalAndIndirectSymbolInits())
2679 if (ShouldLazyLoadMetadata) {
2680 if (
Error Err = rememberAndSkipMetadata())
2684 assert(DeferredMetadataInfo.empty() &&
"Unexpected deferred metadata");
2685 if (
Error Err = MDLoader->parseModuleMetadata())
2689 if (
Error Err = MDLoader->parseMetadataKinds())
2695 if (!SeenFirstFunctionBody) {
2696 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2697 if (
Error Err = globalCleanup())
2699 SeenFirstFunctionBody =
true;
2702 if (VSTOffset > 0) {
2706 if (!SeenValueSymbolTable) {
2707 if (
Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
2709 SeenValueSymbolTable =
true;
2722 return error(
"Invalid record");
2731 if (
Error Err = rememberAndSkipFunctionBody())
2738 if (SeenValueSymbolTable) {
2742 return globalCleanup();
2746 if (
Error Err = parseUseLists())
2750 if (
Error Err = parseOperandBundleTags())
2756 case BitstreamEntry::Record:
2766 if (Record.
size() < 1)
2767 return error(
"Invalid record");
2769 unsigned module_version = Record[0];
2770 switch (module_version) {
2772 return error(
"Invalid value");
2774 UseRelativeIDs =
false;
2777 UseRelativeIDs =
true;
2784 if (convertToString(Record, 0, S))
2785 return error(
"Invalid record");
2786 TheModule->setTargetTriple(S);
2791 if (convertToString(Record, 0, S))
2792 return error(
"Invalid record");
2793 TheModule->setDataLayout(S);
2798 if (convertToString(Record, 0, S))
2799 return error(
"Invalid record");
2800 TheModule->setModuleInlineAsm(S);
2806 if (convertToString(Record, 0, S))
2807 return error(
"Invalid record");
2813 if (convertToString(Record, 0, S))
2814 return error(
"Invalid record");
2815 SectionTable.push_back(S);
2820 if (convertToString(Record, 0, S))
2821 return error(
"Invalid record");
2822 GCTable.push_back(S);
2826 if (Record.
size() < 2)
2827 return error(
"Invalid record");
2829 unsigned ComdatNameSize = Record[1];
2830 std::string ComdatName;
2831 ComdatName.
reserve(ComdatNameSize);
2832 for (
unsigned i = 0; i != ComdatNameSize; ++
i)
2833 ComdatName += (
char)Record[2 +
i];
2834 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2836 ComdatList.push_back(C);
2844 if (Record.
size() < 6)
2845 return error(
"Invalid record");
2846 Type *Ty = getTypeByID(Record[0]);
2848 return error(
"Invalid record");
2849 bool isConstant = Record[1] & 1;
2850 bool explicitType = Record[1] & 2;
2853 AddressSpace = Record[1] >> 2;
2856 return error(
"Invalid type for value");
2857 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2858 Ty = cast<PointerType>(Ty)->getElementType();
2861 uint64_t RawLinkage = Record[3];
2864 if (
Error Err = parseAlignmentValue(Record[4], Alignment))
2868 if (Record[5]-1 >= SectionTable.
size())
2869 return error(
"Invalid ID");
2870 Section = SectionTable[Record[5]-1];
2874 if (Record.
size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2878 GlobalVariable::ThreadLocalMode
TLM = GlobalVariable::NotThreadLocal;
2879 if (Record.
size() > 7)
2883 if (Record.
size() > 8)
2886 bool ExternallyInitialized =
false;
2887 if (Record.
size() > 9)
2888 ExternallyInitialized = Record[9];
2891 new GlobalVariable(*TheModule, Ty, isConstant, Linkage,
nullptr,
"",
nullptr,
2892 TLM, AddressSpace, ExternallyInitialized);
2894 if (!Section.empty())
2899 if (Record.
size() > 10)
2904 ValueList.push_back(NewGV);
2907 if (
unsigned InitID = Record[2])
2908 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2910 if (Record.
size() > 11) {
2911 if (
unsigned ComdatID = Record[11]) {
2912 if (ComdatID > ComdatList.size())
2913 return error(
"Invalid global variable comdat ID");
2914 NewGV->
setComdat(ComdatList[ComdatID - 1]);
2917 NewGV->
setComdat(reinterpret_cast<Comdat *>(1));
2926 if (Record.
size() < 8)
2927 return error(
"Invalid record");
2928 Type *Ty = getTypeByID(Record[0]);
2930 return error(
"Invalid record");
2931 if (
auto *PTy = dyn_cast<PointerType>(Ty))
2935 return error(
"Invalid type for value");
2938 return error(
"Invalid calling convention ID");
2940 Function *
Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2944 bool isProto = Record[2];
2945 uint64_t RawLinkage = Record[3];
2950 if (
Error Err = parseAlignmentValue(Record[5], Alignment))
2954 if (Record[6]-1 >= SectionTable.
size())
2955 return error(
"Invalid ID");
2962 if (Record.
size() > 8 && Record[8]) {
2963 if (Record[8]-1 >= GCTable.
size())
2964 return error(
"Invalid ID");
2965 Func->
setGC(GCTable[Record[8] - 1]);
2968 if (Record.
size() > 9)
2971 if (Record.
size() > 10 && Record[10] != 0)
2972 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2974 if (Record.
size() > 11)
2979 if (Record.
size() > 12) {
2980 if (
unsigned ComdatID = Record[12]) {
2981 if (ComdatID > ComdatList.size())
2982 return error(
"Invalid function comdat ID");
2983 Func->
setComdat(ComdatList[ComdatID - 1]);
2986 Func->
setComdat(reinterpret_cast<Comdat *>(1));
2989 if (Record.
size() > 13 && Record[13] != 0)
2990 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2992 if (Record.
size() > 14 && Record[14] != 0)
2993 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2995 ValueList.push_back(Func);
3001 FunctionsWithBodies.push_back(Func);
3002 DeferredFunctionInfo[
Func] = 0;
3014 return error(
"Invalid record");
3016 Type *Ty = getTypeByID(Record[OpNum++]);
3018 return error(
"Invalid record");
3024 return error(
"Invalid type for value");
3028 AddrSpace = Record[OpNum++];
3031 auto Val = Record[OpNum++];
3032 auto Linkage = Record[OpNum++];
3040 "",
nullptr, TheModule);
3043 if (OpNum != Record.
size()) {
3044 auto VisInd = OpNum++;
3049 if (OpNum != Record.
size())
3053 if (OpNum != Record.
size())
3055 if (OpNum != Record.
size())
3057 ValueList.push_back(NewGA);
3058 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3064 if (Record.
size() < 1 || Record[0] > ValueList.
size())
3065 return error(
"Invalid record");
3066 ValueList.shrinkTo(Record[0]);
3070 if (Record.
size() < 1)
3071 return error(
"Invalid record");
3075 VSTOffset = Record[0] - 1;
3080 if (convertToString(Record, 0, ValueName))
3081 return error(
"Invalid record");
3082 TheModule->setSourceFileName(ValueName);
3089 Error BitcodeReader::parseBitcodeInto(
Module *M,
bool ShouldLazyLoadMetadata,
3093 [&](
unsigned ID) {
return getTypeByID(ID); });
3094 return parseModule(0, ShouldLazyLoadMetadata);
3099 if (!isa<PointerType>(PtrType))
3100 return error(
"Load/Store operand is not a pointer type");
3101 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3103 if (ValType && ValType != ElemType)
3104 return error(
"Explicit load/store type does not match pointee "
3105 "type of pointer operand");
3106 if (!PointerType::isLoadableOrStorableType(ElemType))
3107 return error(
"Cannot load/store from pointer");
3114 return error(
"Invalid record");
3117 if (MDLoader->hasFwdRefs())
3118 return error(
"Invalid function metadata: incoming forward references");
3120 InstructionList.clear();
3121 unsigned ModuleValueListSize = ValueList.size();
3122 unsigned ModuleMDLoaderSize = MDLoader->size();
3126 ValueList.push_back(&
I);
3128 unsigned NextValueNo = ValueList.size();
3130 unsigned CurBBNo = 0;
3133 auto getLastInstruction = [&]() ->
Instruction * {
3134 if (CurBB && !CurBB->
empty())
3135 return &CurBB->
back();
3136 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3137 !FunctionBBs[CurBBNo - 1]->empty())
3138 return &FunctionBBs[CurBBNo - 1]->back();
3142 std::vector<OperandBundleDef> OperandBundles;
3150 switch (Entry.
Kind) {
3152 return error(
"Malformed block");
3153 case BitstreamEntry::EndBlock:
3154 goto OutOfRecordLoop;
3156 case BitstreamEntry::SubBlock:
3160 return error(
"Invalid record");
3163 if (
Error Err = parseConstants())
3165 NextValueNo = ValueList.size();
3168 if (
Error Err = parseValueSymbolTable())
3172 if (
Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3176 assert(DeferredMetadataInfo.empty() &&
3177 "Must read all module-level metadata before function-level");
3178 if (
Error Err = MDLoader->parseFunctionMetadata())
3182 if (
Error Err = parseUseLists())
3188 case BitstreamEntry::Record:
3196 unsigned BitCode = Stream.
readRecord(Entry.
ID, Record);
3199 return error(
"Invalid value");
3201 if (Record.
size() < 1 || Record[0] == 0)
3202 return error(
"Invalid record");
3204 FunctionBBs.resize(Record[0]);
3207 auto BBFRI = BasicBlockFwdRefs.find(F);
3208 if (BBFRI == BasicBlockFwdRefs.end()) {
3209 for (
unsigned i = 0, e = FunctionBBs.size(); i != e; ++
i)
3210 FunctionBBs[i] = BasicBlock::Create(Context,
"", F);
3212 auto &BBRefs = BBFRI->second;
3214 if (BBRefs.size() > FunctionBBs.size())
3215 return error(
"Invalid ID");
3216 assert(!BBRefs.empty() &&
"Unexpected empty array");
3217 assert(!BBRefs.front() &&
"Invalid reference to entry block");
3218 for (
unsigned I = 0,
E = FunctionBBs.size(), RE = BBRefs.size(); I !=
E;
3220 if (I < RE && BBRefs[I]) {
3221 BBRefs[
I]->insertInto(F);
3222 FunctionBBs[
I] = BBRefs[
I];
3224 FunctionBBs[
I] = BasicBlock::Create(Context,
"", F);
3228 BasicBlockFwdRefs.erase(BBFRI);
3231 CurBB = FunctionBBs[0];
3238 I = getLastInstruction();
3241 return error(
"Invalid record");
3242 I->setDebugLoc(LastLoc);
3247 I = getLastInstruction();
3248 if (!I || Record.
size() < 4)
3249 return error(
"Invalid record");
3251 unsigned Line = Record[0], Col = Record[1];
3252 unsigned ScopeID = Record[2], IAID = Record[3];
3254 MDNode *Scope =
nullptr, *IA =
nullptr;
3256 Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
3258 return error(
"Invalid record");
3261 IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
3263 return error(
"Invalid record");
3265 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3266 I->setDebugLoc(LastLoc);
3274 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3275 popValue(Record, OpNum, NextValueNo, LHS->
getType(), RHS) ||
3276 OpNum+1 > Record.
size())
3277 return error(
"Invalid record");
3281 return error(
"Invalid record");
3283 InstructionList.push_back(I);
3284 if (OpNum < Record.
size()) {
3286 Opc == Instruction::Sub ||
3287 Opc == Instruction::Mul ||
3288 Opc == Instruction::Shl) {
3290 cast<BinaryOperator>(I)->setHasNoSignedWrap(
true);
3292 cast<BinaryOperator>(
I)->setHasNoUnsignedWrap(
true);
3293 }
else if (Opc == Instruction::SDiv ||
3294 Opc == Instruction::UDiv ||
3295 Opc == Instruction::LShr ||
3296 Opc == Instruction::AShr) {
3298 cast<BinaryOperator>(
I)->setIsExact(
true);
3299 }
else if (isa<FPMathOperator>(I)) {
3302 I->setFastMathFlags(FMF);
3311 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3312 OpNum+2 != Record.
size())
3313 return error(
"Invalid record");
3315 Type *ResTy = getTypeByID(Record[OpNum]);
3317 if (Opc == -1 || !ResTy)
3318 return error(
"Invalid record");
3322 InstructionList.push_back(Temp);
3327 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3328 return error(
"Invalid cast");
3329 I = CastInst::Create(CastOp, Op, ResTy);
3331 InstructionList.push_back(I);
3343 InBounds = Record[OpNum++];
3344 Ty = getTypeByID(Record[OpNum++]);
3351 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3352 return error(
"Invalid record");
3361 "Explicit gep type does not match pointee type of pointer operand");
3364 while (OpNum != Record.
size()) {
3366 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3367 return error(
"Invalid record");
3371 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3373 InstructionList.push_back(I);
3375 cast<GetElementPtrInst>(
I)->setIsInBounds(
true);
3383 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3384 return error(
"Invalid record");
3386 unsigned RecSize = Record.
size();
3387 if (OpNum == RecSize)
3388 return error(
"EXTRACTVAL: Invalid instruction with 0 indices");
3392 for (; OpNum != RecSize; ++OpNum) {
3395 uint64_t Index = Record[OpNum];
3397 if (!IsStruct && !IsArray)
3398 return error(
"EXTRACTVAL: Invalid type");
3399 if ((
unsigned)Index != Index)
3400 return error(
"Invalid value");
3401 if (IsStruct && Index >= CurTy->
subtypes().size())
3402 return error(
"EXTRACTVAL: Invalid struct index");
3404 return error(
"EXTRACTVAL: Invalid array index");
3405 EXTRACTVALIdx.
push_back((
unsigned)Index);
3413 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3414 InstructionList.push_back(I);
3422 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3423 return error(
"Invalid record");
3425 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3426 return error(
"Invalid record");
3428 unsigned RecSize = Record.
size();
3429 if (OpNum == RecSize)
3430 return error(
"INSERTVAL: Invalid instruction with 0 indices");
3434 for (; OpNum != RecSize; ++OpNum) {
3437 uint64_t Index = Record[OpNum];
3439 if (!IsStruct && !IsArray)
3440 return error(
"INSERTVAL: Invalid type");
3441 if ((
unsigned)Index != Index)
3442 return error(
"Invalid value");
3443 if (IsStruct && Index >= CurTy->
subtypes().size())
3444 return error(
"INSERTVAL: Invalid struct index");
3446 return error(
"INSERTVAL: Invalid array index");
3448 INSERTVALIdx.
push_back((
unsigned)Index);
3456 return error(
"Inserted value type doesn't match aggregate type");
3458 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3459 InstructionList.push_back(I);
3467 Value *TrueVal, *FalseVal, *Cond;
3468 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3469 popValue(Record, OpNum, NextValueNo, TrueVal->
getType(), FalseVal) ||
3470 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3471 return error(
"Invalid record");
3473 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3474 InstructionList.push_back(I);
3482 Value *TrueVal, *FalseVal, *Cond;
3483 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3484 popValue(Record, OpNum, NextValueNo, TrueVal->
getType(), FalseVal) ||
3485 getValueTypePair(Record, OpNum, NextValueNo, Cond))
3486 return error(
"Invalid record");
3490 dyn_cast<VectorType>(Cond->
getType())) {
3492 if (vector_type->getElementType() != Type::getInt1Ty(Context))
3493 return error(
"Invalid type for value");
3496 if (Cond->
getType() != Type::getInt1Ty(Context))
3497 return error(
"Invalid type for value");
3500 I = SelectInst::Create(Cond, TrueVal, FalseVal);
3501 InstructionList.push_back(I);
3508 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3509 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3510 return error(
"Invalid record");
3512 return error(
"Invalid type for value");
3513 I = ExtractElementInst::Create(Vec, Idx);
3514 InstructionList.push_back(I);
3520 Value *Vec, *Elt, *Idx;
3521 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3522 return error(
"Invalid record");
3524 return error(
"Invalid type for value");
3525 if (popValue(Record, OpNum, NextValueNo,
3526 cast<VectorType>(Vec->
getType())->getElementType(), Elt) ||
3527 getValueTypePair(Record, OpNum, NextValueNo, Idx))
3528 return error(
"Invalid record");
3529 I = InsertElementInst::Create(Vec, Elt, Idx);
3530 InstructionList.push_back(I);
3537 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3538 popValue(Record, OpNum, NextValueNo, Vec1->
getType(), Vec2))
3539 return error(
"Invalid record");
3541 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3542 return error(
"Invalid record");
3544 return error(
"Invalid type for value");
3546 InstructionList.push_back(I);
3559 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3560 popValue(Record, OpNum, NextValueNo, LHS->
getType(), RHS))
3561 return error(
"Invalid record");
3563 unsigned PredVal = Record[OpNum];
3566 if (IsFP && Record.
size() > OpNum+1)
3569 if (OpNum+1 != Record.
size())
3570 return error(
"Invalid record");
3578 I->setFastMathFlags(FMF);
3579 InstructionList.push_back(I);
3585 unsigned Size = Record.
size();
3587 I = ReturnInst::Create(Context);
3588 InstructionList.push_back(I);
3593 Value *Op =
nullptr;
3594 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3595 return error(
"Invalid record");
3596 if (OpNum != Record.
size())
3597 return error(
"Invalid record");
3599 I = ReturnInst::Create(Context, Op);
3600 InstructionList.push_back(I);
3604 if (Record.
size() != 1 && Record.
size() != 3)
3605 return error(
"Invalid record");
3606 BasicBlock *TrueDest = getBasicBlock(Record[0]);
3608 return error(
"Invalid record");
3610 if (Record.
size() == 1) {
3611 I = BranchInst::Create(TrueDest);
3612 InstructionList.push_back(I);
3615 BasicBlock *FalseDest = getBasicBlock(Record[1]);
3616 Value *Cond = getValue(Record, 2, NextValueNo,
3617 Type::getInt1Ty(Context));
3618 if (!FalseDest || !Cond)
3619 return error(
"Invalid record");
3620 I = BranchInst::Create(TrueDest, FalseDest, Cond);
3621 InstructionList.push_back(I);
3626 if (Record.
size() != 1 && Record.
size() != 2)
3627 return error(
"Invalid record");
3630 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3632 return error(
"Invalid record");
3634 if (Record.
size() == 2) {
3635 UnwindDest = getBasicBlock(Record[Idx++]);
3637 return error(
"Invalid record");
3640 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
3641 InstructionList.push_back(I);
3645 if (Record.
size() != 2)
3646 return error(
"Invalid record");
3649 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3651 return error(
"Invalid record");
3652 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3654 return error(
"Invalid record");
3656 I = CatchReturnInst::Create(CatchPad, BB);
3657 InstructionList.push_back(I);
3662 if (Record.
size() < 2)
3663 return error(
"Invalid record");
3668 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3670 unsigned NumHandlers = Record[Idx++];
3673 for (
unsigned Op = 0; Op != NumHandlers; ++
Op) {
3674 BasicBlock *BB = getBasicBlock(Record[Idx++]);
3676 return error(
"Invalid record");
3681 if (Idx + 1 == Record.
size()) {
3682 UnwindDest = getBasicBlock(Record[Idx++]);
3684 return error(
"Invalid record");
3687 if (Record.
size() != Idx)
3688 return error(
"Invalid record");
3691 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3693 CatchSwitch->addHandler(Handler);
3695 InstructionList.push_back(I);
3701 if (Record.
size() < 2)
3702 return error(
"Invalid record");
3707 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3709 unsigned NumArgOperands = Record[Idx++];
3712 for (
unsigned Op = 0; Op != NumArgOperands; ++
Op) {
3714 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3715 return error(
"Invalid record");
3719 if (Record.
size() != Idx)
3720 return error(
"Invalid record");
3723 I = CleanupPadInst::Create(ParentPad, Args);
3725 I = CatchPadInst::Create(ParentPad, Args);
3726 InstructionList.push_back(I);
3731 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3737 Type *OpTy = getTypeByID(Record[1]);
3738 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->
getBitWidth();
3740 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3742 if (!OpTy || !Cond || !Default)
3743 return error(
"Invalid record");
3745 unsigned NumCases = Record[4];
3747 SwitchInst *
SI = SwitchInst::Create(Cond, Default, NumCases);
3748 InstructionList.push_back(SI);
3750 unsigned CurIdx = 5;
3751 for (
unsigned i = 0; i != NumCases; ++
i) {
3753 unsigned NumItems = Record[CurIdx++];
3754 for (
unsigned ci = 0; ci != NumItems; ++ci) {
3755 bool isSingleNumber = Record[CurIdx++];
3758 unsigned ActiveWords = 1;
3759 if (ValueBitWidth > 64)
3760 ActiveWords = Record[CurIdx++];
3763 CurIdx += ActiveWords;
3765 if (!isSingleNumber) {
3767 if (ValueBitWidth > 64)
3768 ActiveWords = Record[CurIdx++];
3770 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3771 CurIdx += ActiveWords;
3777 for ( ; Low.
ule(High); ++Low)
3778 CaseVals.
push_back(ConstantInt::get(Context, Low));
3780 CaseVals.
push_back(ConstantInt::get(Context, Low));
3782 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3784 cve = CaseVals.
end(); cvi != cve; ++cvi)
3793 if (Record.
size() < 3 || (Record.
size() & 1) == 0)
3794 return error(
"Invalid record");
3795 Type *OpTy = getTypeByID(Record[0]);
3796 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3797 BasicBlock *Default = getBasicBlock(Record[2]);
3798 if (!OpTy || !Cond || !Default)
3799 return error(
"Invalid record");
3800 unsigned NumCases = (Record.
size()-3)/2;
3801 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3802 InstructionList.push_back(SI);
3803 for (
unsigned i = 0, e = NumCases; i != e; ++
i) {
3805 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3806 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3807 if (!CaseVal || !DestBB) {
3809 return error(
"Invalid record");
3817 if (Record.
size() < 2)
3818 return error(
"Invalid record");
3819 Type *OpTy = getTypeByID(Record[0]);
3820 Value *
Address = getValue(Record, 1, NextValueNo, OpTy);
3821 if (!OpTy || !Address)
3822 return error(
"Invalid record");
3823 unsigned NumDests = Record.
size()-2;
3825 InstructionList.push_back(IBI);
3826 for (
unsigned i = 0, e = NumDests; i != e; ++
i) {
3827 if (
BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3831 return error(
"Invalid record");
3840 if (Record.
size() < 4)
3841 return error(
"Invalid record");
3844 unsigned CCInfo = Record[OpNum++];
3845 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3846 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3849 if (CCInfo >> 13 & 1 &&
3850 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3851 return error(
"Explicit invoke type is not a function type");
3854 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3855 return error(
"Invalid record");
3859 return error(
"Callee is not a pointer");
3863 return error(
"Callee is not of pointer to function type");
3865 return error(
"Explicit invoke type does not match pointee type of "
3868 return error(
"Insufficient operands to call");
3871 for (
unsigned i = 0, e = FTy->
getNumParams(); i != e; ++
i, ++OpNum) {
3872 Ops.
push_back(getValue(Record, OpNum, NextValueNo,
3875 return error(
"Invalid record");
3879 if (Record.
size() != OpNum)
3880 return error(
"Invalid record");
3883 while (OpNum != Record.
size()) {
3885 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3886 return error(
"Invalid record");
3891 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
3892 OperandBundles.clear();
3893 InstructionList.push_back(I);
3894 cast<InvokeInst>(
I)->setCallingConv(
3896 cast<InvokeInst>(
I)->setAttributes(PAL);
3901 Value *Val =
nullptr;
3902 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3903 return error(
"Invalid record");
3904 I = ResumeInst::Create(Val);
3905 InstructionList.push_back(I);
3910 InstructionList.push_back(I);
3913 if (Record.
size() < 1 || ((Record.
size()-1)&1))
3914 return error(
"Invalid record");
3915 Type *Ty = getTypeByID(Record[0]);
3917 return error(
"Invalid record");
3919 PHINode *PN = PHINode::Create(Ty, (Record.
size()-1)/2);
3920 InstructionList.push_back(PN);
3922 for (
unsigned i = 0, e = Record.
size()-1; i != e; i += 2) {
3928 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3930 V = getValue(Record, 1+i, NextValueNo, Ty);
3933 return error(
"Invalid record");
3945 if (Record.
size() < 3)
3946 return error(
"Invalid record");
3949 if (Record.
size() < 4)
3950 return error(
"Invalid record");
3952 Type *Ty = getTypeByID(Record[Idx++]);
3954 return error(
"Invalid record");
3956 Value *PersFn =
nullptr;
3957 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3958 return error(
"Invalid record");
3963 return error(
"Personality function mismatch");
3966 bool IsCleanup = !!Record[Idx++];
3967 unsigned NumClauses = Record[Idx++];
3970 for (
unsigned J = 0; J != NumClauses; ++J) {
3975 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3977 return error(
"Invalid record");
3980 assert((CT != LandingPadInst::Catch ||
3981 !isa<ArrayType>(Val->
getType())) &&
3982 "Catch clause has a invalid type!");
3983 assert((CT != LandingPadInst::Filter ||
3984 isa<ArrayType>(Val->
getType())) &&
3985 "Filter clause has invalid type!");
3990 InstructionList.push_back(I);
3995 if (Record.
size() != 4)
3996 return error(
"Invalid record");
3997 uint64_t AlignRecord = Record[3];
3998 const uint64_t InAllocaMask = uint64_t(1) << 5;
3999 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4000 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4001 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4003 bool InAlloca = AlignRecord & InAllocaMask;
4004 bool SwiftError = AlignRecord & SwiftErrorMask;
4005 Type *Ty = getTypeByID(Record[0]);
4006 if ((AlignRecord & ExplicitTypeMask) == 0) {
4007 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4009 return error(
"Old-style alloca with a non-pointer type");
4012 Type *OpTy = getTypeByID(Record[1]);
4013 Value *Size = getFnValueByID(Record[2], OpTy);
4015 if (
Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4019 return error(
"Invalid record");
4024 InstructionList.push_back(I);
4030 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4031 (OpNum + 2 != Record.
size() && OpNum + 3 != Record.
size()))
4032 return error(
"Invalid record");
4035 if (OpNum + 3 == Record.
size())
4036 Ty = getTypeByID(Record[OpNum++]);
4037 if (
Error Err = typeCheckLoadStoreInst(Ty, Op->
getType()))
4040 Ty = cast<PointerType>(Op->
getType())->getElementType();
4043 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4045 I =
new LoadInst(Ty, Op,
"", Record[OpNum + 1], Align);
4047 InstructionList.push_back(I);
4054 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4055 (OpNum + 4 != Record.
size() && OpNum + 5 != Record.
size()))
4056 return error(
"Invalid record");
4059 if (OpNum + 5 == Record.
size())
4060 Ty = getTypeByID(Record[OpNum++]);
4061 if (
Error Err = typeCheckLoadStoreInst(Ty, Op->
getType()))
4064 Ty = cast<PointerType>(Op->
getType())->getElementType();
4067 if (Ordering == AtomicOrdering::NotAtomic ||
4068 Ordering == AtomicOrdering::Release ||
4069 Ordering == AtomicOrdering::AcquireRelease)
4070 return error(
"Invalid record");
4071 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4072 return error(
"Invalid record");
4076 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4078 I =
new LoadInst(Op,
"", Record[OpNum+1], Align, Ordering, SynchScope);
4080 InstructionList.push_back(I);
4087 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4089 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4090 : popValue(Record, OpNum, NextValueNo,
4091 cast<PointerType>(Ptr->
getType())->getElementType(),
4093 OpNum + 2 != Record.
size())
4094 return error(
"Invalid record");
4099 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4101 I =
new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4102 InstructionList.push_back(I);
4110 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4111 !isa<PointerType>(Ptr->
getType()) ||
4113 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4114 : popValue(Record, OpNum, NextValueNo,
4115 cast<PointerType>(Ptr->
getType())->getElementType(),
4117 OpNum + 4 != Record.
size())
4118 return error(
"Invalid record");
4123 if (Ordering == AtomicOrdering::NotAtomic ||
4124 Ordering == AtomicOrdering::Acquire ||
4125 Ordering == AtomicOrdering::AcquireRelease)
4126 return error(
"Invalid record");
4128 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4129 return error(
"Invalid record");
4132 if (
Error Err = parseAlignmentValue(Record[OpNum], Align))
4134 I =
new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4135 InstructionList.push_back(I);
4144 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4146 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4147 : popValue(Record, OpNum, NextValueNo,
4148 cast<PointerType>(Ptr->
getType())->getElementType(),
4150 popValue(Record, OpNum, NextValueNo, Cmp->
getType(), New) ||
4151 Record.
size() < OpNum + 3 || Record.
size() > OpNum + 5)
4152 return error(
"Invalid record");
4154 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4155 SuccessOrdering == AtomicOrdering::Unordered)
4156 return error(
"Invalid record");
4162 if (Record.
size() < 7)
4164 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4170 cast<AtomicCmpXchgInst>(
I)->setVolatile(Record[OpNum]);
4172 if (Record.
size() < 8) {
4177 I = ExtractValueInst::Create(I, 0);
4179 cast<AtomicCmpXchgInst>(
I)->setWeak(Record[OpNum+4]);
4182 InstructionList.push_back(I);
4189 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4190 !isa<PointerType>(Ptr->
getType()) ||
4191 popValue(Record, OpNum, NextValueNo,
4192 cast<PointerType>(Ptr->
getType())->getElementType(), Val) ||
4193 OpNum+4 != Record.
size())
4194 return error(
"Invalid record");
4196 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4197 Operation > AtomicRMWInst::LAST_BINOP)
4198 return error(
"Invalid record");
4200 if (Ordering == AtomicOrdering::NotAtomic ||
4201 Ordering == AtomicOrdering::Unordered)
4202 return error(
"Invalid record");
4204 I =
new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4205 cast<AtomicRMWInst>(
I)->setVolatile(Record[OpNum+1]);
4206 InstructionList.push_back(I);
4210 if (2 != Record.
size())
4211 return error(
"Invalid record");
4213 if (Ordering == AtomicOrdering::NotAtomic ||
4214 Ordering == AtomicOrdering::Unordered ||
4215 Ordering == AtomicOrdering::Monotonic)
4216 return error(
"Invalid record");
4218 I =
new FenceInst(Context, Ordering, SynchScope);
4219 InstructionList.push_back(I);
4224 if (Record.
size() < 3)
4225 return error(
"Invalid record");
4229 unsigned CCInfo = Record[OpNum++];
4235 return error(
"Fast math flags indicator set for call with no FMF");
4240 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4241 return error(
"Explicit call type is not a function type");
4244 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4245 return error(
"Invalid record");
4249 return error(
"Callee is not a pointer type");
4253 return error(
"Callee is not of pointer to function type");
4255 return error(
"Explicit call type does not match pointee type of "
4258 return error(
"Insufficient operands to call");
4262 for (
unsigned i = 0, e = FTy->
getNumParams(); i != e; ++
i, ++OpNum) {
4264 Args.
push_back(getBasicBlock(Record[OpNum]));
4266 Args.
push_back(getValue(Record, OpNum, NextValueNo,
4269 return error(
"Invalid record");
4274 if (OpNum != Record.
size())
4275 return error(
"Invalid record");
4277 while (OpNum != Record.
size()) {
4279 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4280 return error(
"Invalid record");
4285 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4286 OperandBundles.clear();
4287 InstructionList.push_back(I);
4288 cast<CallInst>(
I)->setCallingConv(
4292 TCK = CallInst::TCK_Tail;
4294 TCK = CallInst::TCK_MustTail;
4296 TCK = CallInst::TCK_NoTail;
4297 cast<CallInst>(
I)->setTailCallKind(TCK);
4298 cast<CallInst>(
I)->setAttributes(PAL);
4300 if (!isa<FPMathOperator>(I))
4301 return error(
"Fast-math-flags specified for call without "
4302 "floating-point scalar or vector return type");
4303 I->setFastMathFlags(FMF);
4308 if (Record.
size() < 3)
4309 return error(
"Invalid record");
4310 Type *OpTy = getTypeByID(Record[0]);
4311 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4312 Type *ResTy = getTypeByID(Record[2]);
4313 if (!OpTy || !Op || !ResTy)
4314 return error(
"Invalid record");
4316 InstructionList.push_back(I);
4325 if (Record.
size() < 1 || Record[0] >= BundleTags.
size())
4326 return error(
"Invalid record");
4328 std::vector<Value *> Inputs;
4331 while (OpNum != Record.
size()) {
4333 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4334 return error(
"Invalid record");
4335 Inputs.push_back(Op);
4338 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4347 return error(
"Invalid instruction with no BB");
4349 if (!OperandBundles.empty()) {
4351 return error(
"Operand bundles found with no consumer");
4356 if (isa<TerminatorInst>(I)) {
4358 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] :
nullptr;
4362 if (I && !I->getType()->isVoidTy())
4363 ValueList.assignValue(I, NextValueNo++);
4368 if (!OperandBundles.empty())
4369 return error(
"Operand bundles found with no consumer");
4372 if (
Argument *
A = dyn_cast<Argument>(ValueList.back())) {
4373 if (!
A->getParent()) {
4375 for (
unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++
i){
4376 if ((
A = dyn_cast_or_null<Argument>(ValueList[i])) && !
A->getParent()) {
4377 A->replaceAllUsesWith(UndefValue::get(
A->getType()));
4381 return error(
"Never resolved value found in function");
4386 if (MDLoader->hasFwdRefs())
4387 return error(
"Invalid function metadata: outgoing forward refs");
4390 ValueList.shrinkTo(ModuleValueListSize);
4391 MDLoader->shrinkTo(ModuleMDLoaderSize);
4392 std::vector<BasicBlock*>().
swap(FunctionBBs);
4397 Error BitcodeReader::findFunctionInStream(
4400 while (DeferredFunctionInfoIterator->second == 0) {
4408 if (
Error Err = rememberAndSkipFunctionBodies())
4425 assert(DFII != DeferredFunctionInfo.
end() &&
"Deferred function not found!");
4428 if (DFII->second == 0)
4429 if (
Error Err = findFunctionInStream(F, DFII))
4433 if (
Error Err = materializeMetadata())
4439 if (
Error Err = parseFunctionBody(F))
4447 for (
auto &I : UpgradedIntrinsics) {
4448 for (
auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4452 if (
CallInst *CI = dyn_cast<CallInst>(U))
4458 for (
auto &I : RemangledIntrinsics)
4459 for (
auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4465 if (
DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
4469 if (!MDLoader->isStrippingTBAA()) {
4471 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4472 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4474 MDLoader->setStripTBAA(
true);
4481 return materializeForwardReferencedFunctions();
4484 Error BitcodeReader::materializeModule() {
4485 if (
Error Err = materializeMetadata())
4489 WillMaterializeAllForwardRefs =
true;
4494 if (
Error Err = materialize(&F))
4500 if (LastFunctionBlockBit || NextUnreadBit)
4501 if (
Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4502 ? LastFunctionBlockBit
4508 if (!BasicBlockFwdRefs.empty())
4509 return error(
"Never resolved function from blockaddress");
4515 for (
auto &I : UpgradedIntrinsics) {
4516 for (
auto *U : I.first->
users()) {
4517 if (
CallInst *CI = dyn_cast<CallInst>(U))
4520 if (!I.first->use_empty())
4521 I.first->replaceAllUsesWith(I.second);
4522 I.first->eraseFromParent();
4524 UpgradedIntrinsics.clear();
4526 for (
auto &I : RemangledIntrinsics) {
4527 I.first->replaceAllUsesWith(I.second);
4528 I.first->eraseFromParent();
4530 RemangledIntrinsics.clear();
4538 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes()
const {
4539 return IdentifiedStructTypes;
4542 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4544 : BitcodeReaderBase(std::move(Cursor)), TheIndex(TheIndex) {}
4546 std::pair<GlobalValue::GUID, GlobalValue::GUID>
4547 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(
unsigned ValueId) {
4548 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
4549 assert(VGI != ValueIdToCallGraphGUIDMap.end());
4556 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
4559 assert(Offset > 0 &&
"Expected non-zero VST offset");
4563 return error(
"Invalid record");
4573 switch (Entry.
Kind) {
4574 case BitstreamEntry::SubBlock:
4576 return error(
"Malformed block");
4577 case BitstreamEntry::EndBlock:
4581 case BitstreamEntry::Record:
4592 if (convertToString(Record, 1, ValueName))
4593 return error(
"Invalid record");
4594 unsigned ValueID = Record[0];
4595 assert(!SourceFileName.empty());
4596 auto VLI = ValueIdToLinkageMap.
find(ValueID);
4597 assert(VLI != ValueIdToLinkageMap.
end() &&
4598 "No linkage found for VST entry?");
4599 auto Linkage = VLI->second;
4600 std::string GlobalId =
4601 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4602 auto ValueGUID = GlobalValue::getGUID(GlobalId);
4603 auto OriginalNameID = ValueGUID;
4604 if (GlobalValue::isLocalLinkage(Linkage))
4605 OriginalNameID = GlobalValue::getGUID(ValueName);
4607 dbgs() <<
"GUID " << ValueGUID <<
"(" << OriginalNameID <<
") is "
4608 << ValueName <<
"\n";
4609 ValueIdToCallGraphGUIDMap[ValueID] =
4610 std::make_pair(ValueGUID, OriginalNameID);
4616 if (convertToString(Record, 2, ValueName))
4617 return error(
"Invalid record");
4618 unsigned ValueID = Record[0];
4619 assert(!SourceFileName.empty());
4620 auto VLI = ValueIdToLinkageMap.
find(ValueID);
4621 assert(VLI != ValueIdToLinkageMap.
end() &&
4622 "No linkage found for VST entry?");
4623 auto Linkage = VLI->second;
4624 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
4625 ValueName, VLI->second, SourceFileName);
4626 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
4627 auto OriginalNameID = FunctionGUID;
4628 if (GlobalValue::isLocalLinkage(Linkage))
4629 OriginalNameID = GlobalValue::getGUID(ValueName);
4631 dbgs() <<
"GUID " << FunctionGUID <<
"(" << OriginalNameID <<
") is "
4632 << ValueName <<
"\n";
4633 ValueIdToCallGraphGUIDMap[ValueID] =
4634 std::make_pair(FunctionGUID, OriginalNameID);
4641 unsigned ValueID = Record[0];
4645 ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
4655 Error ModuleSummaryIndexBitcodeReader::parseModule(
StringRef ModulePath) {
4657 return error(
"Invalid record");
4661 unsigned ValueId = 0;
4667 switch (Entry.
Kind) {
4669 return error(
"Malformed block");
4670 case BitstreamEntry::EndBlock:
4673 case BitstreamEntry::SubBlock:
4677 return error(
"Invalid record");
4681 if (readBlockInfo())
4682 return error(
"Malformed block");
4687 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4688 !SeenGlobalValSummary) &&
4689 "Expected early VST parse via VSTOffset record");
4691 return error(
"Invalid record");
4694 assert(!SeenValueSymbolTable &&
4695 "Already read VST when parsing summary block?");
4700 if (VSTOffset > 0) {
4701 if (
Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4703 SeenValueSymbolTable =
true;
4705 SeenGlobalValSummary =
true;
4706 if (
Error Err = parseEntireSummary(ModulePath))
4710 if (
Error Err = parseModuleStringTable())
4716 case BitstreamEntry::Record: {
4725 if (convertToString(Record, 0, ValueName))
4726 return error(
"Invalid record");
4727 SourceFileName = ValueName.
c_str();
4732 if (Record.
size() != 5)
4733 return error(
"Invalid hash length " +
Twine(Record.
size()).str());
4734 if (TheIndex.modulePaths().empty())
4736 TheIndex.addModulePath(ModulePath, 0);
4737 if (TheIndex.modulePaths().size() != 1)
4738 return error(
"Don't expect multiple modules defined?");
4739 auto &
Hash = TheIndex.modulePaths().begin()->second.second;
4741 for (
auto &Val : Record) {
4742 assert(!(Val >> 32) &&
"Unexpected high bits set");
4749 if (Record.size() < 1)
4750 return error(
"Invalid record");
4754 VSTOffset = Record[0] - 1;
4761 if (Record.size() < 6)
4762 return error(
"Invalid record");
4763 uint64_t RawLinkage = Record[3];
4765 ValueIdToLinkageMap[ValueId++] = Linkage;
4772 if (Record.size() < 8)
4773 return error(
"Invalid record");
4774 uint64_t RawLinkage = Record[3];
4776 ValueIdToLinkageMap[ValueId++] = Linkage;
4782 if (Record.size() < 6)
4783 return error(
"Invalid record");
4784 uint64_t RawLinkage = Record[3];
4786 ValueIdToLinkageMap[ValueId++] = Linkage;
4796 std::vector<ValueInfo>
4798 std::vector<ValueInfo>
Ret;
4799 Ret.reserve(Record.
size());
4800 for (uint64_t RefValueId : Record)
4801 Ret.push_back(getGUIDFromValueId(RefValueId).first);
4805 std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
4807 std::vector<FunctionSummary::EdgeTy>
Ret;
4808 Ret.reserve(Record.
size());
4809 for (
unsigned I = 0,
E = Record.
size(); I !=
E; ++
I) {
4812 if (IsOldProfileFormat) {
4816 }
else if (HasProfile)
4825 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
4828 return error(
"Invalid record");
4834 if (Entry.
Kind != BitstreamEntry::Record)
4835 return error(
"Invalid Summary Block: record for version expected");
4837 return error(
"Invalid Summary Block: version expected");
4839 const uint64_t
Version = Record[0];
4840 const bool IsOldProfileFormat = Version == 1;
4841 if (Version < 1 || Version > 3)
4842 return error(
"Invalid summary version " +
Twine(Version) +
4843 ", 1, 2 or 3 expected");
4849 bool Combined =
false;
4850 std::vector<GlobalValue::GUID> PendingTypeTests;
4855 switch (Entry.
Kind) {
4856 case BitstreamEntry::SubBlock:
4858 return error(
"Malformed block");
4859 case BitstreamEntry::EndBlock:
4869 TheIndex.removeEmptySummaryEntries();
4871 case BitstreamEntry::Record:
4895 unsigned ValueID = Record[0];
4896 uint64_t RawFlags = Record[1];
4897 unsigned InstCount = Record[2];
4898 unsigned NumRefs = Record[3];
4905 static int RefListStartIndex = 4;
4906 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
4907 assert(Record.
size() >= RefListStartIndex + NumRefs &&
4908 "Record size inconsistent with number of references");
4909 std::vector<ValueInfo> Refs = makeRefList(
4912 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
4914 IsOldProfileFormat, HasProfile);
4915 auto FS = llvm::make_unique<FunctionSummary>(
4916 Flags, InstCount, std::move(Refs), std::move(Calls),
4917 std::move(PendingTypeTests));
4918 PendingTypeTests.clear();
4919 auto GUID = getGUIDFromValueId(ValueID);
4920 FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
4921 FS->setOriginalName(GUID.second);
4922 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
4929 unsigned ValueID = Record[0];
4930 uint64_t RawFlags = Record[1];
4931 unsigned AliaseeID = Record[2];
4934 llvm::make_unique<AliasSummary>(
Flags, std::vector<ValueInfo>{});
4940 AS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
4943 auto *AliaseeSummary = TheIndex.getGlobalValueSummary(AliaseeGUID);
4944 if (!AliaseeSummary)
4945 return error(
"Alias expects aliasee summary to be parsed");
4946 AS->setAliasee(AliaseeSummary);
4948 auto GUID = getGUIDFromValueId(ValueID);
4949 AS->setOriginalName(GUID.second);
4950 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
4955 unsigned ValueID = Record[0];
4956 uint64_t RawFlags = Record[1];
4958 std::vector<ValueInfo> Refs =
4960 auto FS = llvm::make_unique<GlobalVarSummary>(
Flags, std::move(Refs));
4961 FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
4962 auto GUID = getGUIDFromValueId(ValueID);
4963 FS->setOriginalName(GUID.second);
4964 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
4973 unsigned ValueID = Record[0];
4974 uint64_t ModuleId = Record[1];
4975 uint64_t RawFlags = Record[2];
4976 unsigned InstCount = Record[3];
4977 unsigned NumRefs = Record[4];
4979 static int RefListStartIndex = 5;
4980 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
4981 assert(Record.
size() >= RefListStartIndex + NumRefs &&
4982 "Record size inconsistent with number of references");
4983 std::vector<ValueInfo> Refs = makeRefList(
4986 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
4988 IsOldProfileFormat, HasProfile);
4990 auto FS = llvm::make_unique<FunctionSummary>(
4991 Flags, InstCount, std::move(Refs), std::move(Edges),
4992 std::move(PendingTypeTests));
4993 PendingTypeTests.clear();
4994 LastSeenSummary =
FS.get();
4995 FS->setModulePath(ModuleIdMap[ModuleId]);
4996 TheIndex.addGlobalValueSummary(GUID, std::move(FS));
5004 unsigned ValueID = Record[0];
5005 uint64_t ModuleId = Record[1];
5006 uint64_t RawFlags = Record[2];
5007 unsigned AliaseeValueId = Record[3];
5009 auto AS = llvm::make_unique<AliasSummary>(
Flags, std::vector<ValueInfo>{});
5010 LastSeenSummary = AS.get();
5013 auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
5014 auto AliaseeInModule =
5015 TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
5016 if (!AliaseeInModule)
5017 return error(
"Alias expects aliasee summary to be parsed");
5018 AS->setAliasee(AliaseeInModule);
5021 TheIndex.addGlobalValueSummary(GUID, std::move(AS));
5027 unsigned ValueID = Record[0];
5028 uint64_t ModuleId = Record[1];
5029 uint64_t RawFlags = Record[2];
5031 std::vector<ValueInfo> Refs =
5033 auto FS = llvm::make_unique<GlobalVarSummary>(
Flags, std::move(Refs));
5034 LastSeenSummary =
FS.get();
5035 FS->setModulePath(ModuleIdMap[ModuleId]);
5037 TheIndex.addGlobalValueSummary(GUID, std::move(FS));
5043 uint64_t OriginalName = Record[0];
5044 if (!LastSeenSummary)
5045 return error(
"Name attachment that does not follow a combined record");
5046 LastSeenSummary->setOriginalName(OriginalName);
5048 LastSeenSummary =
nullptr;
5052 assert(PendingTypeTests.empty());
5053 PendingTypeTests.insert(PendingTypeTests.end(), Record.
begin(),
5064 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5066 return error(
"Invalid record");
5076 switch (Entry.
Kind) {
5077 case BitstreamEntry::SubBlock:
5079 return error(
"Malformed block");
5080 case BitstreamEntry::EndBlock:
5082 case BitstreamEntry::Record:
5093 uint64_t ModuleId = Record[0];
5095 if (convertToString(Record, 1, ModulePath))
5096 return error(
"Invalid record");
5098 LastSeenModulePath = TheIndex.addModulePath(ModulePath, ModuleId);
5099 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
5106 if (Record.
size() != 5)
5107 return error(
"Invalid hash length " +
Twine(Record.
size()).str());
5108 if (LastSeenModulePath == TheIndex.modulePaths().end())
5109 return error(
"Invalid hash that does not follow a module path");
5111 for (
auto &Val : Record) {
5112 assert(!(Val >> 32) &&
"Unexpected high bits set");
5113 LastSeenModulePath->second.second[Pos++] = Val;
5116 LastSeenModulePath = TheIndex.modulePaths().end();
5130 const char *
name()
const noexcept
override {
5131 return "llvm.bitcode";
5133 std::string message(
int IE)
const override {
5136 case BitcodeError::CorruptedBitcode:
5137 return "Corrupted bitcode";
5162 std::vector<BitcodeModule> Modules;
5173 switch (Entry.
Kind) {
5174 case BitstreamEntry::EndBlock:
5176 return error(
"Malformed block");
5178 case BitstreamEntry::SubBlock: {
5179 uint64_t IdentificationBit = -1ull;
5183 return error(
"Malformed block");
5186 if (Entry.
Kind != BitstreamEntry::SubBlock ||
5188 return error(
"Malformed block");
5194 return error(
"Malformed block");
5204 return error(
"Malformed block");
5207 case BitstreamEntry::Record:
5223 BitcodeModule::getModuleImpl(
LLVMContext &Context,
bool MaterializeAll,
5224 bool ShouldLazyLoadMetadata,
bool IsImporting) {
5227 std::string ProducerIdentification;
5228 if (IdentificationBit != -1ull) {
5231 readIdentificationBlock(Stream);
5232 if (!ProducerIdentificationOrErr)
5233 return ProducerIdentificationOrErr.
takeError();
5235 ProducerIdentification = *ProducerIdentificationOrErr;
5240 new BitcodeReader(std::move(Stream), ProducerIdentification, Context);
5242 std::unique_ptr<Module> M =
5243 llvm::make_unique<Module>(ModuleIdentifier,
Context);
5248 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5249 return std::move(Err);
5251 if (MaterializeAll) {
5253 if (
Error Err = M->materializeAll())
5254 return std::move(Err);
5257 if (
Error Err = R->materializeForwardReferencedFunctions())
5258 return std::move(Err);
5260 return std::move(M);
5266 return getModuleImpl(Context,
false, ShouldLazyLoadMetadata, IsImporting);
5274 auto Index = llvm::make_unique<ModuleSummaryIndex>();
5275 ModuleSummaryIndexBitcodeReader R(std::move(Stream), *Index);
5277 if (
Error Err = R.parseModule(ModuleIdentifier))
5278 return std::move(Err);
5280 return std::move(Index);
5289 return error(
"Invalid record");
5294 switch (Entry.
Kind) {
5296 return error(
"Malformed block");
5306 return error(
"Malformed block");
5321 if (MsOrErr->size() != 1)
5322 return error(
"Expected a single module");
5324 return (*MsOrErr)[0];
5329 bool ShouldLazyLoadMetadata,
bool IsImporting) {
5334 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
5338 std::unique_ptr<MemoryBuffer> &&Buffer,
LLVMContext &Context,
5339 bool ShouldLazyLoadMetadata,
bool IsImporting) {
5343 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5349 return getModuleImpl(Context,
true,
false,
false);
5360 return BM->parseModule(Context);
5368 return readTriple(*StreamOrErr);
5384 return readIdentificationCode(*StreamOrErr);
5393 return BM->getSummary();
5401 return BM->hasSummary();
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 (if unknown returns 0).
The highest possible calling convention ID. Must be some 2^k - 1.
void sortUseList(Compare Cmp)
Sort the use-list.
void push_back(const T &Elt)
static APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
LLVM Argument representation.
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.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
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 setMaterializer(GVMaterializer *GVM)
Sets the GVMaterializer to GVM.
This class represents a function call, abstracting a target machine's calling convention.
void setGC(std::string Str)
Expected< bool > hasSummary()
Check if the given bitcode buffer contains a summary block.
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...
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)
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
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 reserve(size_type N)
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)
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
bool isMaterializable() const
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.
struct fuzzer::@269 Flags
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...
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)
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.
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.
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
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.
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
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.
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().
Type * getScalarType() const LLVM_READONLY
If this is a vector type, return the element type, otherwise return 'this'.
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)
const std::error_category & BitcodeErrorCategory()
Class to represent pointers.
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information...
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)
isPowerOf2_32 - This function returns 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.
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()
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.
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
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)
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.
const GlobalObject * getBaseObject() const
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.
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
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...
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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Triple - Helper class for working with autoconf configuration names.
size_t getBufferSize() const
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
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...
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)
ValType
This is used to indicate local types.
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.
static SynchronizationScope getDecodedSynchScope(unsigned Val)
bool any() const
Whether any flag is set.
void setLinkage(LinkageTypes LT)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
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.
Class for arbitrary precision integers.
static int getDecodedCastOpcode(unsigned Val)
void push_back(pointer val)
StringRef str() const
Explicit conversion to StringRef.
LinkageTypes
An enumeration for the kinds of linkage for global values.
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 setIsMaterializable(bool V)
void setAttributes(AttributeSet Attrs)
Set the attribute list for this Function.
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
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.
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...
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...
enum llvm::BitstreamEntry::@32 Kind
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
static bool isValidElementType(Type *Ty)
Predicate for the element types that the SLP vectorizer supports.
iterator find(const KeyT &Val)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
AttributeSet getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
void setModulePath(StringRef ModPath)
Set the path to the module containing this function, for use in the combined index.
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
StringMapEntry< Value * > ValueName
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...
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.
Expected< bool > hasGlobalValueSummary(MemoryBufferRef Buffer)
Check if the given bitcode buffer contains a summary block.
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
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)
setCalledFunction - Set the callee to the specified value.
iterator_range< arg_iterator > args()
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
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)