1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Bitcode/BitcodeReader.h"
10 #include "MetadataLoader.h"
11 #include "ValueList.h"
12 #include "llvm/ADT/APFloat.h"
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Bitcode/BitstreamReader.h"
24 #include "llvm/Bitcode/LLVMBitCodes.h"
25 #include "llvm/Config/llvm-config.h"
26 #include "llvm/IR/Argument.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/AutoUpgrade.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Comdat.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DebugInfo.h"
37 #include "llvm/IR/DebugInfoMetadata.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GVMaterializer.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalIFunc.h"
44 #include "llvm/IR/GlobalIndirectSymbol.h"
45 #include "llvm/IR/GlobalObject.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/InlineAsm.h"
49 #include "llvm/IR/InstIterator.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instruction.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Module.h"
57 #include "llvm/IR/ModuleSummaryIndex.h"
58 #include "llvm/IR/Operator.h"
59 #include "llvm/IR/Type.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/IR/Verifier.h"
62 #include "llvm/Support/AtomicOrdering.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Compiler.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/Error.h"
68 #include "llvm/Support/ErrorHandling.h"
69 #include "llvm/Support/ErrorOr.h"
70 #include "llvm/Support/ManagedStatic.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/MemoryBuffer.h"
73 #include "llvm/Support/raw_ostream.h"
83 #include <system_error>
90 static cl::opt<bool> PrintSummaryGUIDs(
91 "print-summary-global-ids", cl::init(false), cl::Hidden,
93 "Print the global id for each value when reading the module summary"));
98 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
101 } // end anonymous namespace
103 static Error error(const Twine &Message) {
104 return make_error<StringError>(
105 Message, make_error_code(BitcodeError::CorruptedBitcode));
108 static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
109 if (!Stream.canSkipToPos(4))
110 return createStringError(std::errc::illegal_byte_sequence,
111 "file too small to contain bitcode header");
112 for (unsigned C : {'B', 'C'})
113 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
115 return createStringError(std::errc::illegal_byte_sequence,
116 "file doesn't start with bitcode header");
118 return Res.takeError();
119 for (unsigned C : {0x0, 0xC, 0xE, 0xD})
120 if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
122 return createStringError(std::errc::illegal_byte_sequence,
123 "file doesn't start with bitcode header");
125 return Res.takeError();
126 return Error::success();
129 static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
130 const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
131 const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
133 if (Buffer.getBufferSize() & 3)
134 return error("Invalid bitcode signature");
136 // If we have a wrapper header, parse it and ignore the non-bc file contents.
137 // The magic number is 0x0B17C0DE stored in little endian.
138 if (isBitcodeWrapper(BufPtr, BufEnd))
139 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
140 return error("Invalid bitcode wrapper header");
142 BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
143 if (Error Err = hasInvalidBitcodeHeader(Stream))
144 return std::move(Err);
146 return std::move(Stream);
149 /// Convert a string from a record into an std::string, return true on failure.
150 template <typename StrTy>
151 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
153 if (Idx > Record.size())
156 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
157 Result += (char)Record[i];
161 // Strip all the TBAA attachment for the module.
162 static void stripTBAA(Module *M) {
164 if (F.isMaterializable())
166 for (auto &I : instructions(F))
167 I.setMetadata(LLVMContext::MD_tbaa, nullptr);
171 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
172 /// "epoch" encoded in the bitcode, and return the producer name if any.
173 static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
174 if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
175 return std::move(Err);
177 // Read all the records.
178 SmallVector<uint64_t, 64> Record;
180 std::string ProducerIdentification;
183 BitstreamEntry Entry;
184 if (Expected<BitstreamEntry> Res = Stream.advance())
187 return Res.takeError();
189 switch (Entry.Kind) {
191 case BitstreamEntry::Error:
192 return error("Malformed block");
193 case BitstreamEntry::EndBlock:
194 return ProducerIdentification;
195 case BitstreamEntry::Record:
196 // The interesting case.
202 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
204 return MaybeBitCode.takeError();
205 switch (MaybeBitCode.get()) {
206 default: // Default behavior: reject
207 return error("Invalid value");
208 case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
209 convertToString(Record, 0, ProducerIdentification);
211 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
212 unsigned epoch = (unsigned)Record[0];
213 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
215 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
216 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
223 static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
224 // We expect a number of well-defined blocks, though we don't necessarily
225 // need to understand them all.
227 if (Stream.AtEndOfStream())
230 BitstreamEntry Entry;
231 if (Expected<BitstreamEntry> Res = Stream.advance())
232 Entry = std::move(Res.get());
234 return Res.takeError();
236 switch (Entry.Kind) {
237 case BitstreamEntry::EndBlock:
238 case BitstreamEntry::Error:
239 return error("Malformed block");
241 case BitstreamEntry::SubBlock:
242 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
243 return readIdentificationBlock(Stream);
245 // Ignore other sub-blocks.
246 if (Error Err = Stream.SkipBlock())
247 return std::move(Err);
249 case BitstreamEntry::Record:
250 if (Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
253 return Skipped.takeError();
258 static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
259 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
260 return std::move(Err);
262 SmallVector<uint64_t, 64> Record;
263 // Read all the records for this module.
266 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
268 return MaybeEntry.takeError();
269 BitstreamEntry Entry = MaybeEntry.get();
271 switch (Entry.Kind) {
272 case BitstreamEntry::SubBlock: // Handled for us already.
273 case BitstreamEntry::Error:
274 return error("Malformed block");
275 case BitstreamEntry::EndBlock:
277 case BitstreamEntry::Record:
278 // The interesting case.
283 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
285 return MaybeRecord.takeError();
286 switch (MaybeRecord.get()) {
288 break; // Default behavior, ignore unknown content.
289 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
291 if (convertToString(Record, 0, S))
292 return error("Invalid record");
293 // Check for the i386 and other (x86_64, ARM) conventions
294 if (S.find("__DATA,__objc_catlist") != std::string::npos ||
295 S.find("__OBJC,__category") != std::string::npos)
302 llvm_unreachable("Exit infinite loop");
305 static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
306 // We expect a number of well-defined blocks, though we don't necessarily
307 // need to understand them all.
309 BitstreamEntry Entry;
310 if (Expected<BitstreamEntry> Res = Stream.advance())
311 Entry = std::move(Res.get());
313 return Res.takeError();
315 switch (Entry.Kind) {
316 case BitstreamEntry::Error:
317 return error("Malformed block");
318 case BitstreamEntry::EndBlock:
321 case BitstreamEntry::SubBlock:
322 if (Entry.ID == bitc::MODULE_BLOCK_ID)
323 return hasObjCCategoryInModule(Stream);
325 // Ignore other sub-blocks.
326 if (Error Err = Stream.SkipBlock())
327 return std::move(Err);
330 case BitstreamEntry::Record:
331 if (Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
334 return Skipped.takeError();
339 static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
340 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
341 return std::move(Err);
343 SmallVector<uint64_t, 64> Record;
347 // Read all the records for this module.
349 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
351 return MaybeEntry.takeError();
352 BitstreamEntry Entry = MaybeEntry.get();
354 switch (Entry.Kind) {
355 case BitstreamEntry::SubBlock: // Handled for us already.
356 case BitstreamEntry::Error:
357 return error("Malformed block");
358 case BitstreamEntry::EndBlock:
360 case BitstreamEntry::Record:
361 // The interesting case.
366 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
368 return MaybeRecord.takeError();
369 switch (MaybeRecord.get()) {
370 default: break; // Default behavior, ignore unknown content.
371 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
373 if (convertToString(Record, 0, S))
374 return error("Invalid record");
381 llvm_unreachable("Exit infinite loop");
384 static Expected<std::string> readTriple(BitstreamCursor &Stream) {
385 // We expect a number of well-defined blocks, though we don't necessarily
386 // need to understand them all.
388 Expected<BitstreamEntry> MaybeEntry = Stream.advance();
390 return MaybeEntry.takeError();
391 BitstreamEntry Entry = MaybeEntry.get();
393 switch (Entry.Kind) {
394 case BitstreamEntry::Error:
395 return error("Malformed block");
396 case BitstreamEntry::EndBlock:
399 case BitstreamEntry::SubBlock:
400 if (Entry.ID == bitc::MODULE_BLOCK_ID)
401 return readModuleTriple(Stream);
403 // Ignore other sub-blocks.
404 if (Error Err = Stream.SkipBlock())
405 return std::move(Err);
408 case BitstreamEntry::Record:
409 if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
412 return Skipped.takeError();
419 class BitcodeReaderBase {
421 BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
422 : Stream(std::move(Stream)), Strtab(Strtab) {
423 this->Stream.setBlockInfo(&BlockInfo);
426 BitstreamBlockInfo BlockInfo;
427 BitstreamCursor Stream;
430 /// In version 2 of the bitcode we store names of global values and comdats in
431 /// a string table rather than in the VST.
432 bool UseStrtab = false;
434 Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
436 /// If this module uses a string table, pop the reference to the string table
437 /// and return the referenced string and the rest of the record. Otherwise
438 /// just return the record itself.
439 std::pair<StringRef, ArrayRef<uint64_t>>
440 readNameFromStrtab(ArrayRef<uint64_t> Record);
442 bool readBlockInfo();
444 // Contains an arbitrary and optional string identifying the bitcode producer
445 std::string ProducerIdentification;
447 Error error(const Twine &Message);
450 } // end anonymous namespace
452 Error BitcodeReaderBase::error(const Twine &Message) {
453 std::string FullMsg = Message.str();
454 if (!ProducerIdentification.empty())
455 FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
456 LLVM_VERSION_STRING "')";
457 return ::error(FullMsg);
461 BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
463 return error("Invalid record");
464 unsigned ModuleVersion = Record[0];
465 if (ModuleVersion > 2)
466 return error("Invalid value");
467 UseStrtab = ModuleVersion >= 2;
468 return ModuleVersion;
471 std::pair<StringRef, ArrayRef<uint64_t>>
472 BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
475 // Invalid reference. Let the caller complain about the record being empty.
476 if (Record[0] + Record[1] > Strtab.size())
478 return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
483 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
484 LLVMContext &Context;
485 Module *TheModule = nullptr;
486 // Next offset to start scanning for lazy parsing of function bodies.
487 uint64_t NextUnreadBit = 0;
488 // Last function offset found in the VST.
489 uint64_t LastFunctionBlockBit = 0;
490 bool SeenValueSymbolTable = false;
491 uint64_t VSTOffset = 0;
493 std::vector<std::string> SectionTable;
494 std::vector<std::string> GCTable;
496 std::vector<Type*> TypeList;
497 DenseMap<Function *, FunctionType *> FunctionTypes;
498 BitcodeReaderValueList ValueList;
499 Optional<MetadataLoader> MDLoader;
500 std::vector<Comdat *> ComdatList;
501 SmallVector<Instruction *, 64> InstructionList;
503 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
504 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
505 std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
506 std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
507 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
509 /// The set of attributes by index. Index zero in the file is for null, and
510 /// is thus not represented here. As such all indices are off by one.
511 std::vector<AttributeList> MAttributes;
513 /// The set of attribute groups.
514 std::map<unsigned, AttributeList> MAttributeGroups;
516 /// While parsing a function body, this is a list of the basic blocks for the
518 std::vector<BasicBlock*> FunctionBBs;
520 // When reading the module header, this list is populated with functions that
521 // have bodies later in the file.
522 std::vector<Function*> FunctionsWithBodies;
524 // When intrinsic functions are encountered which require upgrading they are
525 // stored here with their replacement function.
526 using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
527 UpdatedIntrinsicMap UpgradedIntrinsics;
528 // Intrinsics which were remangled because of types rename
529 UpdatedIntrinsicMap RemangledIntrinsics;
531 // Several operations happen after the module header has been read, but
532 // before function bodies are processed. This keeps track of whether
533 // we've done this yet.
534 bool SeenFirstFunctionBody = false;
536 /// When function bodies are initially scanned, this map contains info about
537 /// where to find deferred function body in the stream.
538 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
540 /// When Metadata block is initially scanned when parsing the module, we may
541 /// choose to defer parsing of the metadata. This vector contains info about
542 /// which Metadata blocks are deferred.
543 std::vector<uint64_t> DeferredMetadataInfo;
545 /// These are basic blocks forward-referenced by block addresses. They are
546 /// inserted lazily into functions when they're loaded. The basic block ID is
547 /// its index into the vector.
548 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
549 std::deque<Function *> BasicBlockFwdRefQueue;
551 /// Indicates that we are using a new encoding for instruction operands where
552 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
553 /// instruction number, for a more compact encoding. Some instruction
554 /// operands are not relative to the instruction ID: basic block numbers, and
555 /// types. Once the old style function blocks have been phased out, we would
556 /// not need this flag.
557 bool UseRelativeIDs = false;
559 /// True if all functions will be materialized, negating the need to process
560 /// (e.g.) blockaddress forward references.
561 bool WillMaterializeAllForwardRefs = false;
563 bool StripDebugInfo = false;
564 TBAAVerifier TBAAVerifyHelper;
566 std::vector<std::string> BundleTags;
567 SmallVector<SyncScope::ID, 8> SSIDs;
570 BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
571 StringRef ProducerIdentification, LLVMContext &Context);
573 Error materializeForwardReferencedFunctions();
575 Error materialize(GlobalValue *GV) override;
576 Error materializeModule() override;
577 std::vector<StructType *> getIdentifiedStructTypes() const override;
579 /// Main interface to parsing a bitcode buffer.
580 /// \returns true if an error occurred.
581 Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
582 bool IsImporting = false);
584 static uint64_t decodeSignRotatedValue(uint64_t V);
586 /// Materialize any deferred Metadata block.
587 Error materializeMetadata() override;
589 void setStripDebugInfo() override;
592 std::vector<StructType *> IdentifiedStructTypes;
593 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
594 StructType *createIdentifiedStructType(LLVMContext &Context);
596 /// Map all pointer types within \param Ty to the opaque pointer
597 /// type in the same address space if opaque pointers are being
598 /// used, otherwise nop. This converts a bitcode-reader internal
599 /// type into one suitable for use in a Value.
600 Type *flattenPointerTypes(Type *Ty) {
604 /// Given a fully structured pointer type (i.e. not opaque), return
605 /// the flattened form of its element, suitable for use in a Value.
606 Type *getPointerElementFlatType(Type *Ty) {
607 return flattenPointerTypes(cast<PointerType>(Ty)->getElementType());
610 /// Given a fully structured pointer type, get its element type in
611 /// both fully structured form, and flattened form suitable for use
613 std::pair<Type *, Type *> getPointerElementTypes(Type *FullTy) {
614 Type *ElTy = cast<PointerType>(FullTy)->getElementType();
615 return std::make_pair(ElTy, flattenPointerTypes(ElTy));
618 /// Return the flattened type (suitable for use in a Value)
619 /// specified by the given \param ID.
620 Type *getTypeByID(unsigned ID) {
621 return flattenPointerTypes(getFullyStructuredTypeByID(ID));
624 /// Return the fully structured (bitcode-reader internal) type
625 /// corresponding to the given \param ID.
626 Type *getFullyStructuredTypeByID(unsigned ID);
628 Value *getFnValueByID(unsigned ID, Type *Ty, Type **FullTy = nullptr) {
629 if (Ty && Ty->isMetadataTy())
630 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
631 return ValueList.getValueFwdRef(ID, Ty, FullTy);
634 Metadata *getFnMetadataByID(unsigned ID) {
635 return MDLoader->getMetadataFwdRefOrLoad(ID);
638 BasicBlock *getBasicBlock(unsigned ID) const {
639 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
640 return FunctionBBs[ID];
643 AttributeList getAttributes(unsigned i) const {
644 if (i-1 < MAttributes.size())
645 return MAttributes[i-1];
646 return AttributeList();
649 /// Read a value/type pair out of the specified record from slot 'Slot'.
650 /// Increment Slot past the number of slots used in the record. Return true on
652 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
653 unsigned InstNum, Value *&ResVal,
654 Type **FullTy = nullptr) {
655 if (Slot == Record.size()) return true;
656 unsigned ValNo = (unsigned)Record[Slot++];
657 // Adjust the ValNo, if it was encoded relative to the InstNum.
659 ValNo = InstNum - ValNo;
660 if (ValNo < InstNum) {
661 // If this is not a forward reference, just return the value we already
663 ResVal = getFnValueByID(ValNo, nullptr, FullTy);
664 return ResVal == nullptr;
666 if (Slot == Record.size())
669 unsigned TypeNo = (unsigned)Record[Slot++];
670 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
672 *FullTy = getFullyStructuredTypeByID(TypeNo);
673 return ResVal == nullptr;
676 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
677 /// past the number of slots used by the value in the record. Return true if
678 /// there is an error.
679 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
680 unsigned InstNum, Type *Ty, Value *&ResVal) {
681 if (getValue(Record, Slot, InstNum, Ty, ResVal))
683 // All values currently take a single record slot.
688 /// Like popValue, but does not increment the Slot number.
689 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
690 unsigned InstNum, Type *Ty, Value *&ResVal) {
691 ResVal = getValue(Record, Slot, InstNum, Ty);
692 return ResVal == nullptr;
695 /// Version of getValue that returns ResVal directly, or 0 if there is an
697 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
698 unsigned InstNum, Type *Ty) {
699 if (Slot == Record.size()) return nullptr;
700 unsigned ValNo = (unsigned)Record[Slot];
701 // Adjust the ValNo, if it was encoded relative to the InstNum.
703 ValNo = InstNum - ValNo;
704 return getFnValueByID(ValNo, Ty);
707 /// Like getValue, but decodes signed VBRs.
708 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
709 unsigned InstNum, Type *Ty) {
710 if (Slot == Record.size()) return nullptr;
711 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
712 // Adjust the ValNo, if it was encoded relative to the InstNum.
714 ValNo = InstNum - ValNo;
715 return getFnValueByID(ValNo, Ty);
718 /// Upgrades old-style typeless byval attributes by adding the corresponding
719 /// argument's pointee type.
720 void propagateByValTypes(CallBase *CB, ArrayRef<Type *> ArgsFullTys);
722 /// Converts alignment exponent (i.e. power of two (or zero)) to the
723 /// corresponding alignment to use. If alignment is too large, returns
724 /// a corresponding error code.
725 Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
726 Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
727 Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
729 Error parseComdatRecord(ArrayRef<uint64_t> Record);
730 Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
731 Error parseFunctionRecord(ArrayRef<uint64_t> Record);
732 Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
733 ArrayRef<uint64_t> Record);
735 Error parseAttributeBlock();
736 Error parseAttributeGroupBlock();
737 Error parseTypeTable();
738 Error parseTypeTableBody();
739 Error parseOperandBundleTags();
740 Error parseSyncScopeNames();
742 Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
743 unsigned NameIndex, Triple &TT);
744 void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
745 ArrayRef<uint64_t> Record);
746 Error parseValueSymbolTable(uint64_t Offset = 0);
747 Error parseGlobalValueSymbolTable();
748 Error parseConstants();
749 Error rememberAndSkipFunctionBodies();
750 Error rememberAndSkipFunctionBody();
751 /// Save the positions of the Metadata blocks and skip parsing the blocks.
752 Error rememberAndSkipMetadata();
753 Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
754 Error parseFunctionBody(Function *F);
755 Error globalCleanup();
756 Error resolveGlobalAndIndirectSymbolInits();
757 Error parseUseLists();
758 Error findFunctionInStream(
760 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
762 SyncScope::ID getDecodedSyncScopeID(unsigned Val);
765 /// Class to manage reading and parsing function summary index bitcode
767 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
768 /// The module index built during parsing.
769 ModuleSummaryIndex &TheIndex;
771 /// Indicates whether we have encountered a global value summary section
772 /// yet during parsing.
773 bool SeenGlobalValSummary = false;
775 /// Indicates whether we have already parsed the VST, used for error checking.
776 bool SeenValueSymbolTable = false;
778 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
779 /// Used to enable on-demand parsing of the VST.
780 uint64_t VSTOffset = 0;
782 // Map to save ValueId to ValueInfo association that was recorded in the
783 // ValueSymbolTable. It is used after the VST is parsed to convert
784 // call graph edges read from the function summary from referencing
785 // callees by their ValueId to using the ValueInfo instead, which is how
786 // they are recorded in the summary index being built.
787 // We save a GUID which refers to the same global as the ValueInfo, but
788 // ignoring the linkage, i.e. for values other than local linkage they are
790 DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
791 ValueIdToValueInfoMap;
793 /// Map populated during module path string table parsing, from the
794 /// module ID to a string reference owned by the index's module
795 /// path string table, used to correlate with combined index
797 DenseMap<uint64_t, StringRef> ModuleIdMap;
799 /// Original source file name recorded in a bitcode record.
800 std::string SourceFileName;
802 /// The string identifier given to this module by the client, normally the
803 /// path to the bitcode file.
804 StringRef ModulePath;
806 /// For per-module summary indexes, the unique numerical identifier given to
807 /// this module by the client.
811 ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
812 ModuleSummaryIndex &TheIndex,
813 StringRef ModulePath, unsigned ModuleId);
818 void setValueGUID(uint64_t ValueID, StringRef ValueName,
819 GlobalValue::LinkageTypes Linkage,
820 StringRef SourceFileName);
821 Error parseValueSymbolTable(
823 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
824 std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
825 std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
826 bool IsOldProfileFormat,
829 Error parseEntireSummary(unsigned ID);
830 Error parseModuleStringTable();
831 void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
832 void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
833 TypeIdCompatibleVtableInfo &TypeId);
835 std::pair<ValueInfo, GlobalValue::GUID>
836 getValueInfoFromValueId(unsigned ValueId);
838 void addThisModule();
839 ModuleSummaryIndex::ModuleInfo *getThisModule();
842 } // end anonymous namespace
844 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
848 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
849 EC = EIB.convertToErrorCode();
850 Ctx.emitError(EIB.message());
854 return std::error_code();
857 BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
858 StringRef ProducerIdentification,
859 LLVMContext &Context)
860 : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
862 this->ProducerIdentification = ProducerIdentification;
865 Error BitcodeReader::materializeForwardReferencedFunctions() {
866 if (WillMaterializeAllForwardRefs)
867 return Error::success();
869 // Prevent recursion.
870 WillMaterializeAllForwardRefs = true;
872 while (!BasicBlockFwdRefQueue.empty()) {
873 Function *F = BasicBlockFwdRefQueue.front();
874 BasicBlockFwdRefQueue.pop_front();
875 assert(F && "Expected valid function");
876 if (!BasicBlockFwdRefs.count(F))
877 // Already materialized.
880 // Check for a function that isn't materializable to prevent an infinite
881 // loop. When parsing a blockaddress stored in a global variable, there
882 // isn't a trivial way to check if a function will have a body without a
883 // linear search through FunctionsWithBodies, so just check it here.
884 if (!F->isMaterializable())
885 return error("Never resolved function from blockaddress");
887 // Try to materialize F.
888 if (Error Err = materialize(F))
891 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
894 WillMaterializeAllForwardRefs = false;
895 return Error::success();
898 //===----------------------------------------------------------------------===//
899 // Helper functions to implement forward reference resolution, etc.
900 //===----------------------------------------------------------------------===//
902 static bool hasImplicitComdat(size_t Val) {
906 case 1: // Old WeakAnyLinkage
907 case 4: // Old LinkOnceAnyLinkage
908 case 10: // Old WeakODRLinkage
909 case 11: // Old LinkOnceODRLinkage
914 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
916 default: // Map unknown/new linkages to external
918 return GlobalValue::ExternalLinkage;
920 return GlobalValue::AppendingLinkage;
922 return GlobalValue::InternalLinkage;
924 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
926 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
928 return GlobalValue::ExternalWeakLinkage;
930 return GlobalValue::CommonLinkage;
932 return GlobalValue::PrivateLinkage;
934 return GlobalValue::AvailableExternallyLinkage;
936 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
938 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
940 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
941 case 1: // Old value with implicit comdat.
943 return GlobalValue::WeakAnyLinkage;
944 case 10: // Old value with implicit comdat.
946 return GlobalValue::WeakODRLinkage;
947 case 4: // Old value with implicit comdat.
949 return GlobalValue::LinkOnceAnyLinkage;
950 case 11: // Old value with implicit comdat.
952 return GlobalValue::LinkOnceODRLinkage;
956 static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
957 FunctionSummary::FFlags Flags;
958 Flags.ReadNone = RawFlags & 0x1;
959 Flags.ReadOnly = (RawFlags >> 1) & 0x1;
960 Flags.NoRecurse = (RawFlags >> 2) & 0x1;
961 Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
962 Flags.NoInline = (RawFlags >> 4) & 0x1;
966 /// Decode the flags for GlobalValue in the summary.
967 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
969 // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
970 // like getDecodedLinkage() above. Any future change to the linkage enum and
971 // to getDecodedLinkage() will need to be taken into account here as above.
972 auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
973 RawFlags = RawFlags >> 4;
974 bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
975 // The Live flag wasn't introduced until version 3. For dead stripping
976 // to work correctly on earlier versions, we must conservatively treat all
978 bool Live = (RawFlags & 0x2) || Version < 3;
979 bool Local = (RawFlags & 0x4);
980 bool AutoHide = (RawFlags & 0x8);
982 return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local, AutoHide);
985 // Decode the flags for GlobalVariable in the summary
986 static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
987 return GlobalVarSummary::GVarFlags((RawFlags & 0x1) ? true : false);
990 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
992 default: // Map unknown visibilities to default.
993 case 0: return GlobalValue::DefaultVisibility;
994 case 1: return GlobalValue::HiddenVisibility;
995 case 2: return GlobalValue::ProtectedVisibility;
999 static GlobalValue::DLLStorageClassTypes
1000 getDecodedDLLStorageClass(unsigned Val) {
1002 default: // Map unknown values to default.
1003 case 0: return GlobalValue::DefaultStorageClass;
1004 case 1: return GlobalValue::DLLImportStorageClass;
1005 case 2: return GlobalValue::DLLExportStorageClass;
1009 static bool getDecodedDSOLocal(unsigned Val) {
1011 default: // Map unknown values to preemptable.
1012 case 0: return false;
1013 case 1: return true;
1017 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
1019 case 0: return GlobalVariable::NotThreadLocal;
1020 default: // Map unknown non-zero value to general dynamic.
1021 case 1: return GlobalVariable::GeneralDynamicTLSModel;
1022 case 2: return GlobalVariable::LocalDynamicTLSModel;
1023 case 3: return GlobalVariable::InitialExecTLSModel;
1024 case 4: return GlobalVariable::LocalExecTLSModel;
1028 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
1030 default: // Map unknown to UnnamedAddr::None.
1031 case 0: return GlobalVariable::UnnamedAddr::None;
1032 case 1: return GlobalVariable::UnnamedAddr::Global;
1033 case 2: return GlobalVariable::UnnamedAddr::Local;
1037 static int getDecodedCastOpcode(unsigned Val) {
1040 case bitc::CAST_TRUNC : return Instruction::Trunc;
1041 case bitc::CAST_ZEXT : return Instruction::ZExt;
1042 case bitc::CAST_SEXT : return Instruction::SExt;
1043 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
1044 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
1045 case bitc::CAST_UITOFP : return Instruction::UIToFP;
1046 case bitc::CAST_SITOFP : return Instruction::SIToFP;
1047 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
1048 case bitc::CAST_FPEXT : return Instruction::FPExt;
1049 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
1050 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
1051 case bitc::CAST_BITCAST : return Instruction::BitCast;
1052 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
1056 static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
1057 bool IsFP = Ty->isFPOrFPVectorTy();
1058 // UnOps are only valid for int/fp or vector of int/fp types
1059 if (!IsFP && !Ty->isIntOrIntVectorTy())
1065 case bitc::UNOP_NEG:
1066 return IsFP ? Instruction::FNeg : -1;
1070 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
1071 bool IsFP = Ty->isFPOrFPVectorTy();
1072 // BinOps are only valid for int/fp or vector of int/fp types
1073 if (!IsFP && !Ty->isIntOrIntVectorTy())
1079 case bitc::BINOP_ADD:
1080 return IsFP ? Instruction::FAdd : Instruction::Add;
1081 case bitc::BINOP_SUB:
1082 return IsFP ? Instruction::FSub : Instruction::Sub;
1083 case bitc::BINOP_MUL:
1084 return IsFP ? Instruction::FMul : Instruction::Mul;
1085 case bitc::BINOP_UDIV:
1086 return IsFP ? -1 : Instruction::UDiv;
1087 case bitc::BINOP_SDIV:
1088 return IsFP ? Instruction::FDiv : Instruction::SDiv;
1089 case bitc::BINOP_UREM:
1090 return IsFP ? -1 : Instruction::URem;
1091 case bitc::BINOP_SREM:
1092 return IsFP ? Instruction::FRem : Instruction::SRem;
1093 case bitc::BINOP_SHL:
1094 return IsFP ? -1 : Instruction::Shl;
1095 case bitc::BINOP_LSHR:
1096 return IsFP ? -1 : Instruction::LShr;
1097 case bitc::BINOP_ASHR:
1098 return IsFP ? -1 : Instruction::AShr;
1099 case bitc::BINOP_AND:
1100 return IsFP ? -1 : Instruction::And;
1101 case bitc::BINOP_OR:
1102 return IsFP ? -1 : Instruction::Or;
1103 case bitc::BINOP_XOR:
1104 return IsFP ? -1 : Instruction::Xor;
1108 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
1110 default: return AtomicRMWInst::BAD_BINOP;
1111 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1112 case bitc::RMW_ADD: return AtomicRMWInst::Add;
1113 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1114 case bitc::RMW_AND: return AtomicRMWInst::And;
1115 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1116 case bitc::RMW_OR: return AtomicRMWInst::Or;
1117 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1118 case bitc::RMW_MAX: return AtomicRMWInst::Max;
1119 case bitc::RMW_MIN: return AtomicRMWInst::Min;
1120 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1121 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1122 case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1123 case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1127 static AtomicOrdering getDecodedOrdering(unsigned Val) {
1129 case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1130 case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1131 case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1132 case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1133 case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1134 case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1135 default: // Map unknown orderings to sequentially-consistent.
1136 case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1140 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1142 default: // Map unknown selection kinds to any.
1143 case bitc::COMDAT_SELECTION_KIND_ANY:
1145 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1146 return Comdat::ExactMatch;
1147 case bitc::COMDAT_SELECTION_KIND_LARGEST:
1148 return Comdat::Largest;
1149 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1150 return Comdat::NoDuplicates;
1151 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1152 return Comdat::SameSize;
1156 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1158 if (0 != (Val & bitc::UnsafeAlgebra))
1160 if (0 != (Val & bitc::AllowReassoc))
1161 FMF.setAllowReassoc();
1162 if (0 != (Val & bitc::NoNaNs))
1164 if (0 != (Val & bitc::NoInfs))
1166 if (0 != (Val & bitc::NoSignedZeros))
1167 FMF.setNoSignedZeros();
1168 if (0 != (Val & bitc::AllowReciprocal))
1169 FMF.setAllowReciprocal();
1170 if (0 != (Val & bitc::AllowContract))
1171 FMF.setAllowContract(true);
1172 if (0 != (Val & bitc::ApproxFunc))
1173 FMF.setApproxFunc();
1177 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1179 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1180 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1184 Type *BitcodeReader::getFullyStructuredTypeByID(unsigned ID) {
1185 // The type table size is always specified correctly.
1186 if (ID >= TypeList.size())
1189 if (Type *Ty = TypeList[ID])
1192 // If we have a forward reference, the only possible case is when it is to a
1193 // named struct. Just create a placeholder for now.
1194 return TypeList[ID] = createIdentifiedStructType(Context);
1197 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1199 auto *Ret = StructType::create(Context, Name);
1200 IdentifiedStructTypes.push_back(Ret);
1204 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1205 auto *Ret = StructType::create(Context);
1206 IdentifiedStructTypes.push_back(Ret);
1210 //===----------------------------------------------------------------------===//
1211 // Functions for parsing blocks from the bitcode file
1212 //===----------------------------------------------------------------------===//
1214 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1216 case Attribute::EndAttrKinds:
1217 llvm_unreachable("Synthetic enumerators which should never get here");
1219 case Attribute::None: return 0;
1220 case Attribute::ZExt: return 1 << 0;
1221 case Attribute::SExt: return 1 << 1;
1222 case Attribute::NoReturn: return 1 << 2;
1223 case Attribute::InReg: return 1 << 3;
1224 case Attribute::StructRet: return 1 << 4;
1225 case Attribute::NoUnwind: return 1 << 5;
1226 case Attribute::NoAlias: return 1 << 6;
1227 case Attribute::ByVal: return 1 << 7;
1228 case Attribute::Nest: return 1 << 8;
1229 case Attribute::ReadNone: return 1 << 9;
1230 case Attribute::ReadOnly: return 1 << 10;
1231 case Attribute::NoInline: return 1 << 11;
1232 case Attribute::AlwaysInline: return 1 << 12;
1233 case Attribute::OptimizeForSize: return 1 << 13;
1234 case Attribute::StackProtect: return 1 << 14;
1235 case Attribute::StackProtectReq: return 1 << 15;
1236 case Attribute::Alignment: return 31 << 16;
1237 case Attribute::NoCapture: return 1 << 21;
1238 case Attribute::NoRedZone: return 1 << 22;
1239 case Attribute::NoImplicitFloat: return 1 << 23;
1240 case Attribute::Naked: return 1 << 24;
1241 case Attribute::InlineHint: return 1 << 25;
1242 case Attribute::StackAlignment: return 7 << 26;
1243 case Attribute::ReturnsTwice: return 1 << 29;
1244 case Attribute::UWTable: return 1 << 30;
1245 case Attribute::NonLazyBind: return 1U << 31;
1246 case Attribute::SanitizeAddress: return 1ULL << 32;
1247 case Attribute::MinSize: return 1ULL << 33;
1248 case Attribute::NoDuplicate: return 1ULL << 34;
1249 case Attribute::StackProtectStrong: return 1ULL << 35;
1250 case Attribute::SanitizeThread: return 1ULL << 36;
1251 case Attribute::SanitizeMemory: return 1ULL << 37;
1252 case Attribute::NoBuiltin: return 1ULL << 38;
1253 case Attribute::Returned: return 1ULL << 39;
1254 case Attribute::Cold: return 1ULL << 40;
1255 case Attribute::Builtin: return 1ULL << 41;
1256 case Attribute::OptimizeNone: return 1ULL << 42;
1257 case Attribute::InAlloca: return 1ULL << 43;
1258 case Attribute::NonNull: return 1ULL << 44;
1259 case Attribute::JumpTable: return 1ULL << 45;
1260 case Attribute::Convergent: return 1ULL << 46;
1261 case Attribute::SafeStack: return 1ULL << 47;
1262 case Attribute::NoRecurse: return 1ULL << 48;
1263 case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1264 case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1265 case Attribute::SwiftSelf: return 1ULL << 51;
1266 case Attribute::SwiftError: return 1ULL << 52;
1267 case Attribute::WriteOnly: return 1ULL << 53;
1268 case Attribute::Speculatable: return 1ULL << 54;
1269 case Attribute::StrictFP: return 1ULL << 55;
1270 case Attribute::SanitizeHWAddress: return 1ULL << 56;
1271 case Attribute::NoCfCheck: return 1ULL << 57;
1272 case Attribute::OptForFuzzing: return 1ULL << 58;
1273 case Attribute::ShadowCallStack: return 1ULL << 59;
1274 case Attribute::SpeculativeLoadHardening:
1276 case Attribute::ImmArg:
1278 case Attribute::WillReturn:
1280 case Attribute::Dereferenceable:
1281 llvm_unreachable("dereferenceable attribute not supported in raw format");
1283 case Attribute::DereferenceableOrNull:
1284 llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1287 case Attribute::ArgMemOnly:
1288 llvm_unreachable("argmemonly attribute not supported in raw format");
1290 case Attribute::AllocSize:
1291 llvm_unreachable("allocsize not supported in raw format");
1294 llvm_unreachable("Unsupported attribute type");
1297 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1300 for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1301 I = Attribute::AttrKind(I + 1)) {
1302 if (I == Attribute::Dereferenceable ||
1303 I == Attribute::DereferenceableOrNull ||
1304 I == Attribute::ArgMemOnly ||
1305 I == Attribute::AllocSize)
1307 if (uint64_t A = (Val & getRawAttributeMask(I))) {
1308 if (I == Attribute::Alignment)
1309 B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1310 else if (I == Attribute::StackAlignment)
1311 B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1318 /// This fills an AttrBuilder object with the LLVM attributes that have
1319 /// been decoded from the given integer. This function must stay in sync with
1320 /// 'encodeLLVMAttributesForBitcode'.
1321 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1322 uint64_t EncodedAttrs) {
1323 // FIXME: Remove in 4.0.
1325 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1326 // the bits above 31 down by 11 bits.
1327 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1328 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1329 "Alignment must be a power of two.");
1332 B.addAlignmentAttr(Alignment);
1333 addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1334 (EncodedAttrs & 0xffff));
1337 Error BitcodeReader::parseAttributeBlock() {
1338 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1341 if (!MAttributes.empty())
1342 return error("Invalid multiple blocks");
1344 SmallVector<uint64_t, 64> Record;
1346 SmallVector<AttributeList, 8> Attrs;
1348 // Read all the records.
1350 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1352 return MaybeEntry.takeError();
1353 BitstreamEntry Entry = MaybeEntry.get();
1355 switch (Entry.Kind) {
1356 case BitstreamEntry::SubBlock: // Handled for us already.
1357 case BitstreamEntry::Error:
1358 return error("Malformed block");
1359 case BitstreamEntry::EndBlock:
1360 return Error::success();
1361 case BitstreamEntry::Record:
1362 // The interesting case.
1368 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1370 return MaybeRecord.takeError();
1371 switch (MaybeRecord.get()) {
1372 default: // Default behavior: ignore.
1374 case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1375 // FIXME: Remove in 4.0.
1376 if (Record.size() & 1)
1377 return error("Invalid record");
1379 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1381 decodeLLVMAttributesForBitcode(B, Record[i+1]);
1382 Attrs.push_back(AttributeList::get(Context, Record[i], B));
1385 MAttributes.push_back(AttributeList::get(Context, Attrs));
1388 case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1389 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1390 Attrs.push_back(MAttributeGroups[Record[i]]);
1392 MAttributes.push_back(AttributeList::get(Context, Attrs));
1399 // Returns Attribute::None on unrecognized codes.
1400 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1403 return Attribute::None;
1404 case bitc::ATTR_KIND_ALIGNMENT:
1405 return Attribute::Alignment;
1406 case bitc::ATTR_KIND_ALWAYS_INLINE:
1407 return Attribute::AlwaysInline;
1408 case bitc::ATTR_KIND_ARGMEMONLY:
1409 return Attribute::ArgMemOnly;
1410 case bitc::ATTR_KIND_BUILTIN:
1411 return Attribute::Builtin;
1412 case bitc::ATTR_KIND_BY_VAL:
1413 return Attribute::ByVal;
1414 case bitc::ATTR_KIND_IN_ALLOCA:
1415 return Attribute::InAlloca;
1416 case bitc::ATTR_KIND_COLD:
1417 return Attribute::Cold;
1418 case bitc::ATTR_KIND_CONVERGENT:
1419 return Attribute::Convergent;
1420 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1421 return Attribute::InaccessibleMemOnly;
1422 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1423 return Attribute::InaccessibleMemOrArgMemOnly;
1424 case bitc::ATTR_KIND_INLINE_HINT:
1425 return Attribute::InlineHint;
1426 case bitc::ATTR_KIND_IN_REG:
1427 return Attribute::InReg;
1428 case bitc::ATTR_KIND_JUMP_TABLE:
1429 return Attribute::JumpTable;
1430 case bitc::ATTR_KIND_MIN_SIZE:
1431 return Attribute::MinSize;
1432 case bitc::ATTR_KIND_NAKED:
1433 return Attribute::Naked;
1434 case bitc::ATTR_KIND_NEST:
1435 return Attribute::Nest;
1436 case bitc::ATTR_KIND_NO_ALIAS:
1437 return Attribute::NoAlias;
1438 case bitc::ATTR_KIND_NO_BUILTIN:
1439 return Attribute::NoBuiltin;
1440 case bitc::ATTR_KIND_NO_CAPTURE:
1441 return Attribute::NoCapture;
1442 case bitc::ATTR_KIND_NO_DUPLICATE:
1443 return Attribute::NoDuplicate;
1444 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1445 return Attribute::NoImplicitFloat;
1446 case bitc::ATTR_KIND_NO_INLINE:
1447 return Attribute::NoInline;
1448 case bitc::ATTR_KIND_NO_RECURSE:
1449 return Attribute::NoRecurse;
1450 case bitc::ATTR_KIND_NON_LAZY_BIND:
1451 return Attribute::NonLazyBind;
1452 case bitc::ATTR_KIND_NON_NULL:
1453 return Attribute::NonNull;
1454 case bitc::ATTR_KIND_DEREFERENCEABLE:
1455 return Attribute::Dereferenceable;
1456 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1457 return Attribute::DereferenceableOrNull;
1458 case bitc::ATTR_KIND_ALLOC_SIZE:
1459 return Attribute::AllocSize;
1460 case bitc::ATTR_KIND_NO_RED_ZONE:
1461 return Attribute::NoRedZone;
1462 case bitc::ATTR_KIND_NO_RETURN:
1463 return Attribute::NoReturn;
1464 case bitc::ATTR_KIND_NOCF_CHECK:
1465 return Attribute::NoCfCheck;
1466 case bitc::ATTR_KIND_NO_UNWIND:
1467 return Attribute::NoUnwind;
1468 case bitc::ATTR_KIND_OPT_FOR_FUZZING:
1469 return Attribute::OptForFuzzing;
1470 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1471 return Attribute::OptimizeForSize;
1472 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1473 return Attribute::OptimizeNone;
1474 case bitc::ATTR_KIND_READ_NONE:
1475 return Attribute::ReadNone;
1476 case bitc::ATTR_KIND_READ_ONLY:
1477 return Attribute::ReadOnly;
1478 case bitc::ATTR_KIND_RETURNED:
1479 return Attribute::Returned;
1480 case bitc::ATTR_KIND_RETURNS_TWICE:
1481 return Attribute::ReturnsTwice;
1482 case bitc::ATTR_KIND_S_EXT:
1483 return Attribute::SExt;
1484 case bitc::ATTR_KIND_SPECULATABLE:
1485 return Attribute::Speculatable;
1486 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1487 return Attribute::StackAlignment;
1488 case bitc::ATTR_KIND_STACK_PROTECT:
1489 return Attribute::StackProtect;
1490 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1491 return Attribute::StackProtectReq;
1492 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1493 return Attribute::StackProtectStrong;
1494 case bitc::ATTR_KIND_SAFESTACK:
1495 return Attribute::SafeStack;
1496 case bitc::ATTR_KIND_SHADOWCALLSTACK:
1497 return Attribute::ShadowCallStack;
1498 case bitc::ATTR_KIND_STRICT_FP:
1499 return Attribute::StrictFP;
1500 case bitc::ATTR_KIND_STRUCT_RET:
1501 return Attribute::StructRet;
1502 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1503 return Attribute::SanitizeAddress;
1504 case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
1505 return Attribute::SanitizeHWAddress;
1506 case bitc::ATTR_KIND_SANITIZE_THREAD:
1507 return Attribute::SanitizeThread;
1508 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1509 return Attribute::SanitizeMemory;
1510 case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
1511 return Attribute::SpeculativeLoadHardening;
1512 case bitc::ATTR_KIND_SWIFT_ERROR:
1513 return Attribute::SwiftError;
1514 case bitc::ATTR_KIND_SWIFT_SELF:
1515 return Attribute::SwiftSelf;
1516 case bitc::ATTR_KIND_UW_TABLE:
1517 return Attribute::UWTable;
1518 case bitc::ATTR_KIND_WILLRETURN:
1519 return Attribute::WillReturn;
1520 case bitc::ATTR_KIND_WRITEONLY:
1521 return Attribute::WriteOnly;
1522 case bitc::ATTR_KIND_Z_EXT:
1523 return Attribute::ZExt;
1524 case bitc::ATTR_KIND_IMMARG:
1525 return Attribute::ImmArg;
1529 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1530 unsigned &Alignment) {
1531 // Note: Alignment in bitcode files is incremented by 1, so that zero
1532 // can be used for default alignment.
1533 if (Exponent > Value::MaxAlignmentExponent + 1)
1534 return error("Invalid alignment value");
1535 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1536 return Error::success();
1539 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
1540 *Kind = getAttrFromCode(Code);
1541 if (*Kind == Attribute::None)
1542 return error("Unknown attribute kind (" + Twine(Code) + ")");
1543 return Error::success();
1546 Error BitcodeReader::parseAttributeGroupBlock() {
1547 if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1550 if (!MAttributeGroups.empty())
1551 return error("Invalid multiple blocks");
1553 SmallVector<uint64_t, 64> Record;
1555 // Read all the records.
1557 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1559 return MaybeEntry.takeError();
1560 BitstreamEntry Entry = MaybeEntry.get();
1562 switch (Entry.Kind) {
1563 case BitstreamEntry::SubBlock: // Handled for us already.
1564 case BitstreamEntry::Error:
1565 return error("Malformed block");
1566 case BitstreamEntry::EndBlock:
1567 return Error::success();
1568 case BitstreamEntry::Record:
1569 // The interesting case.
1575 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1577 return MaybeRecord.takeError();
1578 switch (MaybeRecord.get()) {
1579 default: // Default behavior: ignore.
1581 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1582 if (Record.size() < 3)
1583 return error("Invalid record");
1585 uint64_t GrpID = Record[0];
1586 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1589 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1590 if (Record[i] == 0) { // Enum attribute
1591 Attribute::AttrKind Kind;
1592 if (Error Err = parseAttrKind(Record[++i], &Kind))
1595 // Upgrade old-style byval attribute to one with a type, even if it's
1596 // nullptr. We will have to insert the real type when we associate
1597 // this AttributeList with a function.
1598 if (Kind == Attribute::ByVal)
1599 B.addByValAttr(nullptr);
1601 B.addAttribute(Kind);
1602 } else if (Record[i] == 1) { // Integer attribute
1603 Attribute::AttrKind Kind;
1604 if (Error Err = parseAttrKind(Record[++i], &Kind))
1606 if (Kind == Attribute::Alignment)
1607 B.addAlignmentAttr(Record[++i]);
1608 else if (Kind == Attribute::StackAlignment)
1609 B.addStackAlignmentAttr(Record[++i]);
1610 else if (Kind == Attribute::Dereferenceable)
1611 B.addDereferenceableAttr(Record[++i]);
1612 else if (Kind == Attribute::DereferenceableOrNull)
1613 B.addDereferenceableOrNullAttr(Record[++i]);
1614 else if (Kind == Attribute::AllocSize)
1615 B.addAllocSizeAttrFromRawRepr(Record[++i]);
1616 } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
1617 bool HasValue = (Record[i++] == 4);
1618 SmallString<64> KindStr;
1619 SmallString<64> ValStr;
1621 while (Record[i] != 0 && i != e)
1622 KindStr += Record[i++];
1623 assert(Record[i] == 0 && "Kind string not null terminated");
1626 // Has a value associated with it.
1627 ++i; // Skip the '0' that terminates the "kind" string.
1628 while (Record[i] != 0 && i != e)
1629 ValStr += Record[i++];
1630 assert(Record[i] == 0 && "Value string not null terminated");
1633 B.addAttribute(KindStr.str(), ValStr.str());
1635 assert((Record[i] == 5 || Record[i] == 6) &&
1636 "Invalid attribute group entry");
1637 bool HasType = Record[i] == 6;
1638 Attribute::AttrKind Kind;
1639 if (Error Err = parseAttrKind(Record[++i], &Kind))
1641 if (Kind == Attribute::ByVal)
1642 B.addByValAttr(HasType ? getTypeByID(Record[++i]) : nullptr);
1646 MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1653 Error BitcodeReader::parseTypeTable() {
1654 if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1657 return parseTypeTableBody();
1660 Error BitcodeReader::parseTypeTableBody() {
1661 if (!TypeList.empty())
1662 return error("Invalid multiple blocks");
1664 SmallVector<uint64_t, 64> Record;
1665 unsigned NumRecords = 0;
1667 SmallString<64> TypeName;
1669 // Read all the records for this type table.
1671 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1673 return MaybeEntry.takeError();
1674 BitstreamEntry Entry = MaybeEntry.get();
1676 switch (Entry.Kind) {
1677 case BitstreamEntry::SubBlock: // Handled for us already.
1678 case BitstreamEntry::Error:
1679 return error("Malformed block");
1680 case BitstreamEntry::EndBlock:
1681 if (NumRecords != TypeList.size())
1682 return error("Malformed block");
1683 return Error::success();
1684 case BitstreamEntry::Record:
1685 // The interesting case.
1691 Type *ResultTy = nullptr;
1692 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1694 return MaybeRecord.takeError();
1695 switch (MaybeRecord.get()) {
1697 return error("Invalid value");
1698 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1699 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1700 // type list. This allows us to reserve space.
1701 if (Record.size() < 1)
1702 return error("Invalid record");
1703 TypeList.resize(Record[0]);
1705 case bitc::TYPE_CODE_VOID: // VOID
1706 ResultTy = Type::getVoidTy(Context);
1708 case bitc::TYPE_CODE_HALF: // HALF
1709 ResultTy = Type::getHalfTy(Context);
1711 case bitc::TYPE_CODE_FLOAT: // FLOAT
1712 ResultTy = Type::getFloatTy(Context);
1714 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1715 ResultTy = Type::getDoubleTy(Context);
1717 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1718 ResultTy = Type::getX86_FP80Ty(Context);
1720 case bitc::TYPE_CODE_FP128: // FP128
1721 ResultTy = Type::getFP128Ty(Context);
1723 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1724 ResultTy = Type::getPPC_FP128Ty(Context);
1726 case bitc::TYPE_CODE_LABEL: // LABEL
1727 ResultTy = Type::getLabelTy(Context);
1729 case bitc::TYPE_CODE_METADATA: // METADATA
1730 ResultTy = Type::getMetadataTy(Context);
1732 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1733 ResultTy = Type::getX86_MMXTy(Context);
1735 case bitc::TYPE_CODE_TOKEN: // TOKEN
1736 ResultTy = Type::getTokenTy(Context);
1738 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1739 if (Record.size() < 1)
1740 return error("Invalid record");
1742 uint64_t NumBits = Record[0];
1743 if (NumBits < IntegerType::MIN_INT_BITS ||
1744 NumBits > IntegerType::MAX_INT_BITS)
1745 return error("Bitwidth for integer type out of range");
1746 ResultTy = IntegerType::get(Context, NumBits);
1749 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1750 // [pointee type, address space]
1751 if (Record.size() < 1)
1752 return error("Invalid record");
1753 unsigned AddressSpace = 0;
1754 if (Record.size() == 2)
1755 AddressSpace = Record[1];
1756 ResultTy = getTypeByID(Record[0]);
1758 !PointerType::isValidElementType(ResultTy))
1759 return error("Invalid type");
1760 ResultTy = PointerType::get(ResultTy, AddressSpace);
1763 case bitc::TYPE_CODE_FUNCTION_OLD: {
1764 // FIXME: attrid is dead, remove it in LLVM 4.0
1765 // FUNCTION: [vararg, attrid, retty, paramty x N]
1766 if (Record.size() < 3)
1767 return error("Invalid record");
1768 SmallVector<Type*, 8> ArgTys;
1769 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1770 if (Type *T = getTypeByID(Record[i]))
1771 ArgTys.push_back(T);
1776 ResultTy = getTypeByID(Record[2]);
1777 if (!ResultTy || ArgTys.size() < Record.size()-3)
1778 return error("Invalid type");
1780 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1783 case bitc::TYPE_CODE_FUNCTION: {
1784 // FUNCTION: [vararg, retty, paramty x N]
1785 if (Record.size() < 2)
1786 return error("Invalid record");
1787 SmallVector<Type*, 8> ArgTys;
1788 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1789 if (Type *T = getTypeByID(Record[i])) {
1790 if (!FunctionType::isValidArgumentType(T))
1791 return error("Invalid function argument type");
1792 ArgTys.push_back(T);
1798 ResultTy = getTypeByID(Record[1]);
1799 if (!ResultTy || ArgTys.size() < Record.size()-2)
1800 return error("Invalid type");
1802 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1805 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1806 if (Record.size() < 1)
1807 return error("Invalid record");
1808 SmallVector<Type*, 8> EltTys;
1809 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1810 if (Type *T = getTypeByID(Record[i]))
1811 EltTys.push_back(T);
1815 if (EltTys.size() != Record.size()-1)
1816 return error("Invalid type");
1817 ResultTy = StructType::get(Context, EltTys, Record[0]);
1820 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1821 if (convertToString(Record, 0, TypeName))
1822 return error("Invalid record");
1825 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1826 if (Record.size() < 1)
1827 return error("Invalid record");
1829 if (NumRecords >= TypeList.size())
1830 return error("Invalid TYPE table");
1832 // Check to see if this was forward referenced, if so fill in the temp.
1833 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1835 Res->setName(TypeName);
1836 TypeList[NumRecords] = nullptr;
1837 } else // Otherwise, create a new struct.
1838 Res = createIdentifiedStructType(Context, TypeName);
1841 SmallVector<Type*, 8> EltTys;
1842 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1843 if (Type *T = getTypeByID(Record[i]))
1844 EltTys.push_back(T);
1848 if (EltTys.size() != Record.size()-1)
1849 return error("Invalid record");
1850 Res->setBody(EltTys, Record[0]);
1854 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1855 if (Record.size() != 1)
1856 return error("Invalid record");
1858 if (NumRecords >= TypeList.size())
1859 return error("Invalid TYPE table");
1861 // Check to see if this was forward referenced, if so fill in the temp.
1862 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1864 Res->setName(TypeName);
1865 TypeList[NumRecords] = nullptr;
1866 } else // Otherwise, create a new struct with no body.
1867 Res = createIdentifiedStructType(Context, TypeName);
1872 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1873 if (Record.size() < 2)
1874 return error("Invalid record");
1875 ResultTy = getTypeByID(Record[1]);
1876 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1877 return error("Invalid type");
1878 ResultTy = ArrayType::get(ResultTy, Record[0]);
1880 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1881 if (Record.size() < 2)
1882 return error("Invalid record");
1884 return error("Invalid vector length");
1885 ResultTy = getTypeByID(Record[1]);
1886 if (!ResultTy || !StructType::isValidElementType(ResultTy))
1887 return error("Invalid type");
1888 ResultTy = VectorType::get(ResultTy, Record[0]);
1892 if (NumRecords >= TypeList.size())
1893 return error("Invalid TYPE table");
1894 if (TypeList[NumRecords])
1896 "Invalid TYPE table: Only named structs can be forward referenced");
1897 assert(ResultTy && "Didn't read a type?");
1898 TypeList[NumRecords++] = ResultTy;
1902 Error BitcodeReader::parseOperandBundleTags() {
1903 if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1906 if (!BundleTags.empty())
1907 return error("Invalid multiple blocks");
1909 SmallVector<uint64_t, 64> Record;
1912 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1914 return MaybeEntry.takeError();
1915 BitstreamEntry Entry = MaybeEntry.get();
1917 switch (Entry.Kind) {
1918 case BitstreamEntry::SubBlock: // Handled for us already.
1919 case BitstreamEntry::Error:
1920 return error("Malformed block");
1921 case BitstreamEntry::EndBlock:
1922 return Error::success();
1923 case BitstreamEntry::Record:
1924 // The interesting case.
1928 // Tags are implicitly mapped to integers by their order.
1930 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1932 return MaybeRecord.takeError();
1933 if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
1934 return error("Invalid record");
1936 // OPERAND_BUNDLE_TAG: [strchr x N]
1937 BundleTags.emplace_back();
1938 if (convertToString(Record, 0, BundleTags.back()))
1939 return error("Invalid record");
1944 Error BitcodeReader::parseSyncScopeNames() {
1945 if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1949 return error("Invalid multiple synchronization scope names blocks");
1951 SmallVector<uint64_t, 64> Record;
1953 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1955 return MaybeEntry.takeError();
1956 BitstreamEntry Entry = MaybeEntry.get();
1958 switch (Entry.Kind) {
1959 case BitstreamEntry::SubBlock: // Handled for us already.
1960 case BitstreamEntry::Error:
1961 return error("Malformed block");
1962 case BitstreamEntry::EndBlock:
1964 return error("Invalid empty synchronization scope names block");
1965 return Error::success();
1966 case BitstreamEntry::Record:
1967 // The interesting case.
1971 // Synchronization scope names are implicitly mapped to synchronization
1972 // scope IDs by their order.
1974 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1976 return MaybeRecord.takeError();
1977 if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
1978 return error("Invalid record");
1980 SmallString<16> SSN;
1981 if (convertToString(Record, 0, SSN))
1982 return error("Invalid record");
1984 SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
1989 /// Associate a value with its name from the given index in the provided record.
1990 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1991 unsigned NameIndex, Triple &TT) {
1992 SmallString<128> ValueName;
1993 if (convertToString(Record, NameIndex, ValueName))
1994 return error("Invalid record");
1995 unsigned ValueID = Record[0];
1996 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1997 return error("Invalid record");
1998 Value *V = ValueList[ValueID];
2000 StringRef NameStr(ValueName.data(), ValueName.size());
2001 if (NameStr.find_first_of(0) != StringRef::npos)
2002 return error("Invalid value name");
2003 V->setName(NameStr);
2004 auto *GO = dyn_cast<GlobalObject>(V);
2006 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
2007 if (TT.supportsCOMDAT())
2008 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2010 GO->setComdat(nullptr);
2016 /// Helper to note and return the current location, and jump to the given
2018 static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
2019 BitstreamCursor &Stream) {
2020 // Save the current parsing location so we can jump back at the end
2022 uint64_t CurrentBit = Stream.GetCurrentBitNo();
2023 if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2024 return std::move(JumpFailed);
2025 Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2027 return MaybeEntry.takeError();
2028 assert(MaybeEntry.get().Kind == BitstreamEntry::SubBlock);
2029 assert(MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID);
2033 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2035 ArrayRef<uint64_t> Record) {
2036 // Note that we subtract 1 here because the offset is relative to one word
2037 // before the start of the identification or module block, which was
2038 // historically always the start of the regular bitcode header.
2039 uint64_t FuncWordOffset = Record[1] - 1;
2040 uint64_t FuncBitOffset = FuncWordOffset * 32;
2041 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2042 // Set the LastFunctionBlockBit to point to the last function block.
2043 // Later when parsing is resumed after function materialization,
2044 // we can simply skip that last function block.
2045 if (FuncBitOffset > LastFunctionBlockBit)
2046 LastFunctionBlockBit = FuncBitOffset;
2049 /// Read a new-style GlobalValue symbol table.
2050 Error BitcodeReader::parseGlobalValueSymbolTable() {
2051 unsigned FuncBitcodeOffsetDelta =
2052 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2054 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2057 SmallVector<uint64_t, 64> Record;
2059 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2061 return MaybeEntry.takeError();
2062 BitstreamEntry Entry = MaybeEntry.get();
2064 switch (Entry.Kind) {
2065 case BitstreamEntry::SubBlock:
2066 case BitstreamEntry::Error:
2067 return error("Malformed block");
2068 case BitstreamEntry::EndBlock:
2069 return Error::success();
2070 case BitstreamEntry::Record:
2075 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2077 return MaybeRecord.takeError();
2078 switch (MaybeRecord.get()) {
2079 case bitc::VST_CODE_FNENTRY: // [valueid, offset]
2080 setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2081 cast<Function>(ValueList[Record[0]]), Record);
2087 /// Parse the value symbol table at either the current parsing location or
2088 /// at the given bit offset if provided.
2089 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2090 uint64_t CurrentBit;
2091 // Pass in the Offset to distinguish between calling for the module-level
2092 // VST (where we want to jump to the VST offset) and the function-level
2093 // VST (where we don't).
2095 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2096 if (!MaybeCurrentBit)
2097 return MaybeCurrentBit.takeError();
2098 CurrentBit = MaybeCurrentBit.get();
2099 // If this module uses a string table, read this as a module-level VST.
2101 if (Error Err = parseGlobalValueSymbolTable())
2103 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2105 return Error::success();
2107 // Otherwise, the VST will be in a similar format to a function-level VST,
2108 // and will contain symbol names.
2111 // Compute the delta between the bitcode indices in the VST (the word offset
2112 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2113 // expected by the lazy reader. The reader's EnterSubBlock expects to have
2114 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2115 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2116 // just before entering the VST subblock because: 1) the EnterSubBlock
2117 // changes the AbbrevID width; 2) the VST block is nested within the same
2118 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2119 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2120 // jump to the FUNCTION_BLOCK using this offset later, we don't want
2121 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2122 unsigned FuncBitcodeOffsetDelta =
2123 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2125 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2128 SmallVector<uint64_t, 64> Record;
2130 Triple TT(TheModule->getTargetTriple());
2132 // Read all the records for this value table.
2133 SmallString<128> ValueName;
2136 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2138 return MaybeEntry.takeError();
2139 BitstreamEntry Entry = MaybeEntry.get();
2141 switch (Entry.Kind) {
2142 case BitstreamEntry::SubBlock: // Handled for us already.
2143 case BitstreamEntry::Error:
2144 return error("Malformed block");
2145 case BitstreamEntry::EndBlock:
2147 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2149 return Error::success();
2150 case BitstreamEntry::Record:
2151 // The interesting case.
2157 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2159 return MaybeRecord.takeError();
2160 switch (MaybeRecord.get()) {
2161 default: // Default behavior: unknown type.
2163 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
2164 Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2165 if (Error Err = ValOrErr.takeError())
2170 case bitc::VST_CODE_FNENTRY: {
2171 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2172 Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2173 if (Error Err = ValOrErr.takeError())
2175 Value *V = ValOrErr.get();
2177 // Ignore function offsets emitted for aliases of functions in older
2178 // versions of LLVM.
2179 if (auto *F = dyn_cast<Function>(V))
2180 setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2183 case bitc::VST_CODE_BBENTRY: {
2184 if (convertToString(Record, 1, ValueName))
2185 return error("Invalid record");
2186 BasicBlock *BB = getBasicBlock(Record[0]);
2188 return error("Invalid record");
2190 BB->setName(StringRef(ValueName.data(), ValueName.size()));
2198 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2200 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2205 // There is no such thing as -0 with integers. "-0" really means MININT.
2209 /// Resolve all of the initializers for global values and aliases that we can.
2210 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2211 std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2212 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
2213 IndirectSymbolInitWorklist;
2214 std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2215 std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2216 std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2218 GlobalInitWorklist.swap(GlobalInits);
2219 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2220 FunctionPrefixWorklist.swap(FunctionPrefixes);
2221 FunctionPrologueWorklist.swap(FunctionPrologues);
2222 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2224 while (!GlobalInitWorklist.empty()) {
2225 unsigned ValID = GlobalInitWorklist.back().second;
2226 if (ValID >= ValueList.size()) {
2227 // Not ready to resolve this yet, it requires something later in the file.
2228 GlobalInits.push_back(GlobalInitWorklist.back());
2230 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2231 GlobalInitWorklist.back().first->setInitializer(C);
2233 return error("Expected a constant");
2235 GlobalInitWorklist.pop_back();
2238 while (!IndirectSymbolInitWorklist.empty()) {
2239 unsigned ValID = IndirectSymbolInitWorklist.back().second;
2240 if (ValID >= ValueList.size()) {
2241 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2243 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2245 return error("Expected a constant");
2246 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2247 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2248 return error("Alias and aliasee types don't match");
2249 GIS->setIndirectSymbol(C);
2251 IndirectSymbolInitWorklist.pop_back();
2254 while (!FunctionPrefixWorklist.empty()) {
2255 unsigned ValID = FunctionPrefixWorklist.back().second;
2256 if (ValID >= ValueList.size()) {
2257 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2259 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2260 FunctionPrefixWorklist.back().first->setPrefixData(C);
2262 return error("Expected a constant");
2264 FunctionPrefixWorklist.pop_back();
2267 while (!FunctionPrologueWorklist.empty()) {
2268 unsigned ValID = FunctionPrologueWorklist.back().second;
2269 if (ValID >= ValueList.size()) {
2270 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2272 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2273 FunctionPrologueWorklist.back().first->setPrologueData(C);
2275 return error("Expected a constant");
2277 FunctionPrologueWorklist.pop_back();
2280 while (!FunctionPersonalityFnWorklist.empty()) {
2281 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2282 if (ValID >= ValueList.size()) {
2283 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2285 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2286 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2288 return error("Expected a constant");
2290 FunctionPersonalityFnWorklist.pop_back();
2293 return Error::success();
2296 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2297 SmallVector<uint64_t, 8> Words(Vals.size());
2298 transform(Vals, Words.begin(),
2299 BitcodeReader::decodeSignRotatedValue);
2301 return APInt(TypeBits, Words);
2304 Error BitcodeReader::parseConstants() {
2305 if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2308 SmallVector<uint64_t, 64> Record;
2310 // Read all the records for this value table.
2311 Type *CurTy = Type::getInt32Ty(Context);
2312 Type *CurFullTy = Type::getInt32Ty(Context);
2313 unsigned NextCstNo = ValueList.size();
2316 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2318 return MaybeEntry.takeError();
2319 BitstreamEntry Entry = MaybeEntry.get();
2321 switch (Entry.Kind) {
2322 case BitstreamEntry::SubBlock: // Handled for us already.
2323 case BitstreamEntry::Error:
2324 return error("Malformed block");
2325 case BitstreamEntry::EndBlock:
2326 if (NextCstNo != ValueList.size())
2327 return error("Invalid constant reference");
2329 // Once all the constants have been read, go through and resolve forward
2331 ValueList.resolveConstantForwardRefs();
2332 return Error::success();
2333 case BitstreamEntry::Record:
2334 // The interesting case.
2340 Type *VoidType = Type::getVoidTy(Context);
2342 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2344 return MaybeBitCode.takeError();
2345 switch (unsigned BitCode = MaybeBitCode.get()) {
2346 default: // Default behavior: unknown constant
2347 case bitc::CST_CODE_UNDEF: // UNDEF
2348 V = UndefValue::get(CurTy);
2350 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2352 return error("Invalid record");
2353 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2354 return error("Invalid record");
2355 if (TypeList[Record[0]] == VoidType)
2356 return error("Invalid constant type");
2357 CurFullTy = TypeList[Record[0]];
2358 CurTy = flattenPointerTypes(CurFullTy);
2359 continue; // Skip the ValueList manipulation.
2360 case bitc::CST_CODE_NULL: // NULL
2361 V = Constant::getNullValue(CurTy);
2363 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2364 if (!CurTy->isIntegerTy() || Record.empty())
2365 return error("Invalid record");
2366 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2368 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2369 if (!CurTy->isIntegerTy() || Record.empty())
2370 return error("Invalid record");
2373 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2374 V = ConstantInt::get(Context, VInt);
2378 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2380 return error("Invalid record");
2381 if (CurTy->isHalfTy())
2382 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2383 APInt(16, (uint16_t)Record[0])));
2384 else if (CurTy->isFloatTy())
2385 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2386 APInt(32, (uint32_t)Record[0])));
2387 else if (CurTy->isDoubleTy())
2388 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2389 APInt(64, Record[0])));
2390 else if (CurTy->isX86_FP80Ty()) {
2391 // Bits are not stored the same way as a normal i80 APInt, compensate.
2392 uint64_t Rearrange[2];
2393 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2394 Rearrange[1] = Record[0] >> 48;
2395 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2396 APInt(80, Rearrange)));
2397 } else if (CurTy->isFP128Ty())
2398 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2399 APInt(128, Record)));
2400 else if (CurTy->isPPC_FP128Ty())
2401 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2402 APInt(128, Record)));
2404 V = UndefValue::get(CurTy);
2408 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2410 return error("Invalid record");
2412 unsigned Size = Record.size();
2413 SmallVector<Constant*, 16> Elts;
2415 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2416 for (unsigned i = 0; i != Size; ++i)
2417 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2418 STy->getElementType(i)));
2419 V = ConstantStruct::get(STy, Elts);
2420 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2421 Type *EltTy = ATy->getElementType();
2422 for (unsigned i = 0; i != Size; ++i)
2423 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2424 V = ConstantArray::get(ATy, Elts);
2425 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2426 Type *EltTy = VTy->getElementType();
2427 for (unsigned i = 0; i != Size; ++i)
2428 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2429 V = ConstantVector::get(Elts);
2431 V = UndefValue::get(CurTy);
2435 case bitc::CST_CODE_STRING: // STRING: [values]
2436 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2438 return error("Invalid record");
2440 SmallString<16> Elts(Record.begin(), Record.end());
2441 V = ConstantDataArray::getString(Context, Elts,
2442 BitCode == bitc::CST_CODE_CSTRING);
2445 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2447 return error("Invalid record");
2449 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2450 if (EltTy->isIntegerTy(8)) {
2451 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2452 if (isa<VectorType>(CurTy))
2453 V = ConstantDataVector::get(Context, Elts);
2455 V = ConstantDataArray::get(Context, Elts);
2456 } else if (EltTy->isIntegerTy(16)) {
2457 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2458 if (isa<VectorType>(CurTy))
2459 V = ConstantDataVector::get(Context, Elts);
2461 V = ConstantDataArray::get(Context, Elts);
2462 } else if (EltTy->isIntegerTy(32)) {
2463 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2464 if (isa<VectorType>(CurTy))
2465 V = ConstantDataVector::get(Context, Elts);
2467 V = ConstantDataArray::get(Context, Elts);
2468 } else if (EltTy->isIntegerTy(64)) {
2469 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2470 if (isa<VectorType>(CurTy))
2471 V = ConstantDataVector::get(Context, Elts);
2473 V = ConstantDataArray::get(Context, Elts);
2474 } else if (EltTy->isHalfTy()) {
2475 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2476 if (isa<VectorType>(CurTy))
2477 V = ConstantDataVector::getFP(Context, Elts);
2479 V = ConstantDataArray::getFP(Context, Elts);
2480 } else if (EltTy->isFloatTy()) {
2481 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2482 if (isa<VectorType>(CurTy))
2483 V = ConstantDataVector::getFP(Context, Elts);
2485 V = ConstantDataArray::getFP(Context, Elts);
2486 } else if (EltTy->isDoubleTy()) {
2487 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2488 if (isa<VectorType>(CurTy))
2489 V = ConstantDataVector::getFP(Context, Elts);
2491 V = ConstantDataArray::getFP(Context, Elts);
2493 return error("Invalid type for value");
2497 case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
2498 if (Record.size() < 2)
2499 return error("Invalid record");
2500 int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
2502 V = UndefValue::get(CurTy); // Unknown unop.
2504 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2506 V = ConstantExpr::get(Opc, LHS, Flags);
2510 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2511 if (Record.size() < 3)
2512 return error("Invalid record");
2513 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2515 V = UndefValue::get(CurTy); // Unknown binop.
2517 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2518 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2520 if (Record.size() >= 4) {
2521 if (Opc == Instruction::Add ||
2522 Opc == Instruction::Sub ||
2523 Opc == Instruction::Mul ||
2524 Opc == Instruction::Shl) {
2525 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2526 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2527 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2528 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2529 } else if (Opc == Instruction::SDiv ||
2530 Opc == Instruction::UDiv ||
2531 Opc == Instruction::LShr ||
2532 Opc == Instruction::AShr) {
2533 if (Record[3] & (1 << bitc::PEO_EXACT))
2534 Flags |= SDivOperator::IsExact;
2537 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2541 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2542 if (Record.size() < 3)
2543 return error("Invalid record");
2544 int Opc = getDecodedCastOpcode(Record[0]);
2546 V = UndefValue::get(CurTy); // Unknown cast.
2548 Type *OpTy = getTypeByID(Record[1]);
2550 return error("Invalid record");
2551 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2552 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2553 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2557 case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2558 case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2559 case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2562 Type *PointeeType = nullptr;
2563 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2565 PointeeType = getTypeByID(Record[OpNum++]);
2567 bool InBounds = false;
2568 Optional<unsigned> InRangeIndex;
2569 if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2570 uint64_t Op = Record[OpNum++];
2572 InRangeIndex = Op >> 1;
2573 } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2576 SmallVector<Constant*, 16> Elts;
2577 Type *Elt0FullTy = nullptr;
2578 while (OpNum != Record.size()) {
2580 Elt0FullTy = getFullyStructuredTypeByID(Record[OpNum]);
2581 Type *ElTy = getTypeByID(Record[OpNum++]);
2583 return error("Invalid record");
2584 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2587 if (Elts.size() < 1)
2588 return error("Invalid gep with no operands");
2590 Type *ImplicitPointeeType =
2591 getPointerElementFlatType(Elt0FullTy->getScalarType());
2593 PointeeType = ImplicitPointeeType;
2594 else if (PointeeType != ImplicitPointeeType)
2595 return error("Explicit gep operator type does not match pointee type "
2596 "of pointer operand");
2598 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2599 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2600 InBounds, InRangeIndex);
2603 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2604 if (Record.size() < 3)
2605 return error("Invalid record");
2607 Type *SelectorTy = Type::getInt1Ty(Context);
2609 // The selector might be an i1 or an <n x i1>
2610 // Get the type from the ValueList before getting a forward ref.
2611 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2612 if (Value *V = ValueList[Record[0]])
2613 if (SelectorTy != V->getType())
2614 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2616 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2618 ValueList.getConstantFwdRef(Record[1],CurTy),
2619 ValueList.getConstantFwdRef(Record[2],CurTy));
2622 case bitc::CST_CODE_CE_EXTRACTELT
2623 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2624 if (Record.size() < 3)
2625 return error("Invalid record");
2627 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2629 return error("Invalid record");
2630 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2631 Constant *Op1 = nullptr;
2632 if (Record.size() == 4) {
2633 Type *IdxTy = getTypeByID(Record[2]);
2635 return error("Invalid record");
2636 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2637 } else // TODO: Remove with llvm 4.0
2638 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2640 return error("Invalid record");
2641 V = ConstantExpr::getExtractElement(Op0, Op1);
2644 case bitc::CST_CODE_CE_INSERTELT
2645 : { // CE_INSERTELT: [opval, opval, opty, opval]
2646 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2647 if (Record.size() < 3 || !OpTy)
2648 return error("Invalid record");
2649 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2650 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2651 OpTy->getElementType());
2652 Constant *Op2 = nullptr;
2653 if (Record.size() == 4) {
2654 Type *IdxTy = getTypeByID(Record[2]);
2656 return error("Invalid record");
2657 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2658 } else // TODO: Remove with llvm 4.0
2659 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2661 return error("Invalid record");
2662 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2665 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2666 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2667 if (Record.size() < 3 || !OpTy)
2668 return error("Invalid record");
2669 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2670 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2671 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2672 OpTy->getNumElements());
2673 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2674 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2677 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2678 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2680 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2681 if (Record.size() < 4 || !RTy || !OpTy)
2682 return error("Invalid record");
2683 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2684 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2685 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2686 RTy->getNumElements());
2687 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2688 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2691 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2692 if (Record.size() < 4)
2693 return error("Invalid record");
2694 Type *OpTy = getTypeByID(Record[0]);
2696 return error("Invalid record");
2697 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2698 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2700 if (OpTy->isFPOrFPVectorTy())
2701 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2703 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2706 // This maintains backward compatibility, pre-asm dialect keywords.
2707 // FIXME: Remove with the 4.0 release.
2708 case bitc::CST_CODE_INLINEASM_OLD: {
2709 if (Record.size() < 2)
2710 return error("Invalid record");
2711 std::string AsmStr, ConstrStr;
2712 bool HasSideEffects = Record[0] & 1;
2713 bool IsAlignStack = Record[0] >> 1;
2714 unsigned AsmStrSize = Record[1];
2715 if (2+AsmStrSize >= Record.size())
2716 return error("Invalid record");
2717 unsigned ConstStrSize = Record[2+AsmStrSize];
2718 if (3+AsmStrSize+ConstStrSize > Record.size())
2719 return error("Invalid record");
2721 for (unsigned i = 0; i != AsmStrSize; ++i)
2722 AsmStr += (char)Record[2+i];
2723 for (unsigned i = 0; i != ConstStrSize; ++i)
2724 ConstrStr += (char)Record[3+AsmStrSize+i];
2725 UpgradeInlineAsmString(&AsmStr);
2727 cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2728 ConstrStr, HasSideEffects, IsAlignStack);
2731 // This version adds support for the asm dialect keywords (e.g.,
2733 case bitc::CST_CODE_INLINEASM: {
2734 if (Record.size() < 2)
2735 return error("Invalid record");
2736 std::string AsmStr, ConstrStr;
2737 bool HasSideEffects = Record[0] & 1;
2738 bool IsAlignStack = (Record[0] >> 1) & 1;
2739 unsigned AsmDialect = Record[0] >> 2;
2740 unsigned AsmStrSize = Record[1];
2741 if (2+AsmStrSize >= Record.size())
2742 return error("Invalid record");
2743 unsigned ConstStrSize = Record[2+AsmStrSize];
2744 if (3+AsmStrSize+ConstStrSize > Record.size())
2745 return error("Invalid record");
2747 for (unsigned i = 0; i != AsmStrSize; ++i)
2748 AsmStr += (char)Record[2+i];
2749 for (unsigned i = 0; i != ConstStrSize; ++i)
2750 ConstrStr += (char)Record[3+AsmStrSize+i];
2751 UpgradeInlineAsmString(&AsmStr);
2753 cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2754 ConstrStr, HasSideEffects, IsAlignStack,
2755 InlineAsm::AsmDialect(AsmDialect));
2758 case bitc::CST_CODE_BLOCKADDRESS:{
2759 if (Record.size() < 3)
2760 return error("Invalid record");
2761 Type *FnTy = getTypeByID(Record[0]);
2763 return error("Invalid record");
2765 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2767 return error("Invalid record");
2769 // If the function is already parsed we can insert the block address right
2772 unsigned BBID = Record[2];
2774 // Invalid reference to entry block.
2775 return error("Invalid ID");
2777 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2778 for (size_t I = 0, E = BBID; I != E; ++I) {
2780 return error("Invalid ID");
2785 // Otherwise insert a placeholder and remember it so it can be inserted
2786 // when the function is parsed.
2787 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2789 BasicBlockFwdRefQueue.push_back(Fn);
2790 if (FwdBBs.size() < BBID + 1)
2791 FwdBBs.resize(BBID + 1);
2793 FwdBBs[BBID] = BasicBlock::Create(Context);
2796 V = BlockAddress::get(Fn, BB);
2801 assert(V->getType() == flattenPointerTypes(CurFullTy) &&
2802 "Incorrect fully structured type provided for Constant");
2803 ValueList.assignValue(V, NextCstNo, CurFullTy);
2808 Error BitcodeReader::parseUseLists() {
2809 if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2812 // Read all the records.
2813 SmallVector<uint64_t, 64> Record;
2816 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2818 return MaybeEntry.takeError();
2819 BitstreamEntry Entry = MaybeEntry.get();
2821 switch (Entry.Kind) {
2822 case BitstreamEntry::SubBlock: // Handled for us already.
2823 case BitstreamEntry::Error:
2824 return error("Malformed block");
2825 case BitstreamEntry::EndBlock:
2826 return Error::success();
2827 case BitstreamEntry::Record:
2828 // The interesting case.
2832 // Read a use list record.
2835 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2837 return MaybeRecord.takeError();
2838 switch (MaybeRecord.get()) {
2839 default: // Default behavior: unknown type.
2841 case bitc::USELIST_CODE_BB:
2844 case bitc::USELIST_CODE_DEFAULT: {
2845 unsigned RecordLength = Record.size();
2846 if (RecordLength < 3)
2847 // Records should have at least an ID and two indexes.
2848 return error("Invalid record");
2849 unsigned ID = Record.back();
2854 assert(ID < FunctionBBs.size() && "Basic block not found");
2855 V = FunctionBBs[ID];
2858 unsigned NumUses = 0;
2859 SmallDenseMap<const Use *, unsigned, 16> Order;
2860 for (const Use &U : V->materialized_uses()) {
2861 if (++NumUses > Record.size())
2863 Order[&U] = Record[NumUses - 1];
2865 if (Order.size() != Record.size() || NumUses > Record.size())
2866 // Mismatches can happen if the functions are being materialized lazily
2867 // (out-of-order), or a value has been upgraded.
2870 V->sortUseList([&](const Use &L, const Use &R) {
2871 return Order.lookup(&L) < Order.lookup(&R);
2879 /// When we see the block for metadata, remember where it is and then skip it.
2880 /// This lets us lazily deserialize the metadata.
2881 Error BitcodeReader::rememberAndSkipMetadata() {
2882 // Save the current stream state.
2883 uint64_t CurBit = Stream.GetCurrentBitNo();
2884 DeferredMetadataInfo.push_back(CurBit);
2886 // Skip over the block for now.
2887 if (Error Err = Stream.SkipBlock())
2889 return Error::success();
2892 Error BitcodeReader::materializeMetadata() {
2893 for (uint64_t BitPos : DeferredMetadataInfo) {
2894 // Move the bit stream to the saved position.
2895 if (Error JumpFailed = Stream.JumpToBit(BitPos))
2897 if (Error Err = MDLoader->parseModuleMetadata())
2901 // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2903 if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
2904 NamedMDNode *LinkerOpts =
2905 TheModule->getOrInsertNamedMetadata("llvm.linker.options");
2906 for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2907 LinkerOpts->addOperand(cast<MDNode>(MDOptions));
2910 DeferredMetadataInfo.clear();
2911 return Error::success();
2914 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2916 /// When we see the block for a function body, remember where it is and then
2917 /// skip it. This lets us lazily deserialize the functions.
2918 Error BitcodeReader::rememberAndSkipFunctionBody() {
2919 // Get the function we are talking about.
2920 if (FunctionsWithBodies.empty())
2921 return error("Insufficient function protos");
2923 Function *Fn = FunctionsWithBodies.back();
2924 FunctionsWithBodies.pop_back();
2926 // Save the current stream state.
2927 uint64_t CurBit = Stream.GetCurrentBitNo();
2929 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2930 "Mismatch between VST and scanned function offsets");
2931 DeferredFunctionInfo[Fn] = CurBit;
2933 // Skip over the function block for now.
2934 if (Error Err = Stream.SkipBlock())
2936 return Error::success();
2939 Error BitcodeReader::globalCleanup() {
2940 // Patch the initializers for globals and aliases up.
2941 if (Error Err = resolveGlobalAndIndirectSymbolInits())
2943 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2944 return error("Malformed global initializer set");
2946 // Look for intrinsic functions which need to be upgraded at some point
2947 for (Function &F : *TheModule) {
2948 MDLoader->upgradeDebugIntrinsics(F);
2950 if (UpgradeIntrinsicFunction(&F, NewFn))
2951 UpgradedIntrinsics[&F] = NewFn;
2952 else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2953 // Some types could be renamed during loading if several modules are
2954 // loaded in the same LLVMContext (LTO scenario). In this case we should
2955 // remangle intrinsics names as well.
2956 RemangledIntrinsics[&F] = Remangled.getValue();
2959 // Look for global variables which need to be renamed.
2960 std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
2961 for (GlobalVariable &GV : TheModule->globals())
2962 if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
2963 UpgradedVariables.emplace_back(&GV, Upgraded);
2964 for (auto &Pair : UpgradedVariables) {
2965 Pair.first->eraseFromParent();
2966 TheModule->getGlobalList().push_back(Pair.second);
2969 // Force deallocation of memory for these vectors to favor the client that
2970 // want lazy deserialization.
2971 std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
2972 std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
2973 IndirectSymbolInits);
2974 return Error::success();
2977 /// Support for lazy parsing of function bodies. This is required if we
2978 /// either have an old bitcode file without a VST forward declaration record,
2979 /// or if we have an anonymous function being materialized, since anonymous
2980 /// functions do not have a name and are therefore not in the VST.
2981 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2982 if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
2985 if (Stream.AtEndOfStream())
2986 return error("Could not find function in stream");
2988 if (!SeenFirstFunctionBody)
2989 return error("Trying to materialize functions before seeing function blocks");
2991 // An old bitcode file with the symbol table at the end would have
2992 // finished the parse greedily.
2993 assert(SeenValueSymbolTable);
2995 SmallVector<uint64_t, 64> Record;
2998 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3000 return MaybeEntry.takeError();
3001 llvm::BitstreamEntry Entry = MaybeEntry.get();
3003 switch (Entry.Kind) {
3005 return error("Expect SubBlock");
3006 case BitstreamEntry::SubBlock:
3009 return error("Expect function block");
3010 case bitc::FUNCTION_BLOCK_ID:
3011 if (Error Err = rememberAndSkipFunctionBody())
3013 NextUnreadBit = Stream.GetCurrentBitNo();
3014 return Error::success();
3020 bool BitcodeReaderBase::readBlockInfo() {
3021 Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3022 Stream.ReadBlockInfoBlock();
3023 if (!MaybeNewBlockInfo)
3024 return true; // FIXME Handle the error.
3025 Optional<BitstreamBlockInfo> NewBlockInfo =
3026 std::move(MaybeNewBlockInfo.get());
3029 BlockInfo = std::move(*NewBlockInfo);
3033 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3034 // v1: [selection_kind, name]
3035 // v2: [strtab_offset, strtab_size, selection_kind]
3037 std::tie(Name, Record) = readNameFromStrtab(Record);
3040 return error("Invalid record");
3041 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3042 std::string OldFormatName;
3044 if (Record.size() < 2)
3045 return error("Invalid record");
3046 unsigned ComdatNameSize = Record[1];
3047 OldFormatName.reserve(ComdatNameSize);
3048 for (unsigned i = 0; i != ComdatNameSize; ++i)
3049 OldFormatName += (char)Record[2 + i];
3050 Name = OldFormatName;
3052 Comdat *C = TheModule->getOrInsertComdat(Name);
3053 C->setSelectionKind(SK);
3054 ComdatList.push_back(C);
3055 return Error::success();
3058 static void inferDSOLocal(GlobalValue *GV) {
3059 // infer dso_local from linkage and visibility if it is not encoded.
3060 if (GV->hasLocalLinkage() ||
3061 (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3062 GV->setDSOLocal(true);
3065 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3066 // v1: [pointer type, isconst, initid, linkage, alignment, section,
3067 // visibility, threadlocal, unnamed_addr, externally_initialized,
3068 // dllstorageclass, comdat, attributes, preemption specifier,
3069 // partition strtab offset, partition strtab size] (name in VST)
3070 // v2: [strtab_offset, strtab_size, v1]
3072 std::tie(Name, Record) = readNameFromStrtab(Record);
3074 if (Record.size() < 6)
3075 return error("Invalid record");
3076 Type *FullTy = getFullyStructuredTypeByID(Record[0]);
3077 Type *Ty = flattenPointerTypes(FullTy);
3079 return error("Invalid record");
3080 bool isConstant = Record[1] & 1;
3081 bool explicitType = Record[1] & 2;
3082 unsigned AddressSpace;
3084 AddressSpace = Record[1] >> 2;
3086 if (!Ty->isPointerTy())
3087 return error("Invalid type for value");
3088 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3089 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
3092 uint64_t RawLinkage = Record[3];
3093 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3095 if (Error Err = parseAlignmentValue(Record[4], Alignment))
3097 std::string Section;
3099 if (Record[5] - 1 >= SectionTable.size())
3100 return error("Invalid ID");
3101 Section = SectionTable[Record[5] - 1];
3103 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3104 // Local linkage must have default visibility.
3105 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3106 // FIXME: Change to an error if non-default in 4.0.
3107 Visibility = getDecodedVisibility(Record[6]);
3109 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3110 if (Record.size() > 7)
3111 TLM = getDecodedThreadLocalMode(Record[7]);
3113 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3114 if (Record.size() > 8)
3115 UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3117 bool ExternallyInitialized = false;
3118 if (Record.size() > 9)
3119 ExternallyInitialized = Record[9];
3121 GlobalVariable *NewGV =
3122 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
3123 nullptr, TLM, AddressSpace, ExternallyInitialized);
3124 NewGV->setAlignment(Alignment);
3125 if (!Section.empty())
3126 NewGV->setSection(Section);
3127 NewGV->setVisibility(Visibility);
3128 NewGV->setUnnamedAddr(UnnamedAddr);
3130 if (Record.size() > 10)
3131 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3133 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3135 FullTy = PointerType::get(FullTy, AddressSpace);
3136 assert(NewGV->getType() == flattenPointerTypes(FullTy) &&
3137 "Incorrect fully specified type for GlobalVariable");
3138 ValueList.push_back(NewGV, FullTy);
3140 // Remember which value to use for the global initializer.
3141 if (unsigned InitID = Record[2])
3142 GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
3144 if (Record.size() > 11) {
3145 if (unsigned ComdatID = Record[11]) {
3146 if (ComdatID > ComdatList.size())
3147 return error("Invalid global variable comdat ID");
3148 NewGV->setComdat(ComdatList[ComdatID - 1]);
3150 } else if (hasImplicitComdat(RawLinkage)) {
3151 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3154 if (Record.size() > 12) {
3155 auto AS = getAttributes(Record[12]).getFnAttributes();
3156 NewGV->setAttributes(AS);
3159 if (Record.size() > 13) {
3160 NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3162 inferDSOLocal(NewGV);
3164 // Check whether we have enough values to read a partition name.
3165 if (Record.size() > 15)
3166 NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3168 return Error::success();
3171 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3172 // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3173 // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3174 // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
3175 // v2: [strtab_offset, strtab_size, v1]
3177 std::tie(Name, Record) = readNameFromStrtab(Record);
3179 if (Record.size() < 8)
3180 return error("Invalid record");
3181 Type *FullFTy = getFullyStructuredTypeByID(Record[0]);
3182 Type *FTy = flattenPointerTypes(FullFTy);
3184 return error("Invalid record");
3185 if (isa<PointerType>(FTy))
3186 std::tie(FullFTy, FTy) = getPointerElementTypes(FullFTy);
3188 if (!isa<FunctionType>(FTy))
3189 return error("Invalid type for value");
3190 auto CC = static_cast<CallingConv::ID>(Record[1]);
3191 if (CC & ~CallingConv::MaxID)
3192 return error("Invalid calling convention ID");
3194 unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3195 if (Record.size() > 16)
3196 AddrSpace = Record[16];
3199 Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
3200 AddrSpace, Name, TheModule);
3202 assert(Func->getFunctionType() == flattenPointerTypes(FullFTy) &&
3203 "Incorrect fully specified type provided for function");
3204 FunctionTypes[Func] = cast<FunctionType>(FullFTy);
3206 Func->setCallingConv(CC);
3207 bool isProto = Record[2];
3208 uint64_t RawLinkage = Record[3];
3209 Func->setLinkage(getDecodedLinkage(RawLinkage));
3210 Func->setAttributes(getAttributes(Record[4]));
3212 // Upgrade any old-style byval without a type by propagating the argument's
3213 // pointee type. There should be no opaque pointers where the byval type is
3215 for (unsigned i = 0; i != Func->arg_size(); ++i) {
3216 if (!Func->hasParamAttribute(i, Attribute::ByVal))
3219 Type *PTy = cast<FunctionType>(FullFTy)->getParamType(i);
3220 Func->removeParamAttr(i, Attribute::ByVal);
3221 Func->addParamAttr(i, Attribute::getWithByValType(
3222 Context, getPointerElementFlatType(PTy)));
3226 if (Error Err = parseAlignmentValue(Record[5], Alignment))
3228 Func->setAlignment(Alignment);
3230 if (Record[6] - 1 >= SectionTable.size())
3231 return error("Invalid ID");
3232 Func->setSection(SectionTable[Record[6] - 1]);
3234 // Local linkage must have default visibility.
3235 if (!Func->hasLocalLinkage())
3236 // FIXME: Change to an error if non-default in 4.0.
3237 Func->setVisibility(getDecodedVisibility(Record[7]));
3238 if (Record.size() > 8 && Record[8]) {
3239 if (Record[8] - 1 >= GCTable.size())
3240 return error("Invalid ID");
3241 Func->setGC(GCTable[Record[8] - 1]);
3243 GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3244 if (Record.size() > 9)
3245 UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3246 Func->setUnnamedAddr(UnnamedAddr);
3247 if (Record.size() > 10 && Record[10] != 0)
3248 FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
3250 if (Record.size() > 11)
3251 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3253 upgradeDLLImportExportLinkage(Func, RawLinkage);
3255 if (Record.size() > 12) {
3256 if (unsigned ComdatID = Record[12]) {
3257 if (ComdatID > ComdatList.size())
3258 return error("Invalid function comdat ID");
3259 Func->setComdat(ComdatList[ComdatID - 1]);
3261 } else if (hasImplicitComdat(RawLinkage)) {
3262 Func->setComdat(reinterpret_cast<Comdat *>(1));
3265 if (Record.size() > 13 && Record[13] != 0)
3266 FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
3268 if (Record.size() > 14 && Record[14] != 0)
3269 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3271 if (Record.size() > 15) {
3272 Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3274 inferDSOLocal(Func);
3276 // Record[16] is the address space number.
3278 // Check whether we have enough values to read a partition name.
3279 if (Record.size() > 18)
3280 Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3282 Type *FullTy = PointerType::get(FullFTy, AddrSpace);
3283 assert(Func->getType() == flattenPointerTypes(FullTy) &&
3284 "Incorrect fully specified type provided for Function");
3285 ValueList.push_back(Func, FullTy);
3287 // If this is a function with a body, remember the prototype we are
3288 // creating now, so that we can match up the body with them later.
3290 Func->setIsMaterializable(true);
3291 FunctionsWithBodies.push_back(Func);
3292 DeferredFunctionInfo[Func] = 0;
3294 return Error::success();
3297 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3298 unsigned BitCode, ArrayRef<uint64_t> Record) {
3299 // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3300 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3301 // dllstorageclass, threadlocal, unnamed_addr,
3302 // preemption specifier] (name in VST)
3303 // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3304 // visibility, dllstorageclass, threadlocal, unnamed_addr,
3305 // preemption specifier] (name in VST)
3306 // v2: [strtab_offset, strtab_size, v1]
3308 std::tie(Name, Record) = readNameFromStrtab(Record);
3310 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3311 if (Record.size() < (3 + (unsigned)NewRecord))
3312 return error("Invalid record");
3314 Type *FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
3315 Type *Ty = flattenPointerTypes(FullTy);
3317 return error("Invalid record");
3321 auto *PTy = dyn_cast<PointerType>(Ty);
3323 return error("Invalid type for value");
3324 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
3325 AddrSpace = PTy->getAddressSpace();
3327 AddrSpace = Record[OpNum++];
3330 auto Val = Record[OpNum++];
3331 auto Linkage = Record[OpNum++];
3332 GlobalIndirectSymbol *NewGA;
3333 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3334 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3335 NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3338 NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3339 nullptr, TheModule);
3341 assert(NewGA->getValueType() == flattenPointerTypes(FullTy) &&
3342 "Incorrect fully structured type provided for GlobalIndirectSymbol");
3343 // Old bitcode files didn't have visibility field.
3344 // Local linkage must have default visibility.
3345 if (OpNum != Record.size()) {
3346 auto VisInd = OpNum++;
3347 if (!NewGA->hasLocalLinkage())
3348 // FIXME: Change to an error if non-default in 4.0.
3349 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3351 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3352 BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
3353 if (OpNum != Record.size())
3354 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3356 upgradeDLLImportExportLinkage(NewGA, Linkage);
3357 if (OpNum != Record.size())
3358 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3359 if (OpNum != Record.size())
3360 NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3362 if (OpNum != Record.size())
3363 NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3364 inferDSOLocal(NewGA);
3366 // Check whether we have enough values to read a partition name.
3367 if (OpNum + 1 < Record.size()) {
3368 NewGA->setPartition(
3369 StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
3373 FullTy = PointerType::get(FullTy, AddrSpace);
3374 assert(NewGA->getType() == flattenPointerTypes(FullTy) &&
3375 "Incorrect fully structured type provided for GlobalIndirectSymbol");
3376 ValueList.push_back(NewGA, FullTy);
3377 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3378 return Error::success();
3381 Error BitcodeReader::parseModule(uint64_t ResumeBit,
3382 bool ShouldLazyLoadMetadata) {
3384 if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
3386 } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3389 SmallVector<uint64_t, 64> Record;
3391 // Read all the records for this module.
3393 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3395 return MaybeEntry.takeError();
3396 llvm::BitstreamEntry Entry = MaybeEntry.get();
3398 switch (Entry.Kind) {
3399 case BitstreamEntry::Error:
3400 return error("Malformed block");
3401 case BitstreamEntry::EndBlock:
3402 return globalCleanup();
3404 case BitstreamEntry::SubBlock:
3406 default: // Skip unknown content.
3407 if (Error Err = Stream.SkipBlock())
3410 case bitc::BLOCKINFO_BLOCK_ID:
3411 if (readBlockInfo())
3412 return error("Malformed block");
3414 case bitc::PARAMATTR_BLOCK_ID:
3415 if (Error Err = parseAttributeBlock())
3418 case bitc::PARAMATTR_GROUP_BLOCK_ID:
3419 if (Error Err = parseAttributeGroupBlock())
3422 case bitc::TYPE_BLOCK_ID_NEW:
3423 if (Error Err = parseTypeTable())
3426 case bitc::VALUE_SYMTAB_BLOCK_ID:
3427 if (!SeenValueSymbolTable) {
3428 // Either this is an old form VST without function index and an
3429 // associated VST forward declaration record (which would have caused
3430 // the VST to be jumped to and parsed before it was encountered
3431 // normally in the stream), or there were no function blocks to
3432 // trigger an earlier parsing of the VST.
3433 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3434 if (Error Err = parseValueSymbolTable())
3436 SeenValueSymbolTable = true;
3438 // We must have had a VST forward declaration record, which caused
3439 // the parser to jump to and parse the VST earlier.
3440 assert(VSTOffset > 0);
3441 if (Error Err = Stream.SkipBlock())
3445 case bitc::CONSTANTS_BLOCK_ID:
3446 if (Error Err = parseConstants())
3448 if (Error Err = resolveGlobalAndIndirectSymbolInits())
3451 case bitc::METADATA_BLOCK_ID:
3452 if (ShouldLazyLoadMetadata) {
3453 if (Error Err = rememberAndSkipMetadata())
3457 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3458 if (Error Err = MDLoader->parseModuleMetadata())
3461 case bitc::METADATA_KIND_BLOCK_ID:
3462 if (Error Err = MDLoader->parseMetadataKinds())
3465 case bitc::FUNCTION_BLOCK_ID:
3466 // If this is the first function body we've seen, reverse the
3467 // FunctionsWithBodies list.
3468 if (!SeenFirstFunctionBody) {
3469 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3470 if (Error Err = globalCleanup())
3472 SeenFirstFunctionBody = true;
3475 if (VSTOffset > 0) {
3476 // If we have a VST forward declaration record, make sure we
3477 // parse the VST now if we haven't already. It is needed to
3478 // set up the DeferredFunctionInfo vector for lazy reading.
3479 if (!SeenValueSymbolTable) {
3480 if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3482 SeenValueSymbolTable = true;
3483 // Fall through so that we record the NextUnreadBit below.
3484 // This is necessary in case we have an anonymous function that
3485 // is later materialized. Since it will not have a VST entry we
3486 // need to fall back to the lazy parse to find its offset.
3488 // If we have a VST forward declaration record, but have already
3489 // parsed the VST (just above, when the first function body was
3490 // encountered here), then we are resuming the parse after
3491 // materializing functions. The ResumeBit points to the
3492 // start of the last function block recorded in the
3493 // DeferredFunctionInfo map. Skip it.
3494 if (Error Err = Stream.SkipBlock())
3500 // Support older bitcode files that did not have the function
3501 // index in the VST, nor a VST forward declaration record, as
3502 // well as anonymous functions that do not have VST entries.
3503 // Build the DeferredFunctionInfo vector on the fly.
3504 if (Error Err = rememberAndSkipFunctionBody())
3507 // Suspend parsing when we reach the function bodies. Subsequent
3508 // materialization calls will resume it when necessary. If the bitcode
3509 // file is old, the symbol table will be at the end instead and will not
3510 // have been seen yet. In this case, just finish the parse now.
3511 if (SeenValueSymbolTable) {
3512 NextUnreadBit = Stream.GetCurrentBitNo();
3513 // After the VST has been parsed, we need to make sure intrinsic name
3514 // are auto-upgraded.
3515 return globalCleanup();
3518 case bitc::USELIST_BLOCK_ID:
3519 if (Error Err = parseUseLists())
3522 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3523 if (Error Err = parseOperandBundleTags())
3526 case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3527 if (Error Err = parseSyncScopeNames())
3533 case BitstreamEntry::Record:
3534 // The interesting case.
3539 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3541 return MaybeBitCode.takeError();
3542 switch (unsigned BitCode = MaybeBitCode.get()) {
3543 default: break; // Default behavior, ignore unknown content.
3544 case bitc::MODULE_CODE_VERSION: {
3545 Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3547 return VersionOrErr.takeError();
3548 UseRelativeIDs = *VersionOrErr >= 1;
3551 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3553 if (convertToString(Record, 0, S))
3554 return error("Invalid record");
3555 TheModule->setTargetTriple(S);
3558 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3560 if (convertToString(Record, 0, S))
3561 return error("Invalid record");
3562 TheModule->setDataLayout(S);
3565 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3567 if (convertToString(Record, 0, S))
3568 return error("Invalid record");
3569 TheModule->setModuleInlineAsm(S);
3572 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3573 // FIXME: Remove in 4.0.
3575 if (convertToString(Record, 0, S))
3576 return error("Invalid record");
3580 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3582 if (convertToString(Record, 0, S))
3583 return error("Invalid record");
3584 SectionTable.push_back(S);
3587 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3589 if (convertToString(Record, 0, S))
3590 return error("Invalid record");
3591 GCTable.push_back(S);
3594 case bitc::MODULE_CODE_COMDAT:
3595 if (Error Err = parseComdatRecord(Record))
3598 case bitc::MODULE_CODE_GLOBALVAR:
3599 if (Error Err = parseGlobalVarRecord(Record))
3602 case bitc::MODULE_CODE_FUNCTION:
3603 if (Error Err = parseFunctionRecord(Record))
3606 case bitc::MODULE_CODE_IFUNC:
3607 case bitc::MODULE_CODE_ALIAS:
3608 case bitc::MODULE_CODE_ALIAS_OLD:
3609 if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3612 /// MODULE_CODE_VSTOFFSET: [offset]
3613 case bitc::MODULE_CODE_VSTOFFSET:
3614 if (Record.size() < 1)
3615 return error("Invalid record");
3616 // Note that we subtract 1 here because the offset is relative to one word
3617 // before the start of the identification or module block, which was
3618 // historically always the start of the regular bitcode header.
3619 VSTOffset = Record[0] - 1;
3621 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3622 case bitc::MODULE_CODE_SOURCE_FILENAME:
3623 SmallString<128> ValueName;
3624 if (convertToString(Record, 0, ValueName))
3625 return error("Invalid record");
3626 TheModule->setSourceFileName(ValueName);
3633 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3636 MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3637 [&](unsigned ID) { return getTypeByID(ID); });
3638 return parseModule(0, ShouldLazyLoadMetadata);
3641 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3642 if (!isa<PointerType>(PtrType))
3643 return error("Load/Store operand is not a pointer type");
3644 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3646 if (ValType && ValType != ElemType)
3647 return error("Explicit load/store type does not match pointee "
3648 "type of pointer operand");
3649 if (!PointerType::isLoadableOrStorableType(ElemType))
3650 return error("Cannot load/store from pointer");
3651 return Error::success();
3654 void BitcodeReader::propagateByValTypes(CallBase *CB,
3655 ArrayRef<Type *> ArgsFullTys) {
3656 for (unsigned i = 0; i != CB->arg_size(); ++i) {
3657 if (!CB->paramHasAttr(i, Attribute::ByVal))
3660 CB->removeParamAttr(i, Attribute::ByVal);
3662 i, Attribute::getWithByValType(
3663 Context, getPointerElementFlatType(ArgsFullTys[i])));
3667 /// Lazily parse the specified function body block.
3668 Error BitcodeReader::parseFunctionBody(Function *F) {
3669 if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3672 // Unexpected unresolved metadata when parsing function.
3673 if (MDLoader->hasFwdRefs())
3674 return error("Invalid function metadata: incoming forward references");
3676 InstructionList.clear();
3677 unsigned ModuleValueListSize = ValueList.size();
3678 unsigned ModuleMDLoaderSize = MDLoader->size();
3680 // Add all the function arguments to the value table.
3682 FunctionType *FullFTy = FunctionTypes[F];
3683 for (Argument &I : F->args()) {
3684 assert(I.getType() == flattenPointerTypes(FullFTy->getParamType(ArgNo)) &&
3685 "Incorrect fully specified type for Function Argument");
3686 ValueList.push_back(&I, FullFTy->getParamType(ArgNo++));
3688 unsigned NextValueNo = ValueList.size();
3689 BasicBlock *CurBB = nullptr;
3690 unsigned CurBBNo = 0;
3693 auto getLastInstruction = [&]() -> Instruction * {
3694 if (CurBB && !CurBB->empty())
3695 return &CurBB->back();
3696 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3697 !FunctionBBs[CurBBNo - 1]->empty())
3698 return &FunctionBBs[CurBBNo - 1]->back();
3702 std::vector<OperandBundleDef> OperandBundles;
3704 // Read all the records.
3705 SmallVector<uint64_t, 64> Record;
3708 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3710 return MaybeEntry.takeError();
3711 llvm::BitstreamEntry Entry = MaybeEntry.get();
3713 switch (Entry.Kind) {
3714 case BitstreamEntry::Error:
3715 return error("Malformed block");
3716 case BitstreamEntry::EndBlock:
3717 goto OutOfRecordLoop;
3719 case BitstreamEntry::SubBlock:
3721 default: // Skip unknown content.
3722 if (Error Err = Stream.SkipBlock())
3725 case bitc::CONSTANTS_BLOCK_ID:
3726 if (Error Err = parseConstants())
3728 NextValueNo = ValueList.size();
3730 case bitc::VALUE_SYMTAB_BLOCK_ID:
3731 if (Error Err = parseValueSymbolTable())
3734 case bitc::METADATA_ATTACHMENT_ID:
3735 if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3738 case bitc::METADATA_BLOCK_ID:
3739 assert(DeferredMetadataInfo.empty() &&
3740 "Must read all module-level metadata before function-level");
3741 if (Error Err = MDLoader->parseFunctionMetadata())
3744 case bitc::USELIST_BLOCK_ID:
3745 if (Error Err = parseUseLists())
3751 case BitstreamEntry::Record:
3752 // The interesting case.
3758 Instruction *I = nullptr;
3759 Type *FullTy = nullptr;
3760 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3762 return MaybeBitCode.takeError();
3763 switch (unsigned BitCode = MaybeBitCode.get()) {
3764 default: // Default behavior: reject
3765 return error("Invalid value");
3766 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3767 if (Record.size() < 1 || Record[0] == 0)
3768 return error("Invalid record");
3769 // Create all the basic blocks for the function.
3770 FunctionBBs.resize(Record[0]);
3772 // See if anything took the address of blocks in this function.
3773 auto BBFRI = BasicBlockFwdRefs.find(F);
3774 if (BBFRI == BasicBlockFwdRefs.end()) {
3775 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3776 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3778 auto &BBRefs = BBFRI->second;
3779 // Check for invalid basic block references.
3780 if (BBRefs.size() > FunctionBBs.size())
3781 return error("Invalid ID");
3782 assert(!BBRefs.empty() && "Unexpected empty array");
3783 assert(!BBRefs.front() && "Invalid reference to entry block");
3784 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3786 if (I < RE && BBRefs[I]) {
3787 BBRefs[I]->insertInto(F);
3788 FunctionBBs[I] = BBRefs[I];
3790 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3793 // Erase from the table.
3794 BasicBlockFwdRefs.erase(BBFRI);
3797 CurBB = FunctionBBs[0];
3801 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3802 // This record indicates that the last instruction is at the same
3803 // location as the previous instruction with a location.
3804 I = getLastInstruction();
3807 return error("Invalid record");
3808 I->setDebugLoc(LastLoc);
3812 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3813 I = getLastInstruction();
3814 if (!I || Record.size() < 4)
3815 return error("Invalid record");
3817 unsigned Line = Record[0], Col = Record[1];
3818 unsigned ScopeID = Record[2], IAID = Record[3];
3819 bool isImplicitCode = Record.size() == 5 && Record[4];
3821 MDNode *Scope = nullptr, *IA = nullptr;
3823 Scope = dyn_cast_or_null<MDNode>(
3824 MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
3826 return error("Invalid record");
3829 IA = dyn_cast_or_null<MDNode>(
3830 MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
3832 return error("Invalid record");
3834 LastLoc = DebugLoc::get(Line, Col, Scope, IA, isImplicitCode);
3835 I->setDebugLoc(LastLoc);
3839 case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
3842 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3843 OpNum+1 > Record.size())
3844 return error("Invalid record");
3846 int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
3848 return error("Invalid record");
3849 I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
3850 InstructionList.push_back(I);
3851 if (OpNum < Record.size()) {
3852 if (isa<FPMathOperator>(I)) {
3853 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3855 I->setFastMathFlags(FMF);
3860 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3863 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3864 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3865 OpNum+1 > Record.size())
3866 return error("Invalid record");
3868 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3870 return error("Invalid record");
3871 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3872 InstructionList.push_back(I);
3873 if (OpNum < Record.size()) {
3874 if (Opc == Instruction::Add ||
3875 Opc == Instruction::Sub ||
3876 Opc == Instruction::Mul ||
3877 Opc == Instruction::Shl) {
3878 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3879 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3880 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3881 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3882 } else if (Opc == Instruction::SDiv ||
3883 Opc == Instruction::UDiv ||
3884 Opc == Instruction::LShr ||
3885 Opc == Instruction::AShr) {
3886 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3887 cast<BinaryOperator>(I)->setIsExact(true);
3888 } else if (isa<FPMathOperator>(I)) {
3889 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3891 I->setFastMathFlags(FMF);
3897 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3900 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3901 OpNum+2 != Record.size())
3902 return error("Invalid record");
3904 FullTy = getFullyStructuredTypeByID(Record[OpNum]);
3905 Type *ResTy = flattenPointerTypes(FullTy);
3906 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3907 if (Opc == -1 || !ResTy)
3908 return error("Invalid record");
3909 Instruction *Temp = nullptr;
3910 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3912 InstructionList.push_back(Temp);
3913 CurBB->getInstList().push_back(Temp);
3916 auto CastOp = (Instruction::CastOps)Opc;
3917 if (!CastInst::castIsValid(CastOp, Op, ResTy))
3918 return error("Invalid cast");
3919 I = CastInst::Create(CastOp, Op, ResTy);
3921 InstructionList.push_back(I);
3924 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3925 case bitc::FUNC_CODE_INST_GEP_OLD:
3926 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3932 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3933 InBounds = Record[OpNum++];
3934 FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
3935 Ty = flattenPointerTypes(FullTy);
3937 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3942 Type *FullBaseTy = nullptr;
3943 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, &FullBaseTy))
3944 return error("Invalid record");
3947 std::tie(FullTy, Ty) =
3948 getPointerElementTypes(FullBaseTy->getScalarType());
3949 } else if (Ty != getPointerElementFlatType(FullBaseTy->getScalarType()))
3951 "Explicit gep type does not match pointee type of pointer operand");
3953 SmallVector<Value*, 16> GEPIdx;
3954 while (OpNum != Record.size()) {
3956 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3957 return error("Invalid record");
3958 GEPIdx.push_back(Op);
3961 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3962 FullTy = GetElementPtrInst::getGEPReturnType(FullTy, I, GEPIdx);
3964 InstructionList.push_back(I);
3966 cast<GetElementPtrInst>(I)->setIsInBounds(true);
3970 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3971 // EXTRACTVAL: [opty, opval, n x indices]
3974 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy))
3975 return error("Invalid record");
3977 unsigned RecSize = Record.size();
3978 if (OpNum == RecSize)
3979 return error("EXTRACTVAL: Invalid instruction with 0 indices");
3981 SmallVector<unsigned, 4> EXTRACTVALIdx;
3982 for (; OpNum != RecSize; ++OpNum) {
3983 bool IsArray = FullTy->isArrayTy();
3984 bool IsStruct = FullTy->isStructTy();
3985 uint64_t Index = Record[OpNum];
3987 if (!IsStruct && !IsArray)
3988 return error("EXTRACTVAL: Invalid type");
3989 if ((unsigned)Index != Index)
3990 return error("Invalid value");
3991 if (IsStruct && Index >= FullTy->getStructNumElements())
3992 return error("EXTRACTVAL: Invalid struct index");
3993 if (IsArray && Index >= FullTy->getArrayNumElements())
3994 return error("EXTRACTVAL: Invalid array index");
3995 EXTRACTVALIdx.push_back((unsigned)Index);
3998 FullTy = FullTy->getStructElementType(Index);
4000 FullTy = FullTy->getArrayElementType();
4003 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4004 InstructionList.push_back(I);
4008 case bitc::FUNC_CODE_INST_INSERTVAL: {
4009 // INSERTVAL: [opty, opval, opty, opval, n x indices]
4012 if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy))
4013 return error("Invalid record");
4015 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4016 return error("Invalid record");
4018 unsigned RecSize = Record.size();
4019 if (OpNum == RecSize)
4020 return error("INSERTVAL: Invalid instruction with 0 indices");
4022 SmallVector<unsigned, 4> INSERTVALIdx;
4023 Type *CurTy = Agg->getType();
4024 for (; OpNum != RecSize; ++OpNum) {
4025 bool IsArray = CurTy->isArrayTy();
4026 bool IsStruct = CurTy->isStructTy();
4027 uint64_t Index = Record[OpNum];
4029 if (!IsStruct && !IsArray)
4030 return error("INSERTVAL: Invalid type");
4031 if ((unsigned)Index != Index)
4032 return error("Invalid value");
4033 if (IsStruct && Index >= CurTy->getStructNumElements())
4034 return error("INSERTVAL: Invalid struct index");
4035 if (IsArray && Index >= CurTy->getArrayNumElements())
4036 return error("INSERTVAL: Invalid array index");
4038 INSERTVALIdx.push_back((unsigned)Index);
4040 CurTy = CurTy->getStructElementType(Index);
4042 CurTy = CurTy->getArrayElementType();
4045 if (CurTy != Val->getType())
4046 return error("Inserted value type doesn't match aggregate type");
4048 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4049 InstructionList.push_back(I);
4053 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4054 // obsolete form of select
4055 // handles select i1 ... in old bitcode
4057 Value *TrueVal, *FalseVal, *Cond;
4058 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) ||
4059 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4060 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4061 return error("Invalid record");
4063 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4064 InstructionList.push_back(I);
4068 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4069 // new form of select
4070 // handles select i1 or select [N x i1]
4072 Value *TrueVal, *FalseVal, *Cond;
4073 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) ||
4074 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4075 getValueTypePair(Record, OpNum, NextValueNo, Cond))
4076 return error("Invalid record");
4078 // select condition can be either i1 or [N x i1]
4079 if (VectorType* vector_type =
4080 dyn_cast<VectorType>(Cond->getType())) {
4082 if (vector_type->getElementType() != Type::getInt1Ty(Context))
4083 return error("Invalid type for value");
4086 if (Cond->getType() != Type::getInt1Ty(Context))
4087 return error("Invalid type for value");
4090 I = SelectInst::Create(Cond, TrueVal, FalseVal);
4091 InstructionList.push_back(I);
4092 if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
4093 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4095 I->setFastMathFlags(FMF);
4100 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4103 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy) ||
4104 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4105 return error("Invalid record");
4106 if (!Vec->getType()->isVectorTy())
4107 return error("Invalid type for value");
4108 I = ExtractElementInst::Create(Vec, Idx);
4109 FullTy = FullTy->getVectorElementType();
4110 InstructionList.push_back(I);
4114 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4116 Value *Vec, *Elt, *Idx;
4117 if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy))
4118 return error("Invalid record");
4119 if (!Vec->getType()->isVectorTy())
4120 return error("Invalid type for value");
4121 if (popValue(Record, OpNum, NextValueNo,
4122 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4123 getValueTypePair(Record, OpNum, NextValueNo, Idx))
4124 return error("Invalid record");
4125 I = InsertElementInst::Create(Vec, Elt, Idx);
4126 InstructionList.push_back(I);
4130 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4132 Value *Vec1, *Vec2, *Mask;
4133 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, &FullTy) ||
4134 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4135 return error("Invalid record");
4137 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4138 return error("Invalid record");
4139 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4140 return error("Invalid type for value");
4141 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4142 FullTy = VectorType::get(FullTy->getVectorElementType(),
4143 Mask->getType()->getVectorNumElements());
4144 InstructionList.push_back(I);
4148 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4149 // Old form of ICmp/FCmp returning bool
4150 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4151 // both legal on vectors but had different behaviour.
4152 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4153 // FCmp/ICmp returning bool or vector of bool
4157 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4158 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4159 return error("Invalid record");
4161 unsigned PredVal = Record[OpNum];
4162 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4164 if (IsFP && Record.size() > OpNum+1)
4165 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4167 if (OpNum+1 != Record.size())
4168 return error("Invalid record");
4170 if (LHS->getType()->isFPOrFPVectorTy())
4171 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4173 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4176 I->setFastMathFlags(FMF);
4177 InstructionList.push_back(I);
4181 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4183 unsigned Size = Record.size();
4185 I = ReturnInst::Create(Context);
4186 InstructionList.push_back(I);
4191 Value *Op = nullptr;
4192 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4193 return error("Invalid record");
4194 if (OpNum != Record.size())
4195 return error("Invalid record");
4197 I = ReturnInst::Create(Context, Op);
4198 InstructionList.push_back(I);
4201 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4202 if (Record.size() != 1 && Record.size() != 3)
4203 return error("Invalid record");
4204 BasicBlock *TrueDest = getBasicBlock(Record[0]);
4206 return error("Invalid record");
4208 if (Record.size() == 1) {
4209 I = BranchInst::Create(TrueDest);
4210 InstructionList.push_back(I);
4213 BasicBlock *FalseDest = getBasicBlock(Record[1]);
4214 Value *Cond = getValue(Record, 2, NextValueNo,
4215 Type::getInt1Ty(Context));
4216 if (!FalseDest || !Cond)
4217 return error("Invalid record");
4218 I = BranchInst::Create(TrueDest, FalseDest, Cond);
4219 InstructionList.push_back(I);
4223 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4224 if (Record.size() != 1 && Record.size() != 2)
4225 return error("Invalid record");
4228 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4230 return error("Invalid record");
4231 BasicBlock *UnwindDest = nullptr;
4232 if (Record.size() == 2) {
4233 UnwindDest = getBasicBlock(Record[Idx++]);
4235 return error("Invalid record");
4238 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4239 InstructionList.push_back(I);
4242 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4243 if (Record.size() != 2)
4244 return error("Invalid record");
4247 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4249 return error("Invalid record");
4250 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4252 return error("Invalid record");
4254 I = CatchReturnInst::Create(CatchPad, BB);
4255 InstructionList.push_back(I);
4258 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4259 // We must have, at minimum, the outer scope and the number of arguments.
4260 if (Record.size() < 2)
4261 return error("Invalid record");
4266 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4268 unsigned NumHandlers = Record[Idx++];
4270 SmallVector<BasicBlock *, 2> Handlers;
4271 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4272 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4274 return error("Invalid record");
4275 Handlers.push_back(BB);
4278 BasicBlock *UnwindDest = nullptr;
4279 if (Idx + 1 == Record.size()) {
4280 UnwindDest = getBasicBlock(Record[Idx++]);
4282 return error("Invalid record");
4285 if (Record.size() != Idx)
4286 return error("Invalid record");
4289 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4290 for (BasicBlock *Handler : Handlers)
4291 CatchSwitch->addHandler(Handler);
4293 InstructionList.push_back(I);
4296 case bitc::FUNC_CODE_INST_CATCHPAD:
4297 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4298 // We must have, at minimum, the outer scope and the number of arguments.
4299 if (Record.size() < 2)
4300 return error("Invalid record");
4305 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4307 unsigned NumArgOperands = Record[Idx++];
4309 SmallVector<Value *, 2> Args;
4310 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4312 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4313 return error("Invalid record");
4314 Args.push_back(Val);
4317 if (Record.size() != Idx)
4318 return error("Invalid record");
4320 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4321 I = CleanupPadInst::Create(ParentPad, Args);
4323 I = CatchPadInst::Create(ParentPad, Args);
4324 InstructionList.push_back(I);
4327 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4329 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4330 // "New" SwitchInst format with case ranges. The changes to write this
4331 // format were reverted but we still recognize bitcode that uses it.
4332 // Hopefully someday we will have support for case ranges and can use
4333 // this format again.
4335 Type *OpTy = getTypeByID(Record[1]);
4336 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4338 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4339 BasicBlock *Default = getBasicBlock(Record[3]);
4340 if (!OpTy || !Cond || !Default)
4341 return error("Invalid record");
4343 unsigned NumCases = Record[4];
4345 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4346 InstructionList.push_back(SI);
4348 unsigned CurIdx = 5;
4349 for (unsigned i = 0; i != NumCases; ++i) {
4350 SmallVector<ConstantInt*, 1> CaseVals;
4351 unsigned NumItems = Record[CurIdx++];
4352 for (unsigned ci = 0; ci != NumItems; ++ci) {
4353 bool isSingleNumber = Record[CurIdx++];
4356 unsigned ActiveWords = 1;
4357 if (ValueBitWidth > 64)
4358 ActiveWords = Record[CurIdx++];
4359 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4361 CurIdx += ActiveWords;
4363 if (!isSingleNumber) {
4365 if (ValueBitWidth > 64)
4366 ActiveWords = Record[CurIdx++];
4367 APInt High = readWideAPInt(
4368 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4369 CurIdx += ActiveWords;
4371 // FIXME: It is not clear whether values in the range should be
4372 // compared as signed or unsigned values. The partially
4373 // implemented changes that used this format in the past used
4374 // unsigned comparisons.
4375 for ( ; Low.ule(High); ++Low)
4376 CaseVals.push_back(ConstantInt::get(Context, Low));
4378 CaseVals.push_back(ConstantInt::get(Context, Low));
4380 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4381 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4382 cve = CaseVals.end(); cvi != cve; ++cvi)
4383 SI->addCase(*cvi, DestBB);
4389 // Old SwitchInst format without case ranges.
4391 if (Record.size() < 3 || (Record.size() & 1) == 0)
4392 return error("Invalid record");
4393 Type *OpTy = getTypeByID(Record[0]);
4394 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4395 BasicBlock *Default = getBasicBlock(Record[2]);
4396 if (!OpTy || !Cond || !Default)
4397 return error("Invalid record");
4398 unsigned NumCases = (Record.size()-3)/2;
4399 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4400 InstructionList.push_back(SI);
4401 for (unsigned i = 0, e = NumCases; i != e; ++i) {
4402 ConstantInt *CaseVal =
4403 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4404 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4405 if (!CaseVal || !DestBB) {
4407 return error("Invalid record");
4409 SI->addCase(CaseVal, DestBB);
4414 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4415 if (Record.size() < 2)
4416 return error("Invalid record");
4417 Type *OpTy = getTypeByID(Record[0]);
4418 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4419 if (!OpTy || !Address)
4420 return error("Invalid record");
4421 unsigned NumDests = Record.size()-2;
4422 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4423 InstructionList.push_back(IBI);
4424 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4425 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4426 IBI->addDestination(DestBB);
4429 return error("Invalid record");
4436 case bitc::FUNC_CODE_INST_INVOKE: {
4437 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4438 if (Record.size() < 4)
4439 return error("Invalid record");
4441 AttributeList PAL = getAttributes(Record[OpNum++]);
4442 unsigned CCInfo = Record[OpNum++];
4443 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4444 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4446 FunctionType *FTy = nullptr;
4447 FunctionType *FullFTy = nullptr;
4448 if ((CCInfo >> 13) & 1) {
4450 dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
4452 return error("Explicit invoke type is not a function type");
4453 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4457 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
4458 return error("Invalid record");
4460 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4462 return error("Callee is not a pointer");
4465 dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
4467 return error("Callee is not of pointer to function type");
4468 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4469 } else if (getPointerElementFlatType(FullTy) != FTy)
4470 return error("Explicit invoke type does not match pointee type of "
4472 if (Record.size() < FTy->getNumParams() + OpNum)
4473 return error("Insufficient operands to call");
4475 SmallVector<Value*, 16> Ops;
4476 SmallVector<Type *, 16> ArgsFullTys;
4477 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4478 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4479 FTy->getParamType(i)));
4480 ArgsFullTys.push_back(FullFTy->getParamType(i));
4482 return error("Invalid record");
4485 if (!FTy->isVarArg()) {
4486 if (Record.size() != OpNum)
4487 return error("Invalid record");
4489 // Read type/value pairs for varargs params.
4490 while (OpNum != Record.size()) {
4493 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
4494 return error("Invalid record");
4496 ArgsFullTys.push_back(FullTy);
4500 I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
4502 FullTy = FullFTy->getReturnType();
4503 OperandBundles.clear();
4504 InstructionList.push_back(I);
4505 cast<InvokeInst>(I)->setCallingConv(
4506 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4507 cast<InvokeInst>(I)->setAttributes(PAL);
4508 propagateByValTypes(cast<CallBase>(I), ArgsFullTys);
4512 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4514 Value *Val = nullptr;
4515 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4516 return error("Invalid record");
4517 I = ResumeInst::Create(Val);
4518 InstructionList.push_back(I);
4521 case bitc::FUNC_CODE_INST_CALLBR: {
4522 // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
4524 AttributeList PAL = getAttributes(Record[OpNum++]);
4525 unsigned CCInfo = Record[OpNum++];
4527 BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
4528 unsigned NumIndirectDests = Record[OpNum++];
4529 SmallVector<BasicBlock *, 16> IndirectDests;
4530 for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
4531 IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
4533 FunctionType *FTy = nullptr;
4534 FunctionType *FullFTy = nullptr;
4535 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
4537 dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
4539 return error("Explicit call type is not a function type");
4540 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4544 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
4545 return error("Invalid record");
4547 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4549 return error("Callee is not a pointer type");
4552 dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
4554 return error("Callee is not of pointer to function type");
4555 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4556 } else if (getPointerElementFlatType(FullTy) != FTy)
4557 return error("Explicit call type does not match pointee type of "
4559 if (Record.size() < FTy->getNumParams() + OpNum)
4560 return error("Insufficient operands to call");
4562 SmallVector<Value*, 16> Args;
4563 // Read the fixed params.
4564 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4565 if (FTy->getParamType(i)->isLabelTy())
4566 Args.push_back(getBasicBlock(Record[OpNum]));
4568 Args.push_back(getValue(Record, OpNum, NextValueNo,
4569 FTy->getParamType(i)));
4571 return error("Invalid record");
4574 // Read type/value pairs for varargs params.
4575 if (!FTy->isVarArg()) {
4576 if (OpNum != Record.size())
4577 return error("Invalid record");
4579 while (OpNum != Record.size()) {
4581 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4582 return error("Invalid record");
4587 I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
4589 FullTy = FullFTy->getReturnType();
4590 OperandBundles.clear();
4591 InstructionList.push_back(I);
4592 cast<CallBrInst>(I)->setCallingConv(
4593 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4594 cast<CallBrInst>(I)->setAttributes(PAL);
4597 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4598 I = new UnreachableInst(Context);
4599 InstructionList.push_back(I);
4601 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4602 if (Record.size() < 1 || ((Record.size()-1)&1))
4603 return error("Invalid record");
4604 FullTy = getFullyStructuredTypeByID(Record[0]);
4605 Type *Ty = flattenPointerTypes(FullTy);
4607 return error("Invalid record");
4609 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4610 InstructionList.push_back(PN);
4612 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4614 // With the new function encoding, it is possible that operands have
4615 // negative IDs (for forward references). Use a signed VBR
4616 // representation to keep the encoding small.
4618 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4620 V = getValue(Record, 1+i, NextValueNo, Ty);
4621 BasicBlock *BB = getBasicBlock(Record[2+i]);
4623 return error("Invalid record");
4624 PN->addIncoming(V, BB);
4630 case bitc::FUNC_CODE_INST_LANDINGPAD:
4631 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4632 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4634 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4635 if (Record.size() < 3)
4636 return error("Invalid record");
4638 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4639 if (Record.size() < 4)
4640 return error("Invalid record");
4642 FullTy = getFullyStructuredTypeByID(Record[Idx++]);
4643 Type *Ty = flattenPointerTypes(FullTy);
4645 return error("Invalid record");
4646 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4647 Value *PersFn = nullptr;
4648 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4649 return error("Invalid record");
4651 if (!F->hasPersonalityFn())
4652 F->setPersonalityFn(cast<Constant>(PersFn));
4653 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4654 return error("Personality function mismatch");
4657 bool IsCleanup = !!Record[Idx++];
4658 unsigned NumClauses = Record[Idx++];
4659 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4660 LP->setCleanup(IsCleanup);
4661 for (unsigned J = 0; J != NumClauses; ++J) {
4662 LandingPadInst::ClauseType CT =
4663 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4666 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4668 return error("Invalid record");
4671 assert((CT != LandingPadInst::Catch ||
4672 !isa<ArrayType>(Val->getType())) &&
4673 "Catch clause has a invalid type!");
4674 assert((CT != LandingPadInst::Filter ||
4675 isa<ArrayType>(Val->getType())) &&
4676 "Filter clause has invalid type!");
4677 LP->addClause(cast<Constant>(Val));
4681 InstructionList.push_back(I);
4685 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4686 if (Record.size() != 4)
4687 return error("Invalid record");
4688 uint64_t AlignRecord = Record[3];
4689 const uint64_t InAllocaMask = uint64_t(1) << 5;
4690 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4691 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4692 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4694 bool InAlloca = AlignRecord & InAllocaMask;
4695 bool SwiftError = AlignRecord & SwiftErrorMask;
4696 FullTy = getFullyStructuredTypeByID(Record[0]);
4697 Type *Ty = flattenPointerTypes(FullTy);
4698 if ((AlignRecord & ExplicitTypeMask) == 0) {
4699 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4701 return error("Old-style alloca with a non-pointer type");
4702 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
4704 Type *OpTy = getTypeByID(Record[1]);
4705 Value *Size = getFnValueByID(Record[2], OpTy);
4707 if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4711 return error("Invalid record");
4713 // FIXME: Make this an optional field.
4714 const DataLayout &DL = TheModule->getDataLayout();
4715 unsigned AS = DL.getAllocaAddrSpace();
4717 AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
4718 AI->setUsedWithInAlloca(InAlloca);
4719 AI->setSwiftError(SwiftError);
4721 FullTy = PointerType::get(FullTy, AS);
4722 InstructionList.push_back(I);
4725 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4728 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) ||
4729 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4730 return error("Invalid record");
4732 if (!isa<PointerType>(Op->getType()))
4733 return error("Load operand is not a pointer type");
4736 if (OpNum + 3 == Record.size()) {
4737 FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
4738 Ty = flattenPointerTypes(FullTy);
4740 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
4742 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4746 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4748 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4749 InstructionList.push_back(I);
4752 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4753 // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
4756 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) ||
4757 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4758 return error("Invalid record");
4760 if (!isa<PointerType>(Op->getType()))
4761 return error("Load operand is not a pointer type");
4764 if (OpNum + 5 == Record.size()) {
4765 FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
4766 Ty = flattenPointerTypes(FullTy);
4768 std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
4770 if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4773 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4774 if (Ordering == AtomicOrdering::NotAtomic ||
4775 Ordering == AtomicOrdering::Release ||
4776 Ordering == AtomicOrdering::AcquireRelease)
4777 return error("Invalid record");
4778 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4779 return error("Invalid record");
4780 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4783 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4785 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align, Ordering, SSID);
4786 InstructionList.push_back(I);
4789 case bitc::FUNC_CODE_INST_STORE:
4790 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4794 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) ||
4795 (BitCode == bitc::FUNC_CODE_INST_STORE
4796 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4797 : popValue(Record, OpNum, NextValueNo,
4798 getPointerElementFlatType(FullTy), Val)) ||
4799 OpNum + 2 != Record.size())
4800 return error("Invalid record");
4802 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4805 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4807 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4808 InstructionList.push_back(I);
4811 case bitc::FUNC_CODE_INST_STOREATOMIC:
4812 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4813 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
4817 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) ||
4818 !isa<PointerType>(Ptr->getType()) ||
4819 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4820 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4821 : popValue(Record, OpNum, NextValueNo,
4822 getPointerElementFlatType(FullTy), Val)) ||
4823 OpNum + 4 != Record.size())
4824 return error("Invalid record");
4826 if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4828 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4829 if (Ordering == AtomicOrdering::NotAtomic ||
4830 Ordering == AtomicOrdering::Acquire ||
4831 Ordering == AtomicOrdering::AcquireRelease)
4832 return error("Invalid record");
4833 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4834 if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4835 return error("Invalid record");
4838 if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4840 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
4841 InstructionList.push_back(I);
4844 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4845 case bitc::FUNC_CODE_INST_CMPXCHG: {
4846 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
4847 // failureordering?, isweak?]
4849 Value *Ptr, *Cmp, *New;
4850 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy))
4851 return error("Invalid record");
4853 if (!isa<PointerType>(Ptr->getType()))
4854 return error("Cmpxchg operand is not a pointer type");
4856 if (BitCode == bitc::FUNC_CODE_INST_CMPXCHG) {
4857 if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, &FullTy))
4858 return error("Invalid record");
4859 } else if (popValue(Record, OpNum, NextValueNo,
4860 getPointerElementFlatType(FullTy), Cmp))
4861 return error("Invalid record");
4863 FullTy = cast<PointerType>(FullTy)->getElementType();
4865 if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4866 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4867 return error("Invalid record");
4869 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4870 if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4871 SuccessOrdering == AtomicOrdering::Unordered)
4872 return error("Invalid record");
4873 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
4875 if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4877 AtomicOrdering FailureOrdering;
4878 if (Record.size() < 7)
4880 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4882 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4884 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4886 FullTy = StructType::get(Context, {FullTy, Type::getInt1Ty(Context)});
4887 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4889 if (Record.size() < 8) {
4890 // Before weak cmpxchgs existed, the instruction simply returned the
4891 // value loaded from memory, so bitcode files from that era will be
4892 // expecting the first component of a modern cmpxchg.
4893 CurBB->getInstList().push_back(I);
4894 I = ExtractValueInst::Create(I, 0);
4895 FullTy = cast<StructType>(FullTy)->getElementType(0);
4897 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4900 InstructionList.push_back(I);
4903 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4904 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
4907 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) ||
4908 !isa<PointerType>(Ptr->getType()) ||
4909 popValue(Record, OpNum, NextValueNo,
4910 getPointerElementFlatType(FullTy), Val) ||
4911 OpNum + 4 != Record.size())
4912 return error("Invalid record");
4913 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4914 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4915 Operation > AtomicRMWInst::LAST_BINOP)
4916 return error("Invalid record");
4917 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4918 if (Ordering == AtomicOrdering::NotAtomic ||
4919 Ordering == AtomicOrdering::Unordered)
4920 return error("Invalid record");
4921 SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4922 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
4923 FullTy = getPointerElementFlatType(FullTy);
4924 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4925 InstructionList.push_back(I);
4928 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
4929 if (2 != Record.size())
4930 return error("Invalid record");
4931 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4932 if (Ordering == AtomicOrdering::NotAtomic ||
4933 Ordering == AtomicOrdering::Unordered ||
4934 Ordering == AtomicOrdering::Monotonic)
4935 return error("Invalid record");
4936 SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
4937 I = new FenceInst(Context, Ordering, SSID);
4938 InstructionList.push_back(I);
4941 case bitc::FUNC_CODE_INST_CALL: {
4942 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4943 if (Record.size() < 3)
4944 return error("Invalid record");
4947 AttributeList PAL = getAttributes(Record[OpNum++]);
4948 unsigned CCInfo = Record[OpNum++];
4951 if ((CCInfo >> bitc::CALL_FMF) & 1) {
4952 FMF = getDecodedFastMathFlags(Record[OpNum++]);
4954 return error("Fast math flags indicator set for call with no FMF");
4957 FunctionType *FTy = nullptr;
4958 FunctionType *FullFTy = nullptr;
4959 if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
4961 dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
4963 return error("Explicit call type is not a function type");
4964 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4968 if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
4969 return error("Invalid record");
4971 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4973 return error("Callee is not a pointer type");
4976 dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
4978 return error("Callee is not of pointer to function type");
4979 FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4980 } else if (getPointerElementFlatType(FullTy) != FTy)
4981 return error("Explicit call type does not match pointee type of "
4983 if (Record.size() < FTy->getNumParams() + OpNum)
4984 return error("Insufficient operands to call");
4986 SmallVector<Value*, 16> Args;
4987 SmallVector<Type*, 16> ArgsFullTys;
4988 // Read the fixed params.
4989 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4990 if (FTy->getParamType(i)->isLabelTy())
4991 Args.push_back(getBasicBlock(Record[OpNum]));
4993 Args.push_back(getValue(Record, OpNum, NextValueNo,
4994 FTy->getParamType(i)));
4995 ArgsFullTys.push_back(FullFTy->getParamType(i));
4997 return error("Invalid record");
5000 // Read type/value pairs for varargs params.
5001 if (!FTy->isVarArg()) {
5002 if (OpNum != Record.size())
5003 return error("Invalid record");
5005 while (OpNum != Record.size()) {
5008 if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
5009 return error("Invalid record");
5011 ArgsFullTys.push_back(FullTy);
5015 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5016 FullTy = FullFTy->getReturnType();
5017 OperandBundles.clear();
5018 InstructionList.push_back(I);
5019 cast<CallInst>(I)->setCallingConv(
5020 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5021 CallInst::TailCallKind TCK = CallInst::TCK_None;
5022 if (CCInfo & 1 << bitc::CALL_TAIL)
5023 TCK = CallInst::TCK_Tail;
5024 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5025 TCK = CallInst::TCK_MustTail;
5026 if (CCInfo & (1 << bitc::CALL_NOTAIL))
5027 TCK = CallInst::TCK_NoTail;
5028 cast<CallInst>(I)->setTailCallKind(TCK);
5029 cast<CallInst>(I)->setAttributes(PAL);
5030 propagateByValTypes(cast<CallBase>(I), ArgsFullTys);
5032 if (!isa<FPMathOperator>(I))
5033 return error("Fast-math-flags specified for call without "
5034 "floating-point scalar or vector return type");
5035 I->setFastMathFlags(FMF);
5039 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5040 if (Record.size() < 3)
5041 return error("Invalid record");
5042 Type *OpTy = getTypeByID(Record[0]);
5043 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5044 FullTy = getFullyStructuredTypeByID(Record[2]);
5045 Type *ResTy = flattenPointerTypes(FullTy);
5046 if (!OpTy || !Op || !ResTy)
5047 return error("Invalid record");
5048 I = new VAArgInst(Op, ResTy);
5049 InstructionList.push_back(I);
5053 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5054 // A call or an invoke can be optionally prefixed with some variable
5055 // number of operand bundle blocks. These blocks are read into
5056 // OperandBundles and consumed at the next call or invoke instruction.
5058 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5059 return error("Invalid record");
5061 std::vector<Value *> Inputs;
5064 while (OpNum != Record.size()) {
5066 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5067 return error("Invalid record");
5068 Inputs.push_back(Op);
5071 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5076 // Add instruction to end of current BB. If there is no current BB, reject
5080 return error("Invalid instruction with no BB");
5082 if (!OperandBundles.empty()) {
5084 return error("Operand bundles found with no consumer");
5086 CurBB->getInstList().push_back(I);
5088 // If this was a terminator instruction, move to the next block.
5089 if (I->isTerminator()) {
5091 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5094 // Non-void values get registered in the value table for future use.
5095 if (I && !I->getType()->isVoidTy()) {
5097 FullTy = I->getType();
5099 !FullTy->isPointerTy() && !isa<StructType>(FullTy) &&
5100 !isa<ArrayType>(FullTy) &&
5101 (!isa<VectorType>(FullTy) ||
5102 FullTy->getVectorElementType()->isFloatingPointTy() ||
5103 FullTy->getVectorElementType()->isIntegerTy()) &&
5104 "Structured types must be assigned with corresponding non-opaque "
5108 assert(I->getType() == flattenPointerTypes(FullTy) &&
5109 "Incorrect fully structured type provided for Instruction");
5110 ValueList.assignValue(I, NextValueNo++, FullTy);
5116 if (!OperandBundles.empty())
5117 return error("Operand bundles found with no consumer");
5119 // Check the function list for unresolved values.
5120 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5121 if (!A->getParent()) {
5122 // We found at least one unresolved value. Nuke them all to avoid leaks.
5123 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5124 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5125 A->replaceAllUsesWith(UndefValue::get(A->getType()));
5129 return error("Never resolved value found in function");
5133 // Unexpected unresolved metadata about to be dropped.
5134 if (MDLoader->hasFwdRefs())
5135 return error("Invalid function metadata: outgoing forward refs");
5137 // Trim the value list down to the size it was before we parsed this function.
5138 ValueList.shrinkTo(ModuleValueListSize);
5139 MDLoader->shrinkTo(ModuleMDLoaderSize);
5140 std::vector<BasicBlock*>().swap(FunctionBBs);
5141 return Error::success();
5144 /// Find the function body in the bitcode stream
5145 Error BitcodeReader::findFunctionInStream(
5147 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5148 while (DeferredFunctionInfoIterator->second == 0) {
5149 // This is the fallback handling for the old format bitcode that
5150 // didn't contain the function index in the VST, or when we have
5151 // an anonymous function which would not have a VST entry.
5152 // Assert that we have one of those two cases.
5153 assert(VSTOffset == 0 || !F->hasName());
5154 // Parse the next body in the stream and set its position in the
5155 // DeferredFunctionInfo map.
5156 if (Error Err = rememberAndSkipFunctionBodies())
5159 return Error::success();
5162 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
5163 if (Val == SyncScope::SingleThread || Val == SyncScope::System)
5164 return SyncScope::ID(Val);
5165 if (Val >= SSIDs.size())
5166 return SyncScope::System; // Map unknown synchronization scopes to system.
5170 //===----------------------------------------------------------------------===//
5171 // GVMaterializer implementation
5172 //===----------------------------------------------------------------------===//
5174 Error BitcodeReader::materialize(GlobalValue *GV) {
5175 Function *F = dyn_cast<Function>(GV);
5176 // If it's not a function or is already material, ignore the request.
5177 if (!F || !F->isMaterializable())
5178 return Error::success();
5180 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5181 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5182 // If its position is recorded as 0, its body is somewhere in the stream
5183 // but we haven't seen it yet.
5184 if (DFII->second == 0)
5185 if (Error Err = findFunctionInStream(F, DFII))
5188 // Materialize metadata before parsing any function bodies.
5189 if (Error Err = materializeMetadata())
5192 // Move the bit stream to the saved position of the deferred function body.
5193 if (Error JumpFailed = Stream.JumpToBit(DFII->second))
5195 if (Error Err = parseFunctionBody(F))
5197 F->setIsMaterializable(false);
5202 // Upgrade any old intrinsic calls in the function.
5203 for (auto &I : UpgradedIntrinsics) {
5204 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5208 if (CallInst *CI = dyn_cast<CallInst>(U))
5209 UpgradeIntrinsicCall(CI, I.second);
5213 // Update calls to the remangled intrinsics
5214 for (auto &I : RemangledIntrinsics)
5215 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5217 // Don't expect any other users than call sites
5218 CallSite(*UI++).setCalledFunction(I.second);
5220 // Finish fn->subprogram upgrade for materialized functions.
5221 if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
5222 F->setSubprogram(SP);
5224 // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
5225 if (!MDLoader->isStrippingTBAA()) {
5226 for (auto &I : instructions(F)) {
5227 MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
5228 if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
5230 MDLoader->setStripTBAA(true);
5231 stripTBAA(F->getParent());
5235 // Bring in any functions that this function forward-referenced via
5237 return materializeForwardReferencedFunctions();
5240 Error BitcodeReader::materializeModule() {
5241 if (Error Err = materializeMetadata())
5244 // Promise to materialize all forward references.
5245 WillMaterializeAllForwardRefs = true;
5247 // Iterate over the module, deserializing any functions that are still on
5249 for (Function &F : *TheModule) {
5250 if (Error Err = materialize(&F))
5253 // At this point, if there are any function bodies, parse the rest of
5254 // the bits in the module past the last function block we have recorded
5255 // through either lazy scanning or the VST.
5256 if (LastFunctionBlockBit || NextUnreadBit)
5257 if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
5258 ? LastFunctionBlockBit
5262 // Check that all block address forward references got resolved (as we
5264 if (!BasicBlockFwdRefs.empty())
5265 return error("Never resolved function from blockaddress");
5267 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5268 // delete the old functions to clean up. We can't do this unless the entire
5269 // module is materialized because there could always be another function body
5270 // with calls to the old function.
5271 for (auto &I : UpgradedIntrinsics) {
5272 for (auto *U : I.first->users()) {
5273 if (CallInst *CI = dyn_cast<CallInst>(U))
5274 UpgradeIntrinsicCall(CI, I.second);
5276 if (!I.first->use_empty())
5277 I.first->replaceAllUsesWith(I.second);
5278 I.first->eraseFromParent();
5280 UpgradedIntrinsics.clear();
5281 // Do the same for remangled intrinsics
5282 for (auto &I : RemangledIntrinsics) {
5283 I.first->replaceAllUsesWith(I.second);
5284 I.first->eraseFromParent();
5286 RemangledIntrinsics.clear();
5288 UpgradeDebugInfo(*TheModule);
5290 UpgradeModuleFlags(*TheModule);
5292 UpgradeRetainReleaseMarker(*TheModule);
5294 return Error::success();
5297 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5298 return IdentifiedStructTypes;
5301 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5302 BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
5303 StringRef ModulePath, unsigned ModuleId)
5304 : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
5305 ModulePath(ModulePath), ModuleId(ModuleId) {}
5307 void ModuleSummaryIndexBitcodeReader::addThisModule() {
5308 TheIndex.addModule(ModulePath, ModuleId);
5311 ModuleSummaryIndex::ModuleInfo *
5312 ModuleSummaryIndexBitcodeReader::getThisModule() {
5313 return TheIndex.getModule(ModulePath);
5316 std::pair<ValueInfo, GlobalValue::GUID>
5317 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
5318 auto VGI = ValueIdToValueInfoMap[ValueId];
5323 void ModuleSummaryIndexBitcodeReader::setValueGUID(
5324 uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
5325 StringRef SourceFileName) {
5326 std::string GlobalId =
5327 GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
5328 auto ValueGUID = GlobalValue::getGUID(GlobalId);
5329 auto OriginalNameID = ValueGUID;
5330 if (GlobalValue::isLocalLinkage(Linkage))
5331 OriginalNameID = GlobalValue::getGUID(ValueName);
5332 if (PrintSummaryGUIDs)
5333 dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5334 << ValueName << "\n";
5336 // UseStrtab is false for legacy summary formats and value names are
5337 // created on stack. In that case we save the name in a string saver in
5338 // the index so that the value name can be recorded.
5339 ValueIdToValueInfoMap[ValueID] = std::make_pair(
5340 TheIndex.getOrInsertValueInfo(
5342 UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
5346 // Specialized value symbol table parser used when reading module index
5347 // blocks where we don't actually create global values. The parsed information
5348 // is saved in the bitcode reader for use when later parsing summaries.
5349 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5351 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5352 // With a strtab the VST is not required to parse the summary.
5354 return Error::success();
5356 assert(Offset > 0 && "Expected non-zero VST offset");
5357 Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
5358 if (!MaybeCurrentBit)
5359 return MaybeCurrentBit.takeError();
5360 uint64_t CurrentBit = MaybeCurrentBit.get();
5362 if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5365 SmallVector<uint64_t, 64> Record;
5367 // Read all the records for this value table.
5368 SmallString<128> ValueName;
5371 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
5373 return MaybeEntry.takeError();
5374 BitstreamEntry Entry = MaybeEntry.get();
5376 switch (Entry.Kind) {
5377 case BitstreamEntry::SubBlock: // Handled for us already.
5378 case BitstreamEntry::Error:
5379 return error("Malformed block");
5380 case BitstreamEntry::EndBlock:
5381 // Done parsing VST, jump back to wherever we came from.
5382 if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
5384 return Error::success();
5385 case BitstreamEntry::Record:
5386 // The interesting case.
5392 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
5394 return MaybeRecord.takeError();
5395 switch (MaybeRecord.get()) {
5396 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5398 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5399 if (convertToString(Record, 1, ValueName))
5400 return error("Invalid record");
5401 unsigned ValueID = Record[0];
5402 assert(!SourceFileName.empty());
5403 auto VLI = ValueIdToLinkageMap.find(ValueID);
5404 assert(VLI != ValueIdToLinkageMap.end() &&
5405 "No linkage found for VST entry?");
5406 auto Linkage = VLI->second;
5407 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5411 case bitc::VST_CODE_FNENTRY: {
5412 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5413 if (convertToString(Record, 2, ValueName))
5414 return error("Invalid record");
5415 unsigned ValueID = Record[0];
5416 assert(!SourceFileName.empty());
5417 auto VLI = ValueIdToLinkageMap.find(ValueID);
5418 assert(VLI != ValueIdToLinkageMap.end() &&
5419 "No linkage found for VST entry?");
5420 auto Linkage = VLI->second;
5421 setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5425 case bitc::VST_CODE_COMBINED_ENTRY: {
5426 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5427 unsigned ValueID = Record[0];
5428 GlobalValue::GUID RefGUID = Record[1];
5429 // The "original name", which is the second value of the pair will be
5430 // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5431 ValueIdToValueInfoMap[ValueID] =
5432 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5439 // Parse just the blocks needed for building the index out of the module.
5440 // At the end of this routine the module Index is populated with a map
5441 // from global value id to GlobalValueSummary objects.
5442 Error ModuleSummaryIndexBitcodeReader::parseModule() {
5443 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5446 SmallVector<uint64_t, 64> Record;
5447 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5448 unsigned ValueId = 0;
5450 // Read the index for this module.
5452 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5454 return MaybeEntry.takeError();
5455 llvm::BitstreamEntry Entry = MaybeEntry.get();
5457 switch (Entry.Kind) {
5458 case BitstreamEntry::Error:
5459 return error("Malformed block");
5460 case BitstreamEntry::EndBlock:
5461 return Error::success();
5463 case BitstreamEntry::SubBlock:
5465 default: // Skip unknown content.
5466 if (Error Err = Stream.SkipBlock())
5469 case bitc::BLOCKINFO_BLOCK_ID:
5470 // Need to parse these to get abbrev ids (e.g. for VST)
5471 if (readBlockInfo())
5472 return error("Malformed block");
5474 case bitc::VALUE_SYMTAB_BLOCK_ID:
5475 // Should have been parsed earlier via VSTOffset, unless there
5476 // is no summary section.
5477 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5478 !SeenGlobalValSummary) &&
5479 "Expected early VST parse via VSTOffset record");
5480 if (Error Err = Stream.SkipBlock())
5483 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5484 case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
5485 // Add the module if it is a per-module index (has a source file name).
5486 if (!SourceFileName.empty())
5488 assert(!SeenValueSymbolTable &&
5489 "Already read VST when parsing summary block?");
5490 // We might not have a VST if there were no values in the
5491 // summary. An empty summary block generated when we are
5492 // performing ThinLTO compiles so we don't later invoke
5493 // the regular LTO process on them.
5494 if (VSTOffset > 0) {
5495 if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5497 SeenValueSymbolTable = true;
5499 SeenGlobalValSummary = true;
5500 if (Error Err = parseEntireSummary(Entry.ID))
5503 case bitc::MODULE_STRTAB_BLOCK_ID:
5504 if (Error Err = parseModuleStringTable())
5510 case BitstreamEntry::Record: {
5512 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5514 return MaybeBitCode.takeError();
5515 switch (MaybeBitCode.get()) {
5517 break; // Default behavior, ignore unknown content.
5518 case bitc::MODULE_CODE_VERSION: {
5519 if (Error Err = parseVersionRecord(Record).takeError())
5523 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5524 case bitc::MODULE_CODE_SOURCE_FILENAME: {
5525 SmallString<128> ValueName;
5526 if (convertToString(Record, 0, ValueName))
5527 return error("Invalid record");
5528 SourceFileName = ValueName.c_str();
5531 /// MODULE_CODE_HASH: [5*i32]
5532 case bitc::MODULE_CODE_HASH: {
5533 if (Record.size() != 5)
5534 return error("Invalid hash length " + Twine(Record.size()).str());
5535 auto &Hash = getThisModule()->second.second;
5537 for (auto &Val : Record) {
5538 assert(!(Val >> 32) && "Unexpected high bits set");
5543 /// MODULE_CODE_VSTOFFSET: [offset]
5544 case bitc::MODULE_CODE_VSTOFFSET:
5545 if (Record.size() < 1)
5546 return error("Invalid record");
5547 // Note that we subtract 1 here because the offset is relative to one
5548 // word before the start of the identification or module block, which
5549 // was historically always the start of the regular bitcode header.
5550 VSTOffset = Record[0] - 1;
5552 // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
5553 // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
5554 // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
5555 // v2: [strtab offset, strtab size, v1]
5556 case bitc::MODULE_CODE_GLOBALVAR:
5557 case bitc::MODULE_CODE_FUNCTION:
5558 case bitc::MODULE_CODE_ALIAS: {
5560 ArrayRef<uint64_t> GVRecord;
5561 std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5562 if (GVRecord.size() <= 3)
5563 return error("Invalid record");
5564 uint64_t RawLinkage = GVRecord[3];
5565 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5567 ValueIdToLinkageMap[ValueId++] = Linkage;
5571 setValueGUID(ValueId++, Name, Linkage, SourceFileName);
5581 std::vector<ValueInfo>
5582 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5583 std::vector<ValueInfo> Ret;
5584 Ret.reserve(Record.size());
5585 for (uint64_t RefValueId : Record)
5586 Ret.push_back(getValueInfoFromValueId(RefValueId).first);
5590 std::vector<FunctionSummary::EdgeTy>
5591 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
5592 bool IsOldProfileFormat,
5593 bool HasProfile, bool HasRelBF) {
5594 std::vector<FunctionSummary::EdgeTy> Ret;
5595 Ret.reserve(Record.size());
5596 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
5597 CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
5599 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
5600 if (IsOldProfileFormat) {
5601 I += 1; // Skip old callsitecount field
5603 I += 1; // Skip old profilecount field
5604 } else if (HasProfile)
5605 Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
5607 RelBF = Record[++I];
5608 Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
5614 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
5615 WholeProgramDevirtResolution &Wpd) {
5616 uint64_t ArgNum = Record[Slot++];
5617 WholeProgramDevirtResolution::ByArg &B =
5618 Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
5622 static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
5623 B.Info = Record[Slot++];
5624 B.Byte = Record[Slot++];
5625 B.Bit = Record[Slot++];
5628 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
5629 StringRef Strtab, size_t &Slot,
5630 TypeIdSummary &TypeId) {
5631 uint64_t Id = Record[Slot++];
5632 WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
5634 Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
5635 Wpd.SingleImplName = {Strtab.data() + Record[Slot],
5636 static_cast<size_t>(Record[Slot + 1])};
5639 uint64_t ResByArgNum = Record[Slot++];
5640 for (uint64_t I = 0; I != ResByArgNum; ++I)
5641 parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
5644 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
5646 ModuleSummaryIndex &TheIndex) {
5648 TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
5649 {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
5652 TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
5653 TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
5654 TypeId.TTRes.AlignLog2 = Record[Slot++];
5655 TypeId.TTRes.SizeM1 = Record[Slot++];
5656 TypeId.TTRes.BitMask = Record[Slot++];
5657 TypeId.TTRes.InlineBits = Record[Slot++];
5659 while (Slot < Record.size())
5660 parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
5663 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
5664 ArrayRef<uint64_t> Record, size_t &Slot,
5665 TypeIdCompatibleVtableInfo &TypeId) {
5666 uint64_t Offset = Record[Slot++];
5667 ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;
5668 TypeId.push_back({Offset, Callee});
5671 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
5672 ArrayRef<uint64_t> Record) {
5674 TypeIdCompatibleVtableInfo &TypeId =
5675 TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
5676 {Strtab.data() + Record[Slot],
5677 static_cast<size_t>(Record[Slot + 1])});
5680 while (Slot < Record.size())
5681 parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
5684 static void setImmutableRefs(std::vector<ValueInfo> &Refs, unsigned Count) {
5685 // Read-only refs are in the end of the refs list.
5686 for (unsigned RefNo = Refs.size() - Count; RefNo < Refs.size(); ++RefNo)
5687 Refs[RefNo].setReadOnly();
5690 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
5691 // objects in the index.
5692 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
5693 if (Error Err = Stream.EnterSubBlock(ID))
5695 SmallVector<uint64_t, 64> Record;
5699 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
5701 return MaybeEntry.takeError();
5702 BitstreamEntry Entry = MaybeEntry.get();
5704 if (Entry.Kind != BitstreamEntry::Record)
5705 return error("Invalid Summary Block: record for version expected");
5706 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
5708 return MaybeRecord.takeError();
5709 if (MaybeRecord.get() != bitc::FS_VERSION)
5710 return error("Invalid Summary Block: version expected");
5712 const uint64_t Version = Record[0];
5713 const bool IsOldProfileFormat = Version == 1;
5714 if (Version < 1 || Version > 6)
5715 return error("Invalid summary version " + Twine(Version) +
5716 ". Version should be in the range [1-6].");
5719 // Keep around the last seen summary to be used when we see an optional
5720 // "OriginalName" attachement.
5721 GlobalValueSummary *LastSeenSummary = nullptr;
5722 GlobalValue::GUID LastSeenGUID = 0;
5724 // We can expect to see any number of type ID information records before
5725 // each function summary records; these variables store the information
5726 // collected so far so that it can be used to create the summary object.
5727 std::vector<GlobalValue::GUID> PendingTypeTests;
5728 std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5729 PendingTypeCheckedLoadVCalls;
5730 std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5731 PendingTypeCheckedLoadConstVCalls;
5734 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
5736 return MaybeEntry.takeError();
5737 BitstreamEntry Entry = MaybeEntry.get();
5739 switch (Entry.Kind) {
5740 case BitstreamEntry::SubBlock: // Handled for us already.
5741 case BitstreamEntry::Error:
5742 return error("Malformed block");
5743 case BitstreamEntry::EndBlock:
5744 return Error::success();
5745 case BitstreamEntry::Record:
5746 // The interesting case.
5750 // Read a record. The record format depends on whether this
5751 // is a per-module index or a combined index file. In the per-module
5752 // case the records contain the associated value's ID for correlation
5753 // with VST entries. In the combined index the correlation is done
5754 // via the bitcode offset of the summary records (which were saved
5755 // in the combined index VST entries). The records also contain
5756 // information used for ThinLTO renaming and importing.
5758 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5760 return MaybeBitCode.takeError();
5761 switch (unsigned BitCode = MaybeBitCode.get()) {
5762 default: // Default behavior: ignore.
5764 case bitc::FS_FLAGS: { // [flags]
5765 uint64_t Flags = Record[0];
5767 assert(Flags <= 0x1f && "Unexpected bits in flag");
5769 // 1 bit: WithGlobalValueDeadStripping flag.
5770 // Set on combined index only.
5772 TheIndex.setWithGlobalValueDeadStripping();
5773 // 1 bit: SkipModuleByDistributedBackend flag.
5774 // Set on combined index only.
5776 TheIndex.setSkipModuleByDistributedBackend();
5777 // 1 bit: HasSyntheticEntryCounts flag.
5778 // Set on combined index only.
5780 TheIndex.setHasSyntheticEntryCounts();
5781 // 1 bit: DisableSplitLTOUnit flag.
5782 // Set on per module indexes. It is up to the client to validate
5783 // the consistency of this flag across modules being linked.
5785 TheIndex.setEnableSplitLTOUnit();
5786 // 1 bit: PartiallySplitLTOUnits flag.
5787 // Set on combined index only.
5789 TheIndex.setPartiallySplitLTOUnits();
5792 case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5793 uint64_t ValueID = Record[0];
5794 GlobalValue::GUID RefGUID = Record[1];
5795 ValueIdToValueInfoMap[ValueID] =
5796 std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5799 // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
5800 // numrefs x valueid, n x (valueid)]
5801 // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
5802 // numrefs x valueid,
5803 // n x (valueid, hotness)]
5804 // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
5805 // numrefs x valueid,
5806 // n x (valueid, relblockfreq)]
5807 case bitc::FS_PERMODULE:
5808 case bitc::FS_PERMODULE_RELBF:
5809 case bitc::FS_PERMODULE_PROFILE: {
5810 unsigned ValueID = Record[0];
5811 uint64_t RawFlags = Record[1];
5812 unsigned InstCount = Record[2];
5813 uint64_t RawFunFlags = 0;
5814 unsigned NumRefs = Record[3];
5815 unsigned NumImmutableRefs = 0;
5816 int RefListStartIndex = 4;
5818 RawFunFlags = Record[3];
5819 NumRefs = Record[4];
5820 RefListStartIndex = 5;
5822 NumImmutableRefs = Record[5];
5823 RefListStartIndex = 6;
5827 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5828 // The module path string ref set in the summary must be owned by the
5829 // index's module string table. Since we don't have a module path
5830 // string table section in the per-module index, we create a single
5831 // module path string table entry with an empty (0) ID to take
5833 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5834 assert(Record.size() >= RefListStartIndex + NumRefs &&
5835 "Record size inconsistent with number of references");
5836 std::vector<ValueInfo> Refs = makeRefList(
5837 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5838 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
5839 bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
5840 std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5841 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5842 IsOldProfileFormat, HasProfile, HasRelBF);
5843 setImmutableRefs(Refs, NumImmutableRefs);
5844 auto FS = llvm::make_unique<FunctionSummary>(
5845 Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
5846 std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
5847 std::move(PendingTypeTestAssumeVCalls),
5848 std::move(PendingTypeCheckedLoadVCalls),
5849 std::move(PendingTypeTestAssumeConstVCalls),
5850 std::move(PendingTypeCheckedLoadConstVCalls));
5851 PendingTypeTests.clear();
5852 PendingTypeTestAssumeVCalls.clear();
5853 PendingTypeCheckedLoadVCalls.clear();
5854 PendingTypeTestAssumeConstVCalls.clear();
5855 PendingTypeCheckedLoadConstVCalls.clear();
5856 auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
5857 FS->setModulePath(getThisModule()->first());
5858 FS->setOriginalName(VIAndOriginalGUID.second);
5859 TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
5862 // FS_ALIAS: [valueid, flags, valueid]
5863 // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5864 // they expect all aliasee summaries to be available.
5865 case bitc::FS_ALIAS: {
5866 unsigned ValueID = Record[0];
5867 uint64_t RawFlags = Record[1];
5868 unsigned AliaseeID = Record[2];
5869 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5870 auto AS = llvm::make_unique<AliasSummary>(Flags);
5871 // The module path string ref set in the summary must be owned by the
5872 // index's module string table. Since we don't have a module path
5873 // string table section in the per-module index, we create a single
5874 // module path string table entry with an empty (0) ID to take
5876 AS->setModulePath(getThisModule()->first());
5878 auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
5879 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
5880 if (!AliaseeInModule)
5881 return error("Alias expects aliasee summary to be parsed");
5882 AS->setAliasee(AliaseeVI, AliaseeInModule);
5884 auto GUID = getValueInfoFromValueId(ValueID);
5885 AS->setOriginalName(GUID.second);
5886 TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
5889 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
5890 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5891 unsigned ValueID = Record[0];
5892 uint64_t RawFlags = Record[1];
5893 unsigned RefArrayStart = 2;
5894 GlobalVarSummary::GVarFlags GVF;
5895 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5897 GVF = getDecodedGVarFlags(Record[2]);
5900 std::vector<ValueInfo> Refs =
5901 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
5903 llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
5904 FS->setModulePath(getThisModule()->first());
5905 auto GUID = getValueInfoFromValueId(ValueID);
5906 FS->setOriginalName(GUID.second);
5907 TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
5910 // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
5911 // numrefs, numrefs x valueid,
5912 // n x (valueid, offset)]
5913 case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
5914 unsigned ValueID = Record[0];
5915 uint64_t RawFlags = Record[1];
5916 GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
5917 unsigned NumRefs = Record[3];
5918 unsigned RefListStartIndex = 4;
5919 unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
5920 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5921 std::vector<ValueInfo> Refs = makeRefList(
5922 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5923 VTableFuncList VTableFuncs;
5924 for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
5925 ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
5926 uint64_t Offset = Record[++I];
5927 VTableFuncs.push_back({Callee, Offset});
5930 llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
5931 VS->setModulePath(getThisModule()->first());
5932 VS->setVTableFuncs(VTableFuncs);
5933 auto GUID = getValueInfoFromValueId(ValueID);
5934 VS->setOriginalName(GUID.second);
5935 TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));
5938 // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
5939 // numrefs x valueid, n x (valueid)]
5940 // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
5941 // numrefs x valueid, n x (valueid, hotness)]
5942 case bitc::FS_COMBINED:
5943 case bitc::FS_COMBINED_PROFILE: {
5944 unsigned ValueID = Record[0];
5945 uint64_t ModuleId = Record[1];
5946 uint64_t RawFlags = Record[2];
5947 unsigned InstCount = Record[3];
5948 uint64_t RawFunFlags = 0;
5949 uint64_t EntryCount = 0;
5950 unsigned NumRefs = Record[4];
5951 unsigned NumImmutableRefs = 0;
5952 int RefListStartIndex = 5;
5955 RawFunFlags = Record[4];
5956 RefListStartIndex = 6;
5957 size_t NumRefsIndex = 5;
5959 RefListStartIndex = 7;
5962 EntryCount = Record[5];
5963 RefListStartIndex = 8;
5965 NumImmutableRefs = Record[RefListStartIndex - 1];
5967 NumRefs = Record[NumRefsIndex];
5970 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5971 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5972 assert(Record.size() >= RefListStartIndex + NumRefs &&
5973 "Record size inconsistent with number of references");
5974 std::vector<ValueInfo> Refs = makeRefList(
5975 ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5976 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5977 std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5978 ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5979 IsOldProfileFormat, HasProfile, false);
5980 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5981 setImmutableRefs(Refs, NumImmutableRefs);
5982 auto FS = llvm::make_unique<FunctionSummary>(
5983 Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
5984 std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
5985 std::move(PendingTypeTestAssumeVCalls),
5986 std::move(PendingTypeCheckedLoadVCalls),
5987 std::move(PendingTypeTestAssumeConstVCalls),
5988 std::move(PendingTypeCheckedLoadConstVCalls));
5989 PendingTypeTests.clear();
5990 PendingTypeTestAssumeVCalls.clear();
5991 PendingTypeCheckedLoadVCalls.clear();
5992 PendingTypeTestAssumeConstVCalls.clear();
5993 PendingTypeCheckedLoadConstVCalls.clear();
5994 LastSeenSummary = FS.get();
5995 LastSeenGUID = VI.getGUID();
5996 FS->setModulePath(ModuleIdMap[ModuleId]);
5997 TheIndex.addGlobalValueSummary(VI, std::move(FS));
6000 // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6001 // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6002 // they expect all aliasee summaries to be available.
6003 case bitc::FS_COMBINED_ALIAS: {
6004 unsigned ValueID = Record[0];
6005 uint64_t ModuleId = Record[1];
6006 uint64_t RawFlags = Record[2];
6007 unsigned AliaseeValueId = Record[3];
6008 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6009 auto AS = llvm::make_unique<AliasSummary>(Flags);
6010 LastSeenSummary = AS.get();
6011 AS->setModulePath(ModuleIdMap[ModuleId]);
6013 auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
6014 auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
6015 AS->setAliasee(AliaseeVI, AliaseeInModule);
6017 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6018 LastSeenGUID = VI.getGUID();
6019 TheIndex.addGlobalValueSummary(VI, std::move(AS));
6022 // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6023 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6024 unsigned ValueID = Record[0];
6025 uint64_t ModuleId = Record[1];
6026 uint64_t RawFlags = Record[2];
6027 unsigned RefArrayStart = 3;
6028 GlobalVarSummary::GVarFlags GVF;
6029 auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6031 GVF = getDecodedGVarFlags(Record[3]);
6034 std::vector<ValueInfo> Refs =
6035 makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6037 llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6038 LastSeenSummary = FS.get();
6039 FS->setModulePath(ModuleIdMap[ModuleId]);
6040 ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6041 LastSeenGUID = VI.getGUID();
6042 TheIndex.addGlobalValueSummary(VI, std::move(FS));
6045 // FS_COMBINED_ORIGINAL_NAME: [original_name]
6046 case bitc::FS_COMBINED_ORIGINAL_NAME: {
6047 uint64_t OriginalName = Record[0];
6048 if (!LastSeenSummary)
6049 return error("Name attachment that does not follow a combined record");
6050 LastSeenSummary->setOriginalName(OriginalName);
6051 TheIndex.addOriginalName(LastSeenGUID, OriginalName);
6052 // Reset the LastSeenSummary
6053 LastSeenSummary = nullptr;
6057 case bitc::FS_TYPE_TESTS:
6058 assert(PendingTypeTests.empty());
6059 PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
6063 case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
6064 assert(PendingTypeTestAssumeVCalls.empty());
6065 for (unsigned I = 0; I != Record.size(); I += 2)
6066 PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
6069 case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
6070 assert(PendingTypeCheckedLoadVCalls.empty());
6071 for (unsigned I = 0; I != Record.size(); I += 2)
6072 PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
6075 case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
6076 PendingTypeTestAssumeConstVCalls.push_back(
6077 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6080 case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
6081 PendingTypeCheckedLoadConstVCalls.push_back(
6082 {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6085 case bitc::FS_CFI_FUNCTION_DEFS: {
6086 std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
6087 for (unsigned I = 0; I != Record.size(); I += 2)
6088 CfiFunctionDefs.insert(
6089 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6093 case bitc::FS_CFI_FUNCTION_DECLS: {
6094 std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
6095 for (unsigned I = 0; I != Record.size(); I += 2)
6096 CfiFunctionDecls.insert(
6097 {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6101 case bitc::FS_TYPE_ID:
6102 parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
6105 case bitc::FS_TYPE_ID_METADATA:
6106 parseTypeIdCompatibleVtableSummaryRecord(Record);
6110 llvm_unreachable("Exit infinite loop");
6113 // Parse the module string table block into the Index.
6114 // This populates the ModulePathStringTable map in the index.
6115 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6116 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6119 SmallVector<uint64_t, 64> Record;
6121 SmallString<128> ModulePath;
6122 ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
6125 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6127 return MaybeEntry.takeError();
6128 BitstreamEntry Entry = MaybeEntry.get();
6130 switch (Entry.Kind) {
6131 case BitstreamEntry::SubBlock: // Handled for us already.
6132 case BitstreamEntry::Error:
6133 return error("Malformed block");
6134 case BitstreamEntry::EndBlock:
6135 return Error::success();
6136 case BitstreamEntry::Record:
6137 // The interesting case.
6142 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6144 return MaybeRecord.takeError();
6145 switch (MaybeRecord.get()) {
6146 default: // Default behavior: ignore.
6148 case bitc::MST_CODE_ENTRY: {
6149 // MST_ENTRY: [modid, namechar x N]
6150 uint64_t ModuleId = Record[0];
6152 if (convertToString(Record, 1, ModulePath))
6153 return error("Invalid record");
6155 LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
6156 ModuleIdMap[ModuleId] = LastSeenModule->first();
6161 /// MST_CODE_HASH: [5*i32]
6162 case bitc::MST_CODE_HASH: {
6163 if (Record.size() != 5)
6164 return error("Invalid hash length " + Twine(Record.size()).str());
6165 if (!LastSeenModule)
6166 return error("Invalid hash that does not follow a module path");
6168 for (auto &Val : Record) {
6169 assert(!(Val >> 32) && "Unexpected high bits set");
6170 LastSeenModule->second.second[Pos++] = Val;
6172 // Reset LastSeenModule to avoid overriding the hash unexpectedly.
6173 LastSeenModule = nullptr;
6178 llvm_unreachable("Exit infinite loop");
6183 // FIXME: This class is only here to support the transition to llvm::Error. It
6184 // will be removed once this transition is complete. Clients should prefer to
6185 // deal with the Error value directly, rather than converting to error_code.
6186 class BitcodeErrorCategoryType : public std::error_category {
6187 const char *name() const noexcept override {
6188 return "llvm.bitcode";
6191 std::string message(int IE) const override {
6192 BitcodeError E = static_cast<BitcodeError>(IE);
6194 case BitcodeError::CorruptedBitcode:
6195 return "Corrupted bitcode";
6197 llvm_unreachable("Unknown error type!");
6201 } // end anonymous namespace
6203 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6205 const std::error_category &llvm::BitcodeErrorCategory() {
6206 return *ErrorCategory;
6209 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
6210 unsigned Block, unsigned RecordID) {
6211 if (Error Err = Stream.EnterSubBlock(Block))
6212 return std::move(Err);
6216 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6218 return MaybeEntry.takeError();
6219 llvm::BitstreamEntry Entry = MaybeEntry.get();
6221 switch (Entry.Kind) {
6222 case BitstreamEntry::EndBlock:
6225 case BitstreamEntry::Error:
6226 return error("Malformed block");
6228 case BitstreamEntry::SubBlock:
6229 if (Error Err = Stream.SkipBlock())
6230 return std::move(Err);
6233 case BitstreamEntry::Record:
6235 SmallVector<uint64_t, 1> Record;
6236 Expected<unsigned> MaybeRecord =
6237 Stream.readRecord(Entry.ID, Record, &Blob);
6239 return MaybeRecord.takeError();
6240 if (MaybeRecord.get() == RecordID)
6247 //===----------------------------------------------------------------------===//
6248 // External interface
6249 //===----------------------------------------------------------------------===//
6251 Expected<std::vector<BitcodeModule>>
6252 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
6253 auto FOrErr = getBitcodeFileContents(Buffer);
6255 return FOrErr.takeError();
6256 return std::move(FOrErr->Mods);
6259 Expected<BitcodeFileContents>
6260 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
6261 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6263 return StreamOrErr.takeError();
6264 BitstreamCursor &Stream = *StreamOrErr;
6266 BitcodeFileContents F;
6268 uint64_t BCBegin = Stream.getCurrentByteNo();
6270 // We may be consuming bitcode from a client that leaves garbage at the end
6271 // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
6272 // the end that there cannot possibly be another module, stop looking.
6273 if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
6276 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6278 return MaybeEntry.takeError();
6279 llvm::BitstreamEntry Entry = MaybeEntry.get();
6281 switch (Entry.Kind) {
6282 case BitstreamEntry::EndBlock:
6283 case BitstreamEntry::Error:
6284 return error("Malformed block");
6286 case BitstreamEntry::SubBlock: {
6287 uint64_t IdentificationBit = -1ull;
6288 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
6289 IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6290 if (Error Err = Stream.SkipBlock())
6291 return std::move(Err);
6294 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6296 return MaybeEntry.takeError();
6297 Entry = MaybeEntry.get();
6300 if (Entry.Kind != BitstreamEntry::SubBlock ||
6301 Entry.ID != bitc::MODULE_BLOCK_ID)
6302 return error("Malformed block");
6305 if (Entry.ID == bitc::MODULE_BLOCK_ID) {
6306 uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6307 if (Error Err = Stream.SkipBlock())
6308 return std::move(Err);
6310 F.Mods.push_back({Stream.getBitcodeBytes().slice(
6311 BCBegin, Stream.getCurrentByteNo() - BCBegin),
6312 Buffer.getBufferIdentifier(), IdentificationBit,
6317 if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
6318 Expected<StringRef> Strtab =
6319 readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
6321 return Strtab.takeError();
6322 // This string table is used by every preceding bitcode module that does
6323 // not have its own string table. A bitcode file may have multiple
6324 // string tables if it was created by binary concatenation, for example
6325 // with "llvm-cat -b".
6326 for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
6327 if (!I->Strtab.empty())
6329 I->Strtab = *Strtab;
6331 // Similarly, the string table is used by every preceding symbol table;
6332 // normally there will be just one unless the bitcode file was created
6333 // by binary concatenation.
6334 if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
6335 F.StrtabForSymtab = *Strtab;
6339 if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
6340 Expected<StringRef> SymtabOrErr =
6341 readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
6343 return SymtabOrErr.takeError();
6345 // We can expect the bitcode file to have multiple symbol tables if it
6346 // was created by binary concatenation. In that case we silently
6347 // ignore any subsequent symbol tables, which is fine because this is a
6348 // low level function. The client is expected to notice that the number
6349 // of modules in the symbol table does not match the number of modules
6350 // in the input file and regenerate the symbol table.
6351 if (F.Symtab.empty())
6352 F.Symtab = *SymtabOrErr;
6356 if (Error Err = Stream.SkipBlock())
6357 return std::move(Err);
6360 case BitstreamEntry::Record:
6361 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
6364 return StreamFailed.takeError();
6369 /// Get a lazy one-at-time loading module from bitcode.
6371 /// This isn't always used in a lazy context. In particular, it's also used by
6372 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
6373 /// in forward-referenced functions from block address references.
6375 /// \param[in] MaterializeAll Set to \c true if we should materialize
6377 Expected<std::unique_ptr<Module>>
6378 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
6379 bool ShouldLazyLoadMetadata, bool IsImporting) {
6380 BitstreamCursor Stream(Buffer);
6382 std::string ProducerIdentification;
6383 if (IdentificationBit != -1ull) {
6384 if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
6385 return std::move(JumpFailed);
6386 Expected<std::string> ProducerIdentificationOrErr =
6387 readIdentificationBlock(Stream);
6388 if (!ProducerIdentificationOrErr)
6389 return ProducerIdentificationOrErr.takeError();
6391 ProducerIdentification = *ProducerIdentificationOrErr;
6394 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6395 return std::move(JumpFailed);
6396 auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
6399 std::unique_ptr<Module> M =
6400 llvm::make_unique<Module>(ModuleIdentifier, Context);
6401 M->setMaterializer(R);
6403 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6405 R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
6406 return std::move(Err);
6408 if (MaterializeAll) {
6409 // Read in the entire module, and destroy the BitcodeReader.
6410 if (Error Err = M->materializeAll())
6411 return std::move(Err);
6413 // Resolve forward references from blockaddresses.
6414 if (Error Err = R->materializeForwardReferencedFunctions())
6415 return std::move(Err);
6417 return std::move(M);
6420 Expected<std::unique_ptr<Module>>
6421 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
6423 return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
6426 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
6427 // We don't use ModuleIdentifier here because the client may need to control the
6428 // module path used in the combined summary (e.g. when reading summaries for
6429 // regular LTO modules).
6430 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
6431 StringRef ModulePath, uint64_t ModuleId) {
6432 BitstreamCursor Stream(Buffer);
6433 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6436 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
6437 ModulePath, ModuleId);
6438 return R.parseModule();
6441 // Parse the specified bitcode buffer, returning the function info index.
6442 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
6443 BitstreamCursor Stream(Buffer);
6444 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6445 return std::move(JumpFailed);
6447 auto Index = llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
6448 ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
6449 ModuleIdentifier, 0);
6451 if (Error Err = R.parseModule())
6452 return std::move(Err);
6454 return std::move(Index);
6457 static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
6459 if (Error Err = Stream.EnterSubBlock(ID))
6460 return std::move(Err);
6461 SmallVector<uint64_t, 64> Record;
6464 Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6466 return MaybeEntry.takeError();
6467 BitstreamEntry Entry = MaybeEntry.get();
6469 switch (Entry.Kind) {
6470 case BitstreamEntry::SubBlock: // Handled for us already.
6471 case BitstreamEntry::Error:
6472 return error("Malformed block");
6473 case BitstreamEntry::EndBlock:
6474 // If no flags record found, conservatively return true to mimic
6475 // behavior before this flag was added.
6477 case BitstreamEntry::Record:
6478 // The interesting case.
6482 // Look for the FS_FLAGS record.
6484 Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6486 return MaybeBitCode.takeError();
6487 switch (MaybeBitCode.get()) {
6488 default: // Default behavior: ignore.
6490 case bitc::FS_FLAGS: { // [flags]
6491 uint64_t Flags = Record[0];
6493 assert(Flags <= 0x1f && "Unexpected bits in flag");
6499 llvm_unreachable("Exit infinite loop");
6502 // Check if the given bitcode buffer contains a global value summary block.
6503 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
6504 BitstreamCursor Stream(Buffer);
6505 if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6506 return std::move(JumpFailed);
6508 if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6509 return std::move(Err);
6512 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6514 return MaybeEntry.takeError();
6515 llvm::BitstreamEntry Entry = MaybeEntry.get();
6517 switch (Entry.Kind) {
6518 case BitstreamEntry::Error:
6519 return error("Malformed block");
6520 case BitstreamEntry::EndBlock:
6521 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
6522 /*EnableSplitLTOUnit=*/false};
6524 case BitstreamEntry::SubBlock:
6525 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
6526 Expected<bool> EnableSplitLTOUnit =
6527 getEnableSplitLTOUnitFlag(Stream, Entry.ID);
6528 if (!EnableSplitLTOUnit)
6529 return EnableSplitLTOUnit.takeError();
6530 return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
6531 *EnableSplitLTOUnit};
6534 if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
6535 Expected<bool> EnableSplitLTOUnit =
6536 getEnableSplitLTOUnitFlag(Stream, Entry.ID);
6537 if (!EnableSplitLTOUnit)
6538 return EnableSplitLTOUnit.takeError();
6539 return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
6540 *EnableSplitLTOUnit};
6543 // Ignore other sub-blocks.
6544 if (Error Err = Stream.SkipBlock())
6545 return std::move(Err);
6548 case BitstreamEntry::Record:
6549 if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
6552 return StreamFailed.takeError();
6557 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
6558 Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
6560 return MsOrErr.takeError();
6562 if (MsOrErr->size() != 1)
6563 return error("Expected a single module");
6565 return (*MsOrErr)[0];
6568 Expected<std::unique_ptr<Module>>
6569 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
6570 bool ShouldLazyLoadMetadata, bool IsImporting) {
6571 Expected<BitcodeModule> BM = getSingleModule(Buffer);
6573 return BM.takeError();
6575 return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
6578 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
6579 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
6580 bool ShouldLazyLoadMetadata, bool IsImporting) {
6581 auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
6584 (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
6588 Expected<std::unique_ptr<Module>>
6589 BitcodeModule::parseModule(LLVMContext &Context) {
6590 return getModuleImpl(Context, true, false, false);
6591 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6592 // written. We must defer until the Module has been fully materialized.
6595 Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6596 LLVMContext &Context) {
6597 Expected<BitcodeModule> BM = getSingleModule(Buffer);
6599 return BM.takeError();
6601 return BM->parseModule(Context);
6604 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
6605 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6607 return StreamOrErr.takeError();
6609 return readTriple(*StreamOrErr);
6612 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
6613 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6615 return StreamOrErr.takeError();
6617 return hasObjCCategory(*StreamOrErr);
6620 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
6621 Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6623 return StreamOrErr.takeError();
6625 return readIdentificationCode(*StreamOrErr);
6628 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
6629 ModuleSummaryIndex &CombinedIndex,
6630 uint64_t ModuleId) {
6631 Expected<BitcodeModule> BM = getSingleModule(Buffer);
6633 return BM.takeError();
6635 return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
6638 Expected<std::unique_ptr<ModuleSummaryIndex>>
6639 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
6640 Expected<BitcodeModule> BM = getSingleModule(Buffer);
6642 return BM.takeError();
6644 return BM->getSummary();
6647 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
6648 Expected<BitcodeModule> BM = getSingleModule(Buffer);
6650 return BM.takeError();
6652 return BM->getLTOInfo();
6655 Expected<std::unique_ptr<ModuleSummaryIndex>>
6656 llvm::getModuleSummaryIndexForFile(StringRef Path,
6657 bool IgnoreEmptyThinLTOIndexFile) {
6658 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6659 MemoryBuffer::getFileOrSTDIN(Path);
6661 return errorCodeToError(FileOrErr.getError());
6662 if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
6664 return getModuleSummaryIndex(**FileOrErr);