xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
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/BitcodeCommon.h"
24 #include "llvm/Bitcode/LLVMBitCodes.h"
25 #include "llvm/Bitstream/BitstreamReader.h"
26 #include "llvm/Config/llvm-config.h"
27 #include "llvm/IR/Argument.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/AutoUpgrade.h"
30 #include "llvm/IR/BasicBlock.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"
74 #include <algorithm>
75 #include <cassert>
76 #include <cstddef>
77 #include <cstdint>
78 #include <deque>
79 #include <map>
80 #include <memory>
81 #include <set>
82 #include <string>
83 #include <system_error>
84 #include <tuple>
85 #include <utility>
86 #include <vector>
87 
88 using namespace llvm;
89 
90 static cl::opt<bool> PrintSummaryGUIDs(
91     "print-summary-global-ids", cl::init(false), cl::Hidden,
92     cl::desc(
93         "Print the global id for each value when reading the module summary"));
94 
95 namespace {
96 
97 enum {
98   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
99 };
100 
101 } // end anonymous namespace
102 
error(const Twine & Message)103 static Error error(const Twine &Message) {
104   return make_error<StringError>(
105       Message, make_error_code(BitcodeError::CorruptedBitcode));
106 }
107 
hasInvalidBitcodeHeader(BitstreamCursor & Stream)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)) {
114       if (Res.get() != C)
115         return createStringError(std::errc::illegal_byte_sequence,
116                                  "file doesn't start with bitcode header");
117     } else
118       return Res.takeError();
119   for (unsigned C : {0x0, 0xC, 0xE, 0xD})
120     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
121       if (Res.get() != C)
122         return createStringError(std::errc::illegal_byte_sequence,
123                                  "file doesn't start with bitcode header");
124     } else
125       return Res.takeError();
126   return Error::success();
127 }
128 
initStream(MemoryBufferRef Buffer)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();
132 
133   if (Buffer.getBufferSize() & 3)
134     return error("Invalid bitcode signature");
135 
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");
141 
142   BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
143   if (Error Err = hasInvalidBitcodeHeader(Stream))
144     return std::move(Err);
145 
146   return std::move(Stream);
147 }
148 
149 /// Convert a string from a record into an std::string, return true on failure.
150 template <typename StrTy>
convertToString(ArrayRef<uint64_t> Record,unsigned Idx,StrTy & Result)151 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
152                             StrTy &Result) {
153   if (Idx > Record.size())
154     return true;
155 
156   Result.append(Record.begin() + Idx, Record.end());
157   return false;
158 }
159 
160 // Strip all the TBAA attachment for the module.
stripTBAA(Module * M)161 static void stripTBAA(Module *M) {
162   for (auto &F : *M) {
163     if (F.isMaterializable())
164       continue;
165     for (auto &I : instructions(F))
166       I.setMetadata(LLVMContext::MD_tbaa, nullptr);
167   }
168 }
169 
170 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
171 /// "epoch" encoded in the bitcode, and return the producer name if any.
readIdentificationBlock(BitstreamCursor & Stream)172 static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
173   if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
174     return std::move(Err);
175 
176   // Read all the records.
177   SmallVector<uint64_t, 64> Record;
178 
179   std::string ProducerIdentification;
180 
181   while (true) {
182     BitstreamEntry Entry;
183     if (Expected<BitstreamEntry> Res = Stream.advance())
184       Entry = Res.get();
185     else
186       return Res.takeError();
187 
188     switch (Entry.Kind) {
189     default:
190     case BitstreamEntry::Error:
191       return error("Malformed block");
192     case BitstreamEntry::EndBlock:
193       return ProducerIdentification;
194     case BitstreamEntry::Record:
195       // The interesting case.
196       break;
197     }
198 
199     // Read a record.
200     Record.clear();
201     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
202     if (!MaybeBitCode)
203       return MaybeBitCode.takeError();
204     switch (MaybeBitCode.get()) {
205     default: // Default behavior: reject
206       return error("Invalid value");
207     case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
208       convertToString(Record, 0, ProducerIdentification);
209       break;
210     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
211       unsigned epoch = (unsigned)Record[0];
212       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
213         return error(
214           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
215           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
216       }
217     }
218     }
219   }
220 }
221 
readIdentificationCode(BitstreamCursor & Stream)222 static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
223   // We expect a number of well-defined blocks, though we don't necessarily
224   // need to understand them all.
225   while (true) {
226     if (Stream.AtEndOfStream())
227       return "";
228 
229     BitstreamEntry Entry;
230     if (Expected<BitstreamEntry> Res = Stream.advance())
231       Entry = std::move(Res.get());
232     else
233       return Res.takeError();
234 
235     switch (Entry.Kind) {
236     case BitstreamEntry::EndBlock:
237     case BitstreamEntry::Error:
238       return error("Malformed block");
239 
240     case BitstreamEntry::SubBlock:
241       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
242         return readIdentificationBlock(Stream);
243 
244       // Ignore other sub-blocks.
245       if (Error Err = Stream.SkipBlock())
246         return std::move(Err);
247       continue;
248     case BitstreamEntry::Record:
249       if (Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
250         continue;
251       else
252         return Skipped.takeError();
253     }
254   }
255 }
256 
hasObjCCategoryInModule(BitstreamCursor & Stream)257 static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
258   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
259     return std::move(Err);
260 
261   SmallVector<uint64_t, 64> Record;
262   // Read all the records for this module.
263 
264   while (true) {
265     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
266     if (!MaybeEntry)
267       return MaybeEntry.takeError();
268     BitstreamEntry Entry = MaybeEntry.get();
269 
270     switch (Entry.Kind) {
271     case BitstreamEntry::SubBlock: // Handled for us already.
272     case BitstreamEntry::Error:
273       return error("Malformed block");
274     case BitstreamEntry::EndBlock:
275       return false;
276     case BitstreamEntry::Record:
277       // The interesting case.
278       break;
279     }
280 
281     // Read a record.
282     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
283     if (!MaybeRecord)
284       return MaybeRecord.takeError();
285     switch (MaybeRecord.get()) {
286     default:
287       break; // Default behavior, ignore unknown content.
288     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
289       std::string S;
290       if (convertToString(Record, 0, S))
291         return error("Invalid record");
292       // Check for the i386 and other (x86_64, ARM) conventions
293       if (S.find("__DATA,__objc_catlist") != std::string::npos ||
294           S.find("__OBJC,__category") != std::string::npos)
295         return true;
296       break;
297     }
298     }
299     Record.clear();
300   }
301   llvm_unreachable("Exit infinite loop");
302 }
303 
hasObjCCategory(BitstreamCursor & Stream)304 static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
305   // We expect a number of well-defined blocks, though we don't necessarily
306   // need to understand them all.
307   while (true) {
308     BitstreamEntry Entry;
309     if (Expected<BitstreamEntry> Res = Stream.advance())
310       Entry = std::move(Res.get());
311     else
312       return Res.takeError();
313 
314     switch (Entry.Kind) {
315     case BitstreamEntry::Error:
316       return error("Malformed block");
317     case BitstreamEntry::EndBlock:
318       return false;
319 
320     case BitstreamEntry::SubBlock:
321       if (Entry.ID == bitc::MODULE_BLOCK_ID)
322         return hasObjCCategoryInModule(Stream);
323 
324       // Ignore other sub-blocks.
325       if (Error Err = Stream.SkipBlock())
326         return std::move(Err);
327       continue;
328 
329     case BitstreamEntry::Record:
330       if (Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
331         continue;
332       else
333         return Skipped.takeError();
334     }
335   }
336 }
337 
readModuleTriple(BitstreamCursor & Stream)338 static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
339   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
340     return std::move(Err);
341 
342   SmallVector<uint64_t, 64> Record;
343 
344   std::string Triple;
345 
346   // Read all the records for this module.
347   while (true) {
348     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
349     if (!MaybeEntry)
350       return MaybeEntry.takeError();
351     BitstreamEntry Entry = MaybeEntry.get();
352 
353     switch (Entry.Kind) {
354     case BitstreamEntry::SubBlock: // Handled for us already.
355     case BitstreamEntry::Error:
356       return error("Malformed block");
357     case BitstreamEntry::EndBlock:
358       return Triple;
359     case BitstreamEntry::Record:
360       // The interesting case.
361       break;
362     }
363 
364     // Read a record.
365     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
366     if (!MaybeRecord)
367       return MaybeRecord.takeError();
368     switch (MaybeRecord.get()) {
369     default: break;  // Default behavior, ignore unknown content.
370     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
371       std::string S;
372       if (convertToString(Record, 0, S))
373         return error("Invalid record");
374       Triple = S;
375       break;
376     }
377     }
378     Record.clear();
379   }
380   llvm_unreachable("Exit infinite loop");
381 }
382 
readTriple(BitstreamCursor & Stream)383 static Expected<std::string> readTriple(BitstreamCursor &Stream) {
384   // We expect a number of well-defined blocks, though we don't necessarily
385   // need to understand them all.
386   while (true) {
387     Expected<BitstreamEntry> MaybeEntry = Stream.advance();
388     if (!MaybeEntry)
389       return MaybeEntry.takeError();
390     BitstreamEntry Entry = MaybeEntry.get();
391 
392     switch (Entry.Kind) {
393     case BitstreamEntry::Error:
394       return error("Malformed block");
395     case BitstreamEntry::EndBlock:
396       return "";
397 
398     case BitstreamEntry::SubBlock:
399       if (Entry.ID == bitc::MODULE_BLOCK_ID)
400         return readModuleTriple(Stream);
401 
402       // Ignore other sub-blocks.
403       if (Error Err = Stream.SkipBlock())
404         return std::move(Err);
405       continue;
406 
407     case BitstreamEntry::Record:
408       if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
409         continue;
410       else
411         return Skipped.takeError();
412     }
413   }
414 }
415 
416 namespace {
417 
418 class BitcodeReaderBase {
419 protected:
BitcodeReaderBase(BitstreamCursor Stream,StringRef Strtab)420   BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
421       : Stream(std::move(Stream)), Strtab(Strtab) {
422     this->Stream.setBlockInfo(&BlockInfo);
423   }
424 
425   BitstreamBlockInfo BlockInfo;
426   BitstreamCursor Stream;
427   StringRef Strtab;
428 
429   /// In version 2 of the bitcode we store names of global values and comdats in
430   /// a string table rather than in the VST.
431   bool UseStrtab = false;
432 
433   Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
434 
435   /// If this module uses a string table, pop the reference to the string table
436   /// and return the referenced string and the rest of the record. Otherwise
437   /// just return the record itself.
438   std::pair<StringRef, ArrayRef<uint64_t>>
439   readNameFromStrtab(ArrayRef<uint64_t> Record);
440 
441   bool readBlockInfo();
442 
443   // Contains an arbitrary and optional string identifying the bitcode producer
444   std::string ProducerIdentification;
445 
446   Error error(const Twine &Message);
447 };
448 
449 } // end anonymous namespace
450 
error(const Twine & Message)451 Error BitcodeReaderBase::error(const Twine &Message) {
452   std::string FullMsg = Message.str();
453   if (!ProducerIdentification.empty())
454     FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
455                LLVM_VERSION_STRING "')";
456   return ::error(FullMsg);
457 }
458 
459 Expected<unsigned>
parseVersionRecord(ArrayRef<uint64_t> Record)460 BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
461   if (Record.empty())
462     return error("Invalid record");
463   unsigned ModuleVersion = Record[0];
464   if (ModuleVersion > 2)
465     return error("Invalid value");
466   UseStrtab = ModuleVersion >= 2;
467   return ModuleVersion;
468 }
469 
470 std::pair<StringRef, ArrayRef<uint64_t>>
readNameFromStrtab(ArrayRef<uint64_t> Record)471 BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
472   if (!UseStrtab)
473     return {"", Record};
474   // Invalid reference. Let the caller complain about the record being empty.
475   if (Record[0] + Record[1] > Strtab.size())
476     return {"", {}};
477   return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
478 }
479 
480 namespace {
481 
482 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
483   LLVMContext &Context;
484   Module *TheModule = nullptr;
485   // Next offset to start scanning for lazy parsing of function bodies.
486   uint64_t NextUnreadBit = 0;
487   // Last function offset found in the VST.
488   uint64_t LastFunctionBlockBit = 0;
489   bool SeenValueSymbolTable = false;
490   uint64_t VSTOffset = 0;
491 
492   std::vector<std::string> SectionTable;
493   std::vector<std::string> GCTable;
494 
495   std::vector<Type*> TypeList;
496   DenseMap<Function *, FunctionType *> FunctionTypes;
497   BitcodeReaderValueList ValueList;
498   Optional<MetadataLoader> MDLoader;
499   std::vector<Comdat *> ComdatList;
500   SmallVector<Instruction *, 64> InstructionList;
501 
502   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
503   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
504   std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
505   std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
506   std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
507 
508   /// The set of attributes by index.  Index zero in the file is for null, and
509   /// is thus not represented here.  As such all indices are off by one.
510   std::vector<AttributeList> MAttributes;
511 
512   /// The set of attribute groups.
513   std::map<unsigned, AttributeList> MAttributeGroups;
514 
515   /// While parsing a function body, this is a list of the basic blocks for the
516   /// function.
517   std::vector<BasicBlock*> FunctionBBs;
518 
519   // When reading the module header, this list is populated with functions that
520   // have bodies later in the file.
521   std::vector<Function*> FunctionsWithBodies;
522 
523   // When intrinsic functions are encountered which require upgrading they are
524   // stored here with their replacement function.
525   using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
526   UpdatedIntrinsicMap UpgradedIntrinsics;
527   // Intrinsics which were remangled because of types rename
528   UpdatedIntrinsicMap RemangledIntrinsics;
529 
530   // Several operations happen after the module header has been read, but
531   // before function bodies are processed. This keeps track of whether
532   // we've done this yet.
533   bool SeenFirstFunctionBody = false;
534 
535   /// When function bodies are initially scanned, this map contains info about
536   /// where to find deferred function body in the stream.
537   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
538 
539   /// When Metadata block is initially scanned when parsing the module, we may
540   /// choose to defer parsing of the metadata. This vector contains info about
541   /// which Metadata blocks are deferred.
542   std::vector<uint64_t> DeferredMetadataInfo;
543 
544   /// These are basic blocks forward-referenced by block addresses.  They are
545   /// inserted lazily into functions when they're loaded.  The basic block ID is
546   /// its index into the vector.
547   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
548   std::deque<Function *> BasicBlockFwdRefQueue;
549 
550   /// Indicates that we are using a new encoding for instruction operands where
551   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
552   /// instruction number, for a more compact encoding.  Some instruction
553   /// operands are not relative to the instruction ID: basic block numbers, and
554   /// types. Once the old style function blocks have been phased out, we would
555   /// not need this flag.
556   bool UseRelativeIDs = false;
557 
558   /// True if all functions will be materialized, negating the need to process
559   /// (e.g.) blockaddress forward references.
560   bool WillMaterializeAllForwardRefs = false;
561 
562   bool StripDebugInfo = false;
563   TBAAVerifier TBAAVerifyHelper;
564 
565   std::vector<std::string> BundleTags;
566   SmallVector<SyncScope::ID, 8> SSIDs;
567 
568 public:
569   BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
570                 StringRef ProducerIdentification, LLVMContext &Context);
571 
572   Error materializeForwardReferencedFunctions();
573 
574   Error materialize(GlobalValue *GV) override;
575   Error materializeModule() override;
576   std::vector<StructType *> getIdentifiedStructTypes() const override;
577 
578   /// Main interface to parsing a bitcode buffer.
579   /// \returns true if an error occurred.
580   Error parseBitcodeInto(
581       Module *M, bool ShouldLazyLoadMetadata = false, bool IsImporting = false,
__anon8c0d27130502(StringRef) 582       DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });
583 
584   static uint64_t decodeSignRotatedValue(uint64_t V);
585 
586   /// Materialize any deferred Metadata block.
587   Error materializeMetadata() override;
588 
589   void setStripDebugInfo() override;
590 
591 private:
592   std::vector<StructType *> IdentifiedStructTypes;
593   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
594   StructType *createIdentifiedStructType(LLVMContext &Context);
595 
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.
flattenPointerTypes(Type * Ty)600   Type *flattenPointerTypes(Type *Ty) {
601     return Ty;
602   }
603 
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.
getPointerElementFlatType(Type * Ty)606   Type *getPointerElementFlatType(Type *Ty) {
607     return flattenPointerTypes(cast<PointerType>(Ty)->getElementType());
608   }
609 
610   /// Given a fully structured pointer type, get its element type in
611   /// both fully structured form, and flattened form suitable for use
612   /// in a Value.
getPointerElementTypes(Type * FullTy)613   std::pair<Type *, Type *> getPointerElementTypes(Type *FullTy) {
614     Type *ElTy = cast<PointerType>(FullTy)->getElementType();
615     return std::make_pair(ElTy, flattenPointerTypes(ElTy));
616   }
617 
618   /// Return the flattened type (suitable for use in a Value)
619   /// specified by the given \param ID .
getTypeByID(unsigned ID)620   Type *getTypeByID(unsigned ID) {
621     return flattenPointerTypes(getFullyStructuredTypeByID(ID));
622   }
623 
624   /// Return the fully structured (bitcode-reader internal) type
625   /// corresponding to the given \param ID .
626   Type *getFullyStructuredTypeByID(unsigned ID);
627 
getFnValueByID(unsigned ID,Type * Ty,Type ** FullTy=nullptr)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);
632   }
633 
getFnMetadataByID(unsigned ID)634   Metadata *getFnMetadataByID(unsigned ID) {
635     return MDLoader->getMetadataFwdRefOrLoad(ID);
636   }
637 
getBasicBlock(unsigned ID) const638   BasicBlock *getBasicBlock(unsigned ID) const {
639     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
640     return FunctionBBs[ID];
641   }
642 
getAttributes(unsigned i) const643   AttributeList getAttributes(unsigned i) const {
644     if (i-1 < MAttributes.size())
645       return MAttributes[i-1];
646     return AttributeList();
647   }
648 
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
651   /// failure.
getValueTypePair(const SmallVectorImpl<uint64_t> & Record,unsigned & Slot,unsigned InstNum,Value * & ResVal,Type ** FullTy=nullptr)652   bool getValueTypePair(const 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.
658     if (UseRelativeIDs)
659       ValNo = InstNum - ValNo;
660     if (ValNo < InstNum) {
661       // If this is not a forward reference, just return the value we already
662       // have.
663       ResVal = getFnValueByID(ValNo, nullptr, FullTy);
664       return ResVal == nullptr;
665     }
666     if (Slot == Record.size())
667       return true;
668 
669     unsigned TypeNo = (unsigned)Record[Slot++];
670     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
671     if (FullTy)
672       *FullTy = getFullyStructuredTypeByID(TypeNo);
673     return ResVal == nullptr;
674   }
675 
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.
popValue(const SmallVectorImpl<uint64_t> & Record,unsigned & Slot,unsigned InstNum,Type * Ty,Value * & ResVal)679   bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
680                 unsigned InstNum, Type *Ty, Value *&ResVal) {
681     if (getValue(Record, Slot, InstNum, Ty, ResVal))
682       return true;
683     // All values currently take a single record slot.
684     ++Slot;
685     return false;
686   }
687 
688   /// Like popValue, but does not increment the Slot number.
getValue(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty,Value * & ResVal)689   bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
690                 unsigned InstNum, Type *Ty, Value *&ResVal) {
691     ResVal = getValue(Record, Slot, InstNum, Ty);
692     return ResVal == nullptr;
693   }
694 
695   /// Version of getValue that returns ResVal directly, or 0 if there is an
696   /// error.
getValue(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty)697   Value *getValue(const 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.
702     if (UseRelativeIDs)
703       ValNo = InstNum - ValNo;
704     return getFnValueByID(ValNo, Ty);
705   }
706 
707   /// Like getValue, but decodes signed VBRs.
getValueSigned(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty)708   Value *getValueSigned(const 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.
713     if (UseRelativeIDs)
714       ValNo = InstNum - ValNo;
715     return getFnValueByID(ValNo, Ty);
716   }
717 
718   /// Upgrades old-style typeless byval or sret attributes by adding the
719   /// corresponding argument's pointee type.
720   void propagateByValSRetTypes(CallBase *CB, ArrayRef<Type *> ArgsFullTys);
721 
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, MaybeAlign &Alignment);
726   Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
727   Error parseModule(
728       uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
__anon8c0d27130602(StringRef) 729       DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });
730 
731   Error parseComdatRecord(ArrayRef<uint64_t> Record);
732   Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
733   Error parseFunctionRecord(ArrayRef<uint64_t> Record);
734   Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
735                                         ArrayRef<uint64_t> Record);
736 
737   Error parseAttributeBlock();
738   Error parseAttributeGroupBlock();
739   Error parseTypeTable();
740   Error parseTypeTableBody();
741   Error parseOperandBundleTags();
742   Error parseSyncScopeNames();
743 
744   Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
745                                 unsigned NameIndex, Triple &TT);
746   void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
747                                ArrayRef<uint64_t> Record);
748   Error parseValueSymbolTable(uint64_t Offset = 0);
749   Error parseGlobalValueSymbolTable();
750   Error parseConstants();
751   Error rememberAndSkipFunctionBodies();
752   Error rememberAndSkipFunctionBody();
753   /// Save the positions of the Metadata blocks and skip parsing the blocks.
754   Error rememberAndSkipMetadata();
755   Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
756   Error parseFunctionBody(Function *F);
757   Error globalCleanup();
758   Error resolveGlobalAndIndirectSymbolInits();
759   Error parseUseLists();
760   Error findFunctionInStream(
761       Function *F,
762       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
763 
764   SyncScope::ID getDecodedSyncScopeID(unsigned Val);
765 };
766 
767 /// Class to manage reading and parsing function summary index bitcode
768 /// files/sections.
769 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
770   /// The module index built during parsing.
771   ModuleSummaryIndex &TheIndex;
772 
773   /// Indicates whether we have encountered a global value summary section
774   /// yet during parsing.
775   bool SeenGlobalValSummary = false;
776 
777   /// Indicates whether we have already parsed the VST, used for error checking.
778   bool SeenValueSymbolTable = false;
779 
780   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
781   /// Used to enable on-demand parsing of the VST.
782   uint64_t VSTOffset = 0;
783 
784   // Map to save ValueId to ValueInfo association that was recorded in the
785   // ValueSymbolTable. It is used after the VST is parsed to convert
786   // call graph edges read from the function summary from referencing
787   // callees by their ValueId to using the ValueInfo instead, which is how
788   // they are recorded in the summary index being built.
789   // We save a GUID which refers to the same global as the ValueInfo, but
790   // ignoring the linkage, i.e. for values other than local linkage they are
791   // identical.
792   DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
793       ValueIdToValueInfoMap;
794 
795   /// Map populated during module path string table parsing, from the
796   /// module ID to a string reference owned by the index's module
797   /// path string table, used to correlate with combined index
798   /// summary records.
799   DenseMap<uint64_t, StringRef> ModuleIdMap;
800 
801   /// Original source file name recorded in a bitcode record.
802   std::string SourceFileName;
803 
804   /// The string identifier given to this module by the client, normally the
805   /// path to the bitcode file.
806   StringRef ModulePath;
807 
808   /// For per-module summary indexes, the unique numerical identifier given to
809   /// this module by the client.
810   unsigned ModuleId;
811 
812 public:
813   ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
814                                   ModuleSummaryIndex &TheIndex,
815                                   StringRef ModulePath, unsigned ModuleId);
816 
817   Error parseModule();
818 
819 private:
820   void setValueGUID(uint64_t ValueID, StringRef ValueName,
821                     GlobalValue::LinkageTypes Linkage,
822                     StringRef SourceFileName);
823   Error parseValueSymbolTable(
824       uint64_t Offset,
825       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
826   std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
827   std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
828                                                     bool IsOldProfileFormat,
829                                                     bool HasProfile,
830                                                     bool HasRelBF);
831   Error parseEntireSummary(unsigned ID);
832   Error parseModuleStringTable();
833   void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
834   void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
835                                        TypeIdCompatibleVtableInfo &TypeId);
836   std::vector<FunctionSummary::ParamAccess>
837   parseParamAccesses(ArrayRef<uint64_t> Record);
838 
839   std::pair<ValueInfo, GlobalValue::GUID>
840   getValueInfoFromValueId(unsigned ValueId);
841 
842   void addThisModule();
843   ModuleSummaryIndex::ModuleInfo *getThisModule();
844 };
845 
846 } // end anonymous namespace
847 
errorToErrorCodeAndEmitErrors(LLVMContext & Ctx,Error Err)848 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
849                                                     Error Err) {
850   if (Err) {
851     std::error_code EC;
852     handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
853       EC = EIB.convertToErrorCode();
854       Ctx.emitError(EIB.message());
855     });
856     return EC;
857   }
858   return std::error_code();
859 }
860 
BitcodeReader(BitstreamCursor Stream,StringRef Strtab,StringRef ProducerIdentification,LLVMContext & Context)861 BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
862                              StringRef ProducerIdentification,
863                              LLVMContext &Context)
864     : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
865       ValueList(Context, Stream.SizeInBytes()) {
866   this->ProducerIdentification = std::string(ProducerIdentification);
867 }
868 
materializeForwardReferencedFunctions()869 Error BitcodeReader::materializeForwardReferencedFunctions() {
870   if (WillMaterializeAllForwardRefs)
871     return Error::success();
872 
873   // Prevent recursion.
874   WillMaterializeAllForwardRefs = true;
875 
876   while (!BasicBlockFwdRefQueue.empty()) {
877     Function *F = BasicBlockFwdRefQueue.front();
878     BasicBlockFwdRefQueue.pop_front();
879     assert(F && "Expected valid function");
880     if (!BasicBlockFwdRefs.count(F))
881       // Already materialized.
882       continue;
883 
884     // Check for a function that isn't materializable to prevent an infinite
885     // loop.  When parsing a blockaddress stored in a global variable, there
886     // isn't a trivial way to check if a function will have a body without a
887     // linear search through FunctionsWithBodies, so just check it here.
888     if (!F->isMaterializable())
889       return error("Never resolved function from blockaddress");
890 
891     // Try to materialize F.
892     if (Error Err = materialize(F))
893       return Err;
894   }
895   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
896 
897   // Reset state.
898   WillMaterializeAllForwardRefs = false;
899   return Error::success();
900 }
901 
902 //===----------------------------------------------------------------------===//
903 //  Helper functions to implement forward reference resolution, etc.
904 //===----------------------------------------------------------------------===//
905 
hasImplicitComdat(size_t Val)906 static bool hasImplicitComdat(size_t Val) {
907   switch (Val) {
908   default:
909     return false;
910   case 1:  // Old WeakAnyLinkage
911   case 4:  // Old LinkOnceAnyLinkage
912   case 10: // Old WeakODRLinkage
913   case 11: // Old LinkOnceODRLinkage
914     return true;
915   }
916 }
917 
getDecodedLinkage(unsigned Val)918 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
919   switch (Val) {
920   default: // Map unknown/new linkages to external
921   case 0:
922     return GlobalValue::ExternalLinkage;
923   case 2:
924     return GlobalValue::AppendingLinkage;
925   case 3:
926     return GlobalValue::InternalLinkage;
927   case 5:
928     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
929   case 6:
930     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
931   case 7:
932     return GlobalValue::ExternalWeakLinkage;
933   case 8:
934     return GlobalValue::CommonLinkage;
935   case 9:
936     return GlobalValue::PrivateLinkage;
937   case 12:
938     return GlobalValue::AvailableExternallyLinkage;
939   case 13:
940     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
941   case 14:
942     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
943   case 15:
944     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
945   case 1: // Old value with implicit comdat.
946   case 16:
947     return GlobalValue::WeakAnyLinkage;
948   case 10: // Old value with implicit comdat.
949   case 17:
950     return GlobalValue::WeakODRLinkage;
951   case 4: // Old value with implicit comdat.
952   case 18:
953     return GlobalValue::LinkOnceAnyLinkage;
954   case 11: // Old value with implicit comdat.
955   case 19:
956     return GlobalValue::LinkOnceODRLinkage;
957   }
958 }
959 
getDecodedFFlags(uint64_t RawFlags)960 static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
961   FunctionSummary::FFlags Flags;
962   Flags.ReadNone = RawFlags & 0x1;
963   Flags.ReadOnly = (RawFlags >> 1) & 0x1;
964   Flags.NoRecurse = (RawFlags >> 2) & 0x1;
965   Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
966   Flags.NoInline = (RawFlags >> 4) & 0x1;
967   Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
968   return Flags;
969 }
970 
971 // Decode the flags for GlobalValue in the summary. The bits for each attribute:
972 //
973 // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
974 // visibility: [8, 10).
getDecodedGVSummaryFlags(uint64_t RawFlags,uint64_t Version)975 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
976                                                             uint64_t Version) {
977   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
978   // like getDecodedLinkage() above. Any future change to the linkage enum and
979   // to getDecodedLinkage() will need to be taken into account here as above.
980   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
981   auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
982   RawFlags = RawFlags >> 4;
983   bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
984   // The Live flag wasn't introduced until version 3. For dead stripping
985   // to work correctly on earlier versions, we must conservatively treat all
986   // values as live.
987   bool Live = (RawFlags & 0x2) || Version < 3;
988   bool Local = (RawFlags & 0x4);
989   bool AutoHide = (RawFlags & 0x8);
990 
991   return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
992                                      Live, Local, AutoHide);
993 }
994 
995 // Decode the flags for GlobalVariable in the summary
getDecodedGVarFlags(uint64_t RawFlags)996 static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
997   return GlobalVarSummary::GVarFlags(
998       (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
999       (RawFlags & 0x4) ? true : false,
1000       (GlobalObject::VCallVisibility)(RawFlags >> 3));
1001 }
1002 
getDecodedVisibility(unsigned Val)1003 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
1004   switch (Val) {
1005   default: // Map unknown visibilities to default.
1006   case 0: return GlobalValue::DefaultVisibility;
1007   case 1: return GlobalValue::HiddenVisibility;
1008   case 2: return GlobalValue::ProtectedVisibility;
1009   }
1010 }
1011 
1012 static GlobalValue::DLLStorageClassTypes
getDecodedDLLStorageClass(unsigned Val)1013 getDecodedDLLStorageClass(unsigned Val) {
1014   switch (Val) {
1015   default: // Map unknown values to default.
1016   case 0: return GlobalValue::DefaultStorageClass;
1017   case 1: return GlobalValue::DLLImportStorageClass;
1018   case 2: return GlobalValue::DLLExportStorageClass;
1019   }
1020 }
1021 
getDecodedDSOLocal(unsigned Val)1022 static bool getDecodedDSOLocal(unsigned Val) {
1023   switch(Val) {
1024   default: // Map unknown values to preemptable.
1025   case 0:  return false;
1026   case 1:  return true;
1027   }
1028 }
1029 
getDecodedThreadLocalMode(unsigned Val)1030 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
1031   switch (Val) {
1032     case 0: return GlobalVariable::NotThreadLocal;
1033     default: // Map unknown non-zero value to general dynamic.
1034     case 1: return GlobalVariable::GeneralDynamicTLSModel;
1035     case 2: return GlobalVariable::LocalDynamicTLSModel;
1036     case 3: return GlobalVariable::InitialExecTLSModel;
1037     case 4: return GlobalVariable::LocalExecTLSModel;
1038   }
1039 }
1040 
getDecodedUnnamedAddrType(unsigned Val)1041 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
1042   switch (Val) {
1043     default: // Map unknown to UnnamedAddr::None.
1044     case 0: return GlobalVariable::UnnamedAddr::None;
1045     case 1: return GlobalVariable::UnnamedAddr::Global;
1046     case 2: return GlobalVariable::UnnamedAddr::Local;
1047   }
1048 }
1049 
getDecodedCastOpcode(unsigned Val)1050 static int getDecodedCastOpcode(unsigned Val) {
1051   switch (Val) {
1052   default: return -1;
1053   case bitc::CAST_TRUNC   : return Instruction::Trunc;
1054   case bitc::CAST_ZEXT    : return Instruction::ZExt;
1055   case bitc::CAST_SEXT    : return Instruction::SExt;
1056   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
1057   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
1058   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
1059   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
1060   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
1061   case bitc::CAST_FPEXT   : return Instruction::FPExt;
1062   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
1063   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
1064   case bitc::CAST_BITCAST : return Instruction::BitCast;
1065   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
1066   }
1067 }
1068 
getDecodedUnaryOpcode(unsigned Val,Type * Ty)1069 static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
1070   bool IsFP = Ty->isFPOrFPVectorTy();
1071   // UnOps are only valid for int/fp or vector of int/fp types
1072   if (!IsFP && !Ty->isIntOrIntVectorTy())
1073     return -1;
1074 
1075   switch (Val) {
1076   default:
1077     return -1;
1078   case bitc::UNOP_FNEG:
1079     return IsFP ? Instruction::FNeg : -1;
1080   }
1081 }
1082 
getDecodedBinaryOpcode(unsigned Val,Type * Ty)1083 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
1084   bool IsFP = Ty->isFPOrFPVectorTy();
1085   // BinOps are only valid for int/fp or vector of int/fp types
1086   if (!IsFP && !Ty->isIntOrIntVectorTy())
1087     return -1;
1088 
1089   switch (Val) {
1090   default:
1091     return -1;
1092   case bitc::BINOP_ADD:
1093     return IsFP ? Instruction::FAdd : Instruction::Add;
1094   case bitc::BINOP_SUB:
1095     return IsFP ? Instruction::FSub : Instruction::Sub;
1096   case bitc::BINOP_MUL:
1097     return IsFP ? Instruction::FMul : Instruction::Mul;
1098   case bitc::BINOP_UDIV:
1099     return IsFP ? -1 : Instruction::UDiv;
1100   case bitc::BINOP_SDIV:
1101     return IsFP ? Instruction::FDiv : Instruction::SDiv;
1102   case bitc::BINOP_UREM:
1103     return IsFP ? -1 : Instruction::URem;
1104   case bitc::BINOP_SREM:
1105     return IsFP ? Instruction::FRem : Instruction::SRem;
1106   case bitc::BINOP_SHL:
1107     return IsFP ? -1 : Instruction::Shl;
1108   case bitc::BINOP_LSHR:
1109     return IsFP ? -1 : Instruction::LShr;
1110   case bitc::BINOP_ASHR:
1111     return IsFP ? -1 : Instruction::AShr;
1112   case bitc::BINOP_AND:
1113     return IsFP ? -1 : Instruction::And;
1114   case bitc::BINOP_OR:
1115     return IsFP ? -1 : Instruction::Or;
1116   case bitc::BINOP_XOR:
1117     return IsFP ? -1 : Instruction::Xor;
1118   }
1119 }
1120 
getDecodedRMWOperation(unsigned Val)1121 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
1122   switch (Val) {
1123   default: return AtomicRMWInst::BAD_BINOP;
1124   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1125   case bitc::RMW_ADD: return AtomicRMWInst::Add;
1126   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1127   case bitc::RMW_AND: return AtomicRMWInst::And;
1128   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1129   case bitc::RMW_OR: return AtomicRMWInst::Or;
1130   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1131   case bitc::RMW_MAX: return AtomicRMWInst::Max;
1132   case bitc::RMW_MIN: return AtomicRMWInst::Min;
1133   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1134   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1135   case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1136   case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1137   }
1138 }
1139 
getDecodedOrdering(unsigned Val)1140 static AtomicOrdering getDecodedOrdering(unsigned Val) {
1141   switch (Val) {
1142   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1143   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1144   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1145   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1146   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1147   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1148   default: // Map unknown orderings to sequentially-consistent.
1149   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1150   }
1151 }
1152 
getDecodedComdatSelectionKind(unsigned Val)1153 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1154   switch (Val) {
1155   default: // Map unknown selection kinds to any.
1156   case bitc::COMDAT_SELECTION_KIND_ANY:
1157     return Comdat::Any;
1158   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1159     return Comdat::ExactMatch;
1160   case bitc::COMDAT_SELECTION_KIND_LARGEST:
1161     return Comdat::Largest;
1162   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1163     return Comdat::NoDuplicates;
1164   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1165     return Comdat::SameSize;
1166   }
1167 }
1168 
getDecodedFastMathFlags(unsigned Val)1169 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1170   FastMathFlags FMF;
1171   if (0 != (Val & bitc::UnsafeAlgebra))
1172     FMF.setFast();
1173   if (0 != (Val & bitc::AllowReassoc))
1174     FMF.setAllowReassoc();
1175   if (0 != (Val & bitc::NoNaNs))
1176     FMF.setNoNaNs();
1177   if (0 != (Val & bitc::NoInfs))
1178     FMF.setNoInfs();
1179   if (0 != (Val & bitc::NoSignedZeros))
1180     FMF.setNoSignedZeros();
1181   if (0 != (Val & bitc::AllowReciprocal))
1182     FMF.setAllowReciprocal();
1183   if (0 != (Val & bitc::AllowContract))
1184     FMF.setAllowContract(true);
1185   if (0 != (Val & bitc::ApproxFunc))
1186     FMF.setApproxFunc();
1187   return FMF;
1188 }
1189 
upgradeDLLImportExportLinkage(GlobalValue * GV,unsigned Val)1190 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1191   switch (Val) {
1192   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1193   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1194   }
1195 }
1196 
getFullyStructuredTypeByID(unsigned ID)1197 Type *BitcodeReader::getFullyStructuredTypeByID(unsigned ID) {
1198   // The type table size is always specified correctly.
1199   if (ID >= TypeList.size())
1200     return nullptr;
1201 
1202   if (Type *Ty = TypeList[ID])
1203     return Ty;
1204 
1205   // If we have a forward reference, the only possible case is when it is to a
1206   // named struct.  Just create a placeholder for now.
1207   return TypeList[ID] = createIdentifiedStructType(Context);
1208 }
1209 
createIdentifiedStructType(LLVMContext & Context,StringRef Name)1210 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1211                                                       StringRef Name) {
1212   auto *Ret = StructType::create(Context, Name);
1213   IdentifiedStructTypes.push_back(Ret);
1214   return Ret;
1215 }
1216 
createIdentifiedStructType(LLVMContext & Context)1217 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1218   auto *Ret = StructType::create(Context);
1219   IdentifiedStructTypes.push_back(Ret);
1220   return Ret;
1221 }
1222 
1223 //===----------------------------------------------------------------------===//
1224 //  Functions for parsing blocks from the bitcode file
1225 //===----------------------------------------------------------------------===//
1226 
getRawAttributeMask(Attribute::AttrKind Val)1227 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1228   switch (Val) {
1229   case Attribute::EndAttrKinds:
1230   case Attribute::EmptyKey:
1231   case Attribute::TombstoneKey:
1232     llvm_unreachable("Synthetic enumerators which should never get here");
1233 
1234   case Attribute::None:            return 0;
1235   case Attribute::ZExt:            return 1 << 0;
1236   case Attribute::SExt:            return 1 << 1;
1237   case Attribute::NoReturn:        return 1 << 2;
1238   case Attribute::InReg:           return 1 << 3;
1239   case Attribute::StructRet:       return 1 << 4;
1240   case Attribute::NoUnwind:        return 1 << 5;
1241   case Attribute::NoAlias:         return 1 << 6;
1242   case Attribute::ByVal:           return 1 << 7;
1243   case Attribute::Nest:            return 1 << 8;
1244   case Attribute::ReadNone:        return 1 << 9;
1245   case Attribute::ReadOnly:        return 1 << 10;
1246   case Attribute::NoInline:        return 1 << 11;
1247   case Attribute::AlwaysInline:    return 1 << 12;
1248   case Attribute::OptimizeForSize: return 1 << 13;
1249   case Attribute::StackProtect:    return 1 << 14;
1250   case Attribute::StackProtectReq: return 1 << 15;
1251   case Attribute::Alignment:       return 31 << 16;
1252   case Attribute::NoCapture:       return 1 << 21;
1253   case Attribute::NoRedZone:       return 1 << 22;
1254   case Attribute::NoImplicitFloat: return 1 << 23;
1255   case Attribute::Naked:           return 1 << 24;
1256   case Attribute::InlineHint:      return 1 << 25;
1257   case Attribute::StackAlignment:  return 7 << 26;
1258   case Attribute::ReturnsTwice:    return 1 << 29;
1259   case Attribute::UWTable:         return 1 << 30;
1260   case Attribute::NonLazyBind:     return 1U << 31;
1261   case Attribute::SanitizeAddress: return 1ULL << 32;
1262   case Attribute::MinSize:         return 1ULL << 33;
1263   case Attribute::NoDuplicate:     return 1ULL << 34;
1264   case Attribute::StackProtectStrong: return 1ULL << 35;
1265   case Attribute::SanitizeThread:  return 1ULL << 36;
1266   case Attribute::SanitizeMemory:  return 1ULL << 37;
1267   case Attribute::NoBuiltin:       return 1ULL << 38;
1268   case Attribute::Returned:        return 1ULL << 39;
1269   case Attribute::Cold:            return 1ULL << 40;
1270   case Attribute::Builtin:         return 1ULL << 41;
1271   case Attribute::OptimizeNone:    return 1ULL << 42;
1272   case Attribute::InAlloca:        return 1ULL << 43;
1273   case Attribute::NonNull:         return 1ULL << 44;
1274   case Attribute::JumpTable:       return 1ULL << 45;
1275   case Attribute::Convergent:      return 1ULL << 46;
1276   case Attribute::SafeStack:       return 1ULL << 47;
1277   case Attribute::NoRecurse:       return 1ULL << 48;
1278   case Attribute::InaccessibleMemOnly:         return 1ULL << 49;
1279   case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1280   case Attribute::SwiftSelf:       return 1ULL << 51;
1281   case Attribute::SwiftError:      return 1ULL << 52;
1282   case Attribute::WriteOnly:       return 1ULL << 53;
1283   case Attribute::Speculatable:    return 1ULL << 54;
1284   case Attribute::StrictFP:        return 1ULL << 55;
1285   case Attribute::SanitizeHWAddress: return 1ULL << 56;
1286   case Attribute::NoCfCheck:       return 1ULL << 57;
1287   case Attribute::OptForFuzzing:   return 1ULL << 58;
1288   case Attribute::ShadowCallStack: return 1ULL << 59;
1289   case Attribute::SpeculativeLoadHardening:
1290     return 1ULL << 60;
1291   case Attribute::ImmArg:
1292     return 1ULL << 61;
1293   case Attribute::WillReturn:
1294     return 1ULL << 62;
1295   case Attribute::NoFree:
1296     return 1ULL << 63;
1297   default:
1298     // Other attributes are not supported in the raw format,
1299     // as we ran out of space.
1300     return 0;
1301   }
1302   llvm_unreachable("Unsupported attribute type");
1303 }
1304 
addRawAttributeValue(AttrBuilder & B,uint64_t Val)1305 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1306   if (!Val) return;
1307 
1308   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1309        I = Attribute::AttrKind(I + 1)) {
1310     if (uint64_t A = (Val & getRawAttributeMask(I))) {
1311       if (I == Attribute::Alignment)
1312         B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1313       else if (I == Attribute::StackAlignment)
1314         B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1315       else
1316         B.addAttribute(I);
1317     }
1318   }
1319 }
1320 
1321 /// This fills an AttrBuilder object with the LLVM attributes that have
1322 /// been decoded from the given integer. This function must stay in sync with
1323 /// 'encodeLLVMAttributesForBitcode'.
decodeLLVMAttributesForBitcode(AttrBuilder & B,uint64_t EncodedAttrs)1324 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1325                                            uint64_t EncodedAttrs) {
1326   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
1327   // the bits above 31 down by 11 bits.
1328   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1329   assert((!Alignment || isPowerOf2_32(Alignment)) &&
1330          "Alignment must be a power of two.");
1331 
1332   if (Alignment)
1333     B.addAlignmentAttr(Alignment);
1334   addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1335                           (EncodedAttrs & 0xffff));
1336 }
1337 
parseAttributeBlock()1338 Error BitcodeReader::parseAttributeBlock() {
1339   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1340     return Err;
1341 
1342   if (!MAttributes.empty())
1343     return error("Invalid multiple blocks");
1344 
1345   SmallVector<uint64_t, 64> Record;
1346 
1347   SmallVector<AttributeList, 8> Attrs;
1348 
1349   // Read all the records.
1350   while (true) {
1351     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1352     if (!MaybeEntry)
1353       return MaybeEntry.takeError();
1354     BitstreamEntry Entry = MaybeEntry.get();
1355 
1356     switch (Entry.Kind) {
1357     case BitstreamEntry::SubBlock: // Handled for us already.
1358     case BitstreamEntry::Error:
1359       return error("Malformed block");
1360     case BitstreamEntry::EndBlock:
1361       return Error::success();
1362     case BitstreamEntry::Record:
1363       // The interesting case.
1364       break;
1365     }
1366 
1367     // Read a record.
1368     Record.clear();
1369     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1370     if (!MaybeRecord)
1371       return MaybeRecord.takeError();
1372     switch (MaybeRecord.get()) {
1373     default:  // Default behavior: ignore.
1374       break;
1375     case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1376       // Deprecated, but still needed to read old bitcode files.
1377       if (Record.size() & 1)
1378         return error("Invalid record");
1379 
1380       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1381         AttrBuilder B;
1382         decodeLLVMAttributesForBitcode(B, Record[i+1]);
1383         Attrs.push_back(AttributeList::get(Context, Record[i], B));
1384       }
1385 
1386       MAttributes.push_back(AttributeList::get(Context, Attrs));
1387       Attrs.clear();
1388       break;
1389     case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1390       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1391         Attrs.push_back(MAttributeGroups[Record[i]]);
1392 
1393       MAttributes.push_back(AttributeList::get(Context, Attrs));
1394       Attrs.clear();
1395       break;
1396     }
1397   }
1398 }
1399 
1400 // Returns Attribute::None on unrecognized codes.
getAttrFromCode(uint64_t Code)1401 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1402   switch (Code) {
1403   default:
1404     return Attribute::None;
1405   case bitc::ATTR_KIND_ALIGNMENT:
1406     return Attribute::Alignment;
1407   case bitc::ATTR_KIND_ALWAYS_INLINE:
1408     return Attribute::AlwaysInline;
1409   case bitc::ATTR_KIND_ARGMEMONLY:
1410     return Attribute::ArgMemOnly;
1411   case bitc::ATTR_KIND_BUILTIN:
1412     return Attribute::Builtin;
1413   case bitc::ATTR_KIND_BY_VAL:
1414     return Attribute::ByVal;
1415   case bitc::ATTR_KIND_IN_ALLOCA:
1416     return Attribute::InAlloca;
1417   case bitc::ATTR_KIND_COLD:
1418     return Attribute::Cold;
1419   case bitc::ATTR_KIND_CONVERGENT:
1420     return Attribute::Convergent;
1421   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1422     return Attribute::InaccessibleMemOnly;
1423   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1424     return Attribute::InaccessibleMemOrArgMemOnly;
1425   case bitc::ATTR_KIND_INLINE_HINT:
1426     return Attribute::InlineHint;
1427   case bitc::ATTR_KIND_IN_REG:
1428     return Attribute::InReg;
1429   case bitc::ATTR_KIND_JUMP_TABLE:
1430     return Attribute::JumpTable;
1431   case bitc::ATTR_KIND_MIN_SIZE:
1432     return Attribute::MinSize;
1433   case bitc::ATTR_KIND_NAKED:
1434     return Attribute::Naked;
1435   case bitc::ATTR_KIND_NEST:
1436     return Attribute::Nest;
1437   case bitc::ATTR_KIND_NO_ALIAS:
1438     return Attribute::NoAlias;
1439   case bitc::ATTR_KIND_NO_BUILTIN:
1440     return Attribute::NoBuiltin;
1441   case bitc::ATTR_KIND_NO_CALLBACK:
1442     return Attribute::NoCallback;
1443   case bitc::ATTR_KIND_NO_CAPTURE:
1444     return Attribute::NoCapture;
1445   case bitc::ATTR_KIND_NO_DUPLICATE:
1446     return Attribute::NoDuplicate;
1447   case bitc::ATTR_KIND_NOFREE:
1448     return Attribute::NoFree;
1449   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1450     return Attribute::NoImplicitFloat;
1451   case bitc::ATTR_KIND_NO_INLINE:
1452     return Attribute::NoInline;
1453   case bitc::ATTR_KIND_NO_RECURSE:
1454     return Attribute::NoRecurse;
1455   case bitc::ATTR_KIND_NO_MERGE:
1456     return Attribute::NoMerge;
1457   case bitc::ATTR_KIND_NON_LAZY_BIND:
1458     return Attribute::NonLazyBind;
1459   case bitc::ATTR_KIND_NON_NULL:
1460     return Attribute::NonNull;
1461   case bitc::ATTR_KIND_DEREFERENCEABLE:
1462     return Attribute::Dereferenceable;
1463   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1464     return Attribute::DereferenceableOrNull;
1465   case bitc::ATTR_KIND_ALLOC_SIZE:
1466     return Attribute::AllocSize;
1467   case bitc::ATTR_KIND_NO_RED_ZONE:
1468     return Attribute::NoRedZone;
1469   case bitc::ATTR_KIND_NO_RETURN:
1470     return Attribute::NoReturn;
1471   case bitc::ATTR_KIND_NOSYNC:
1472     return Attribute::NoSync;
1473   case bitc::ATTR_KIND_NOCF_CHECK:
1474     return Attribute::NoCfCheck;
1475   case bitc::ATTR_KIND_NO_UNWIND:
1476     return Attribute::NoUnwind;
1477   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
1478     return Attribute::NullPointerIsValid;
1479   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
1480     return Attribute::OptForFuzzing;
1481   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1482     return Attribute::OptimizeForSize;
1483   case bitc::ATTR_KIND_OPTIMIZE_NONE:
1484     return Attribute::OptimizeNone;
1485   case bitc::ATTR_KIND_READ_NONE:
1486     return Attribute::ReadNone;
1487   case bitc::ATTR_KIND_READ_ONLY:
1488     return Attribute::ReadOnly;
1489   case bitc::ATTR_KIND_RETURNED:
1490     return Attribute::Returned;
1491   case bitc::ATTR_KIND_RETURNS_TWICE:
1492     return Attribute::ReturnsTwice;
1493   case bitc::ATTR_KIND_S_EXT:
1494     return Attribute::SExt;
1495   case bitc::ATTR_KIND_SPECULATABLE:
1496     return Attribute::Speculatable;
1497   case bitc::ATTR_KIND_STACK_ALIGNMENT:
1498     return Attribute::StackAlignment;
1499   case bitc::ATTR_KIND_STACK_PROTECT:
1500     return Attribute::StackProtect;
1501   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1502     return Attribute::StackProtectReq;
1503   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1504     return Attribute::StackProtectStrong;
1505   case bitc::ATTR_KIND_SAFESTACK:
1506     return Attribute::SafeStack;
1507   case bitc::ATTR_KIND_SHADOWCALLSTACK:
1508     return Attribute::ShadowCallStack;
1509   case bitc::ATTR_KIND_STRICT_FP:
1510     return Attribute::StrictFP;
1511   case bitc::ATTR_KIND_STRUCT_RET:
1512     return Attribute::StructRet;
1513   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1514     return Attribute::SanitizeAddress;
1515   case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
1516     return Attribute::SanitizeHWAddress;
1517   case bitc::ATTR_KIND_SANITIZE_THREAD:
1518     return Attribute::SanitizeThread;
1519   case bitc::ATTR_KIND_SANITIZE_MEMORY:
1520     return Attribute::SanitizeMemory;
1521   case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
1522     return Attribute::SpeculativeLoadHardening;
1523   case bitc::ATTR_KIND_SWIFT_ERROR:
1524     return Attribute::SwiftError;
1525   case bitc::ATTR_KIND_SWIFT_SELF:
1526     return Attribute::SwiftSelf;
1527   case bitc::ATTR_KIND_SWIFT_ASYNC:
1528     return Attribute::SwiftAsync;
1529   case bitc::ATTR_KIND_UW_TABLE:
1530     return Attribute::UWTable;
1531   case bitc::ATTR_KIND_VSCALE_RANGE:
1532     return Attribute::VScaleRange;
1533   case bitc::ATTR_KIND_WILLRETURN:
1534     return Attribute::WillReturn;
1535   case bitc::ATTR_KIND_WRITEONLY:
1536     return Attribute::WriteOnly;
1537   case bitc::ATTR_KIND_Z_EXT:
1538     return Attribute::ZExt;
1539   case bitc::ATTR_KIND_IMMARG:
1540     return Attribute::ImmArg;
1541   case bitc::ATTR_KIND_SANITIZE_MEMTAG:
1542     return Attribute::SanitizeMemTag;
1543   case bitc::ATTR_KIND_PREALLOCATED:
1544     return Attribute::Preallocated;
1545   case bitc::ATTR_KIND_NOUNDEF:
1546     return Attribute::NoUndef;
1547   case bitc::ATTR_KIND_BYREF:
1548     return Attribute::ByRef;
1549   case bitc::ATTR_KIND_MUSTPROGRESS:
1550     return Attribute::MustProgress;
1551   case bitc::ATTR_KIND_HOT:
1552     return Attribute::Hot;
1553   }
1554 }
1555 
parseAlignmentValue(uint64_t Exponent,MaybeAlign & Alignment)1556 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1557                                          MaybeAlign &Alignment) {
1558   // Note: Alignment in bitcode files is incremented by 1, so that zero
1559   // can be used for default alignment.
1560   if (Exponent > Value::MaxAlignmentExponent + 1)
1561     return error("Invalid alignment value");
1562   Alignment = decodeMaybeAlign(Exponent);
1563   return Error::success();
1564 }
1565 
parseAttrKind(uint64_t Code,Attribute::AttrKind * Kind)1566 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
1567   *Kind = getAttrFromCode(Code);
1568   if (*Kind == Attribute::None)
1569     return error("Unknown attribute kind (" + Twine(Code) + ")");
1570   return Error::success();
1571 }
1572 
parseAttributeGroupBlock()1573 Error BitcodeReader::parseAttributeGroupBlock() {
1574   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1575     return Err;
1576 
1577   if (!MAttributeGroups.empty())
1578     return error("Invalid multiple blocks");
1579 
1580   SmallVector<uint64_t, 64> Record;
1581 
1582   // Read all the records.
1583   while (true) {
1584     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1585     if (!MaybeEntry)
1586       return MaybeEntry.takeError();
1587     BitstreamEntry Entry = MaybeEntry.get();
1588 
1589     switch (Entry.Kind) {
1590     case BitstreamEntry::SubBlock: // Handled for us already.
1591     case BitstreamEntry::Error:
1592       return error("Malformed block");
1593     case BitstreamEntry::EndBlock:
1594       return Error::success();
1595     case BitstreamEntry::Record:
1596       // The interesting case.
1597       break;
1598     }
1599 
1600     // Read a record.
1601     Record.clear();
1602     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1603     if (!MaybeRecord)
1604       return MaybeRecord.takeError();
1605     switch (MaybeRecord.get()) {
1606     default:  // Default behavior: ignore.
1607       break;
1608     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1609       if (Record.size() < 3)
1610         return error("Invalid record");
1611 
1612       uint64_t GrpID = Record[0];
1613       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1614 
1615       AttrBuilder B;
1616       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1617         if (Record[i] == 0) {        // Enum attribute
1618           Attribute::AttrKind Kind;
1619           if (Error Err = parseAttrKind(Record[++i], &Kind))
1620             return Err;
1621 
1622           // Upgrade old-style byval attribute to one with a type, even if it's
1623           // nullptr. We will have to insert the real type when we associate
1624           // this AttributeList with a function.
1625           if (Kind == Attribute::ByVal)
1626             B.addByValAttr(nullptr);
1627           else if (Kind == Attribute::StructRet)
1628             B.addStructRetAttr(nullptr);
1629           else if (Kind == Attribute::InAlloca)
1630             B.addInAllocaAttr(nullptr);
1631 
1632           B.addAttribute(Kind);
1633         } else if (Record[i] == 1) { // Integer attribute
1634           Attribute::AttrKind Kind;
1635           if (Error Err = parseAttrKind(Record[++i], &Kind))
1636             return Err;
1637           if (Kind == Attribute::Alignment)
1638             B.addAlignmentAttr(Record[++i]);
1639           else if (Kind == Attribute::StackAlignment)
1640             B.addStackAlignmentAttr(Record[++i]);
1641           else if (Kind == Attribute::Dereferenceable)
1642             B.addDereferenceableAttr(Record[++i]);
1643           else if (Kind == Attribute::DereferenceableOrNull)
1644             B.addDereferenceableOrNullAttr(Record[++i]);
1645           else if (Kind == Attribute::AllocSize)
1646             B.addAllocSizeAttrFromRawRepr(Record[++i]);
1647           else if (Kind == Attribute::VScaleRange)
1648             B.addVScaleRangeAttrFromRawRepr(Record[++i]);
1649         } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
1650           bool HasValue = (Record[i++] == 4);
1651           SmallString<64> KindStr;
1652           SmallString<64> ValStr;
1653 
1654           while (Record[i] != 0 && i != e)
1655             KindStr += Record[i++];
1656           assert(Record[i] == 0 && "Kind string not null terminated");
1657 
1658           if (HasValue) {
1659             // Has a value associated with it.
1660             ++i; // Skip the '0' that terminates the "kind" string.
1661             while (Record[i] != 0 && i != e)
1662               ValStr += Record[i++];
1663             assert(Record[i] == 0 && "Value string not null terminated");
1664           }
1665 
1666           B.addAttribute(KindStr.str(), ValStr.str());
1667         } else {
1668           assert((Record[i] == 5 || Record[i] == 6) &&
1669                  "Invalid attribute group entry");
1670           bool HasType = Record[i] == 6;
1671           Attribute::AttrKind Kind;
1672           if (Error Err = parseAttrKind(Record[++i], &Kind))
1673             return Err;
1674           if (Kind == Attribute::ByVal) {
1675             B.addByValAttr(HasType ? getTypeByID(Record[++i]) : nullptr);
1676           } else if (Kind == Attribute::StructRet) {
1677             B.addStructRetAttr(HasType ? getTypeByID(Record[++i]) : nullptr);
1678           } else if (Kind == Attribute::ByRef) {
1679             B.addByRefAttr(getTypeByID(Record[++i]));
1680           } else if (Kind == Attribute::Preallocated) {
1681             B.addPreallocatedAttr(getTypeByID(Record[++i]));
1682           } else if (Kind == Attribute::InAlloca) {
1683             B.addInAllocaAttr(HasType ? getTypeByID(Record[++i]) : nullptr);
1684           }
1685         }
1686       }
1687 
1688       UpgradeAttributes(B);
1689       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1690       break;
1691     }
1692     }
1693   }
1694 }
1695 
parseTypeTable()1696 Error BitcodeReader::parseTypeTable() {
1697   if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1698     return Err;
1699 
1700   return parseTypeTableBody();
1701 }
1702 
parseTypeTableBody()1703 Error BitcodeReader::parseTypeTableBody() {
1704   if (!TypeList.empty())
1705     return error("Invalid multiple blocks");
1706 
1707   SmallVector<uint64_t, 64> Record;
1708   unsigned NumRecords = 0;
1709 
1710   SmallString<64> TypeName;
1711 
1712   // Read all the records for this type table.
1713   while (true) {
1714     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1715     if (!MaybeEntry)
1716       return MaybeEntry.takeError();
1717     BitstreamEntry Entry = MaybeEntry.get();
1718 
1719     switch (Entry.Kind) {
1720     case BitstreamEntry::SubBlock: // Handled for us already.
1721     case BitstreamEntry::Error:
1722       return error("Malformed block");
1723     case BitstreamEntry::EndBlock:
1724       if (NumRecords != TypeList.size())
1725         return error("Malformed block");
1726       return Error::success();
1727     case BitstreamEntry::Record:
1728       // The interesting case.
1729       break;
1730     }
1731 
1732     // Read a record.
1733     Record.clear();
1734     Type *ResultTy = nullptr;
1735     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1736     if (!MaybeRecord)
1737       return MaybeRecord.takeError();
1738     switch (MaybeRecord.get()) {
1739     default:
1740       return error("Invalid value");
1741     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1742       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1743       // type list.  This allows us to reserve space.
1744       if (Record.empty())
1745         return error("Invalid record");
1746       TypeList.resize(Record[0]);
1747       continue;
1748     case bitc::TYPE_CODE_VOID:      // VOID
1749       ResultTy = Type::getVoidTy(Context);
1750       break;
1751     case bitc::TYPE_CODE_HALF:     // HALF
1752       ResultTy = Type::getHalfTy(Context);
1753       break;
1754     case bitc::TYPE_CODE_BFLOAT:    // BFLOAT
1755       ResultTy = Type::getBFloatTy(Context);
1756       break;
1757     case bitc::TYPE_CODE_FLOAT:     // FLOAT
1758       ResultTy = Type::getFloatTy(Context);
1759       break;
1760     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1761       ResultTy = Type::getDoubleTy(Context);
1762       break;
1763     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1764       ResultTy = Type::getX86_FP80Ty(Context);
1765       break;
1766     case bitc::TYPE_CODE_FP128:     // FP128
1767       ResultTy = Type::getFP128Ty(Context);
1768       break;
1769     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1770       ResultTy = Type::getPPC_FP128Ty(Context);
1771       break;
1772     case bitc::TYPE_CODE_LABEL:     // LABEL
1773       ResultTy = Type::getLabelTy(Context);
1774       break;
1775     case bitc::TYPE_CODE_METADATA:  // METADATA
1776       ResultTy = Type::getMetadataTy(Context);
1777       break;
1778     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
1779       ResultTy = Type::getX86_MMXTy(Context);
1780       break;
1781     case bitc::TYPE_CODE_X86_AMX:   // X86_AMX
1782       ResultTy = Type::getX86_AMXTy(Context);
1783       break;
1784     case bitc::TYPE_CODE_TOKEN:     // TOKEN
1785       ResultTy = Type::getTokenTy(Context);
1786       break;
1787     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1788       if (Record.empty())
1789         return error("Invalid record");
1790 
1791       uint64_t NumBits = Record[0];
1792       if (NumBits < IntegerType::MIN_INT_BITS ||
1793           NumBits > IntegerType::MAX_INT_BITS)
1794         return error("Bitwidth for integer type out of range");
1795       ResultTy = IntegerType::get(Context, NumBits);
1796       break;
1797     }
1798     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1799                                     //          [pointee type, address space]
1800       if (Record.empty())
1801         return error("Invalid record");
1802       unsigned AddressSpace = 0;
1803       if (Record.size() == 2)
1804         AddressSpace = Record[1];
1805       ResultTy = getTypeByID(Record[0]);
1806       if (!ResultTy ||
1807           !PointerType::isValidElementType(ResultTy))
1808         return error("Invalid type");
1809       ResultTy = PointerType::get(ResultTy, AddressSpace);
1810       break;
1811     }
1812     case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
1813       if (Record.size() != 1)
1814         return error("Invalid record");
1815       unsigned AddressSpace = Record[0];
1816       ResultTy = PointerType::get(Context, AddressSpace);
1817       break;
1818     }
1819     case bitc::TYPE_CODE_FUNCTION_OLD: {
1820       // Deprecated, but still needed to read old bitcode files.
1821       // FUNCTION: [vararg, attrid, retty, paramty x N]
1822       if (Record.size() < 3)
1823         return error("Invalid record");
1824       SmallVector<Type*, 8> ArgTys;
1825       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1826         if (Type *T = getTypeByID(Record[i]))
1827           ArgTys.push_back(T);
1828         else
1829           break;
1830       }
1831 
1832       ResultTy = getTypeByID(Record[2]);
1833       if (!ResultTy || ArgTys.size() < Record.size()-3)
1834         return error("Invalid type");
1835 
1836       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1837       break;
1838     }
1839     case bitc::TYPE_CODE_FUNCTION: {
1840       // FUNCTION: [vararg, retty, paramty x N]
1841       if (Record.size() < 2)
1842         return error("Invalid record");
1843       SmallVector<Type*, 8> ArgTys;
1844       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1845         if (Type *T = getTypeByID(Record[i])) {
1846           if (!FunctionType::isValidArgumentType(T))
1847             return error("Invalid function argument type");
1848           ArgTys.push_back(T);
1849         }
1850         else
1851           break;
1852       }
1853 
1854       ResultTy = getTypeByID(Record[1]);
1855       if (!ResultTy || ArgTys.size() < Record.size()-2)
1856         return error("Invalid type");
1857 
1858       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1859       break;
1860     }
1861     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1862       if (Record.empty())
1863         return error("Invalid record");
1864       SmallVector<Type*, 8> EltTys;
1865       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1866         if (Type *T = getTypeByID(Record[i]))
1867           EltTys.push_back(T);
1868         else
1869           break;
1870       }
1871       if (EltTys.size() != Record.size()-1)
1872         return error("Invalid type");
1873       ResultTy = StructType::get(Context, EltTys, Record[0]);
1874       break;
1875     }
1876     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1877       if (convertToString(Record, 0, TypeName))
1878         return error("Invalid record");
1879       continue;
1880 
1881     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1882       if (Record.empty())
1883         return error("Invalid record");
1884 
1885       if (NumRecords >= TypeList.size())
1886         return error("Invalid TYPE table");
1887 
1888       // Check to see if this was forward referenced, if so fill in the temp.
1889       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1890       if (Res) {
1891         Res->setName(TypeName);
1892         TypeList[NumRecords] = nullptr;
1893       } else  // Otherwise, create a new struct.
1894         Res = createIdentifiedStructType(Context, TypeName);
1895       TypeName.clear();
1896 
1897       SmallVector<Type*, 8> EltTys;
1898       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1899         if (Type *T = getTypeByID(Record[i]))
1900           EltTys.push_back(T);
1901         else
1902           break;
1903       }
1904       if (EltTys.size() != Record.size()-1)
1905         return error("Invalid record");
1906       Res->setBody(EltTys, Record[0]);
1907       ResultTy = Res;
1908       break;
1909     }
1910     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1911       if (Record.size() != 1)
1912         return error("Invalid record");
1913 
1914       if (NumRecords >= TypeList.size())
1915         return error("Invalid TYPE table");
1916 
1917       // Check to see if this was forward referenced, if so fill in the temp.
1918       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1919       if (Res) {
1920         Res->setName(TypeName);
1921         TypeList[NumRecords] = nullptr;
1922       } else  // Otherwise, create a new struct with no body.
1923         Res = createIdentifiedStructType(Context, TypeName);
1924       TypeName.clear();
1925       ResultTy = Res;
1926       break;
1927     }
1928     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1929       if (Record.size() < 2)
1930         return error("Invalid record");
1931       ResultTy = getTypeByID(Record[1]);
1932       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1933         return error("Invalid type");
1934       ResultTy = ArrayType::get(ResultTy, Record[0]);
1935       break;
1936     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty] or
1937                                     //         [numelts, eltty, scalable]
1938       if (Record.size() < 2)
1939         return error("Invalid record");
1940       if (Record[0] == 0)
1941         return error("Invalid vector length");
1942       ResultTy = getTypeByID(Record[1]);
1943       if (!ResultTy || !StructType::isValidElementType(ResultTy))
1944         return error("Invalid type");
1945       bool Scalable = Record.size() > 2 ? Record[2] : false;
1946       ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
1947       break;
1948     }
1949 
1950     if (NumRecords >= TypeList.size())
1951       return error("Invalid TYPE table");
1952     if (TypeList[NumRecords])
1953       return error(
1954           "Invalid TYPE table: Only named structs can be forward referenced");
1955     assert(ResultTy && "Didn't read a type?");
1956     TypeList[NumRecords++] = ResultTy;
1957   }
1958 }
1959 
parseOperandBundleTags()1960 Error BitcodeReader::parseOperandBundleTags() {
1961   if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1962     return Err;
1963 
1964   if (!BundleTags.empty())
1965     return error("Invalid multiple blocks");
1966 
1967   SmallVector<uint64_t, 64> Record;
1968 
1969   while (true) {
1970     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1971     if (!MaybeEntry)
1972       return MaybeEntry.takeError();
1973     BitstreamEntry Entry = MaybeEntry.get();
1974 
1975     switch (Entry.Kind) {
1976     case BitstreamEntry::SubBlock: // Handled for us already.
1977     case BitstreamEntry::Error:
1978       return error("Malformed block");
1979     case BitstreamEntry::EndBlock:
1980       return Error::success();
1981     case BitstreamEntry::Record:
1982       // The interesting case.
1983       break;
1984     }
1985 
1986     // Tags are implicitly mapped to integers by their order.
1987 
1988     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1989     if (!MaybeRecord)
1990       return MaybeRecord.takeError();
1991     if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
1992       return error("Invalid record");
1993 
1994     // OPERAND_BUNDLE_TAG: [strchr x N]
1995     BundleTags.emplace_back();
1996     if (convertToString(Record, 0, BundleTags.back()))
1997       return error("Invalid record");
1998     Record.clear();
1999   }
2000 }
2001 
parseSyncScopeNames()2002 Error BitcodeReader::parseSyncScopeNames() {
2003   if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2004     return Err;
2005 
2006   if (!SSIDs.empty())
2007     return error("Invalid multiple synchronization scope names blocks");
2008 
2009   SmallVector<uint64_t, 64> Record;
2010   while (true) {
2011     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2012     if (!MaybeEntry)
2013       return MaybeEntry.takeError();
2014     BitstreamEntry Entry = MaybeEntry.get();
2015 
2016     switch (Entry.Kind) {
2017     case BitstreamEntry::SubBlock: // Handled for us already.
2018     case BitstreamEntry::Error:
2019       return error("Malformed block");
2020     case BitstreamEntry::EndBlock:
2021       if (SSIDs.empty())
2022         return error("Invalid empty synchronization scope names block");
2023       return Error::success();
2024     case BitstreamEntry::Record:
2025       // The interesting case.
2026       break;
2027     }
2028 
2029     // Synchronization scope names are implicitly mapped to synchronization
2030     // scope IDs by their order.
2031 
2032     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2033     if (!MaybeRecord)
2034       return MaybeRecord.takeError();
2035     if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2036       return error("Invalid record");
2037 
2038     SmallString<16> SSN;
2039     if (convertToString(Record, 0, SSN))
2040       return error("Invalid record");
2041 
2042     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2043     Record.clear();
2044   }
2045 }
2046 
2047 /// Associate a value with its name from the given index in the provided record.
recordValue(SmallVectorImpl<uint64_t> & Record,unsigned NameIndex,Triple & TT)2048 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2049                                              unsigned NameIndex, Triple &TT) {
2050   SmallString<128> ValueName;
2051   if (convertToString(Record, NameIndex, ValueName))
2052     return error("Invalid record");
2053   unsigned ValueID = Record[0];
2054   if (ValueID >= ValueList.size() || !ValueList[ValueID])
2055     return error("Invalid record");
2056   Value *V = ValueList[ValueID];
2057 
2058   StringRef NameStr(ValueName.data(), ValueName.size());
2059   if (NameStr.find_first_of(0) != StringRef::npos)
2060     return error("Invalid value name");
2061   V->setName(NameStr);
2062   auto *GO = dyn_cast<GlobalObject>(V);
2063   if (GO) {
2064     if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
2065       if (TT.supportsCOMDAT())
2066         GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2067       else
2068         GO->setComdat(nullptr);
2069     }
2070   }
2071   return V;
2072 }
2073 
2074 /// Helper to note and return the current location, and jump to the given
2075 /// offset.
jumpToValueSymbolTable(uint64_t Offset,BitstreamCursor & Stream)2076 static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
2077                                                  BitstreamCursor &Stream) {
2078   // Save the current parsing location so we can jump back at the end
2079   // of the VST read.
2080   uint64_t CurrentBit = Stream.GetCurrentBitNo();
2081   if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2082     return std::move(JumpFailed);
2083   Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2084   if (!MaybeEntry)
2085     return MaybeEntry.takeError();
2086   assert(MaybeEntry.get().Kind == BitstreamEntry::SubBlock);
2087   assert(MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID);
2088   return CurrentBit;
2089 }
2090 
setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,Function * F,ArrayRef<uint64_t> Record)2091 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2092                                             Function *F,
2093                                             ArrayRef<uint64_t> Record) {
2094   // Note that we subtract 1 here because the offset is relative to one word
2095   // before the start of the identification or module block, which was
2096   // historically always the start of the regular bitcode header.
2097   uint64_t FuncWordOffset = Record[1] - 1;
2098   uint64_t FuncBitOffset = FuncWordOffset * 32;
2099   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2100   // Set the LastFunctionBlockBit to point to the last function block.
2101   // Later when parsing is resumed after function materialization,
2102   // we can simply skip that last function block.
2103   if (FuncBitOffset > LastFunctionBlockBit)
2104     LastFunctionBlockBit = FuncBitOffset;
2105 }
2106 
2107 /// Read a new-style GlobalValue symbol table.
parseGlobalValueSymbolTable()2108 Error BitcodeReader::parseGlobalValueSymbolTable() {
2109   unsigned FuncBitcodeOffsetDelta =
2110       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2111 
2112   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2113     return Err;
2114 
2115   SmallVector<uint64_t, 64> Record;
2116   while (true) {
2117     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2118     if (!MaybeEntry)
2119       return MaybeEntry.takeError();
2120     BitstreamEntry Entry = MaybeEntry.get();
2121 
2122     switch (Entry.Kind) {
2123     case BitstreamEntry::SubBlock:
2124     case BitstreamEntry::Error:
2125       return error("Malformed block");
2126     case BitstreamEntry::EndBlock:
2127       return Error::success();
2128     case BitstreamEntry::Record:
2129       break;
2130     }
2131 
2132     Record.clear();
2133     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2134     if (!MaybeRecord)
2135       return MaybeRecord.takeError();
2136     switch (MaybeRecord.get()) {
2137     case bitc::VST_CODE_FNENTRY: // [valueid, offset]
2138       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2139                               cast<Function>(ValueList[Record[0]]), Record);
2140       break;
2141     }
2142   }
2143 }
2144 
2145 /// Parse the value symbol table at either the current parsing location or
2146 /// at the given bit offset if provided.
parseValueSymbolTable(uint64_t Offset)2147 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2148   uint64_t CurrentBit;
2149   // Pass in the Offset to distinguish between calling for the module-level
2150   // VST (where we want to jump to the VST offset) and the function-level
2151   // VST (where we don't).
2152   if (Offset > 0) {
2153     Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2154     if (!MaybeCurrentBit)
2155       return MaybeCurrentBit.takeError();
2156     CurrentBit = MaybeCurrentBit.get();
2157     // If this module uses a string table, read this as a module-level VST.
2158     if (UseStrtab) {
2159       if (Error Err = parseGlobalValueSymbolTable())
2160         return Err;
2161       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2162         return JumpFailed;
2163       return Error::success();
2164     }
2165     // Otherwise, the VST will be in a similar format to a function-level VST,
2166     // and will contain symbol names.
2167   }
2168 
2169   // Compute the delta between the bitcode indices in the VST (the word offset
2170   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2171   // expected by the lazy reader. The reader's EnterSubBlock expects to have
2172   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2173   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2174   // just before entering the VST subblock because: 1) the EnterSubBlock
2175   // changes the AbbrevID width; 2) the VST block is nested within the same
2176   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2177   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2178   // jump to the FUNCTION_BLOCK using this offset later, we don't want
2179   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2180   unsigned FuncBitcodeOffsetDelta =
2181       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2182 
2183   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2184     return Err;
2185 
2186   SmallVector<uint64_t, 64> Record;
2187 
2188   Triple TT(TheModule->getTargetTriple());
2189 
2190   // Read all the records for this value table.
2191   SmallString<128> ValueName;
2192 
2193   while (true) {
2194     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2195     if (!MaybeEntry)
2196       return MaybeEntry.takeError();
2197     BitstreamEntry Entry = MaybeEntry.get();
2198 
2199     switch (Entry.Kind) {
2200     case BitstreamEntry::SubBlock: // Handled for us already.
2201     case BitstreamEntry::Error:
2202       return error("Malformed block");
2203     case BitstreamEntry::EndBlock:
2204       if (Offset > 0)
2205         if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2206           return JumpFailed;
2207       return Error::success();
2208     case BitstreamEntry::Record:
2209       // The interesting case.
2210       break;
2211     }
2212 
2213     // Read a record.
2214     Record.clear();
2215     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2216     if (!MaybeRecord)
2217       return MaybeRecord.takeError();
2218     switch (MaybeRecord.get()) {
2219     default:  // Default behavior: unknown type.
2220       break;
2221     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
2222       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2223       if (Error Err = ValOrErr.takeError())
2224         return Err;
2225       ValOrErr.get();
2226       break;
2227     }
2228     case bitc::VST_CODE_FNENTRY: {
2229       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2230       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2231       if (Error Err = ValOrErr.takeError())
2232         return Err;
2233       Value *V = ValOrErr.get();
2234 
2235       // Ignore function offsets emitted for aliases of functions in older
2236       // versions of LLVM.
2237       if (auto *F = dyn_cast<Function>(V))
2238         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2239       break;
2240     }
2241     case bitc::VST_CODE_BBENTRY: {
2242       if (convertToString(Record, 1, ValueName))
2243         return error("Invalid record");
2244       BasicBlock *BB = getBasicBlock(Record[0]);
2245       if (!BB)
2246         return error("Invalid record");
2247 
2248       BB->setName(StringRef(ValueName.data(), ValueName.size()));
2249       ValueName.clear();
2250       break;
2251     }
2252     }
2253   }
2254 }
2255 
2256 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2257 /// encoding.
decodeSignRotatedValue(uint64_t V)2258 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2259   if ((V & 1) == 0)
2260     return V >> 1;
2261   if (V != 1)
2262     return -(V >> 1);
2263   // There is no such thing as -0 with integers.  "-0" really means MININT.
2264   return 1ULL << 63;
2265 }
2266 
2267 /// Resolve all of the initializers for global values and aliases that we can.
resolveGlobalAndIndirectSymbolInits()2268 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2269   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2270   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
2271       IndirectSymbolInitWorklist;
2272   std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2273   std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2274   std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2275 
2276   GlobalInitWorklist.swap(GlobalInits);
2277   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2278   FunctionPrefixWorklist.swap(FunctionPrefixes);
2279   FunctionPrologueWorklist.swap(FunctionPrologues);
2280   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2281 
2282   while (!GlobalInitWorklist.empty()) {
2283     unsigned ValID = GlobalInitWorklist.back().second;
2284     if (ValID >= ValueList.size()) {
2285       // Not ready to resolve this yet, it requires something later in the file.
2286       GlobalInits.push_back(GlobalInitWorklist.back());
2287     } else {
2288       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2289         GlobalInitWorklist.back().first->setInitializer(C);
2290       else
2291         return error("Expected a constant");
2292     }
2293     GlobalInitWorklist.pop_back();
2294   }
2295 
2296   while (!IndirectSymbolInitWorklist.empty()) {
2297     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2298     if (ValID >= ValueList.size()) {
2299       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2300     } else {
2301       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2302       if (!C)
2303         return error("Expected a constant");
2304       GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2305       if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2306         return error("Alias and aliasee types don't match");
2307       GIS->setIndirectSymbol(C);
2308     }
2309     IndirectSymbolInitWorklist.pop_back();
2310   }
2311 
2312   while (!FunctionPrefixWorklist.empty()) {
2313     unsigned ValID = FunctionPrefixWorklist.back().second;
2314     if (ValID >= ValueList.size()) {
2315       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2316     } else {
2317       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2318         FunctionPrefixWorklist.back().first->setPrefixData(C);
2319       else
2320         return error("Expected a constant");
2321     }
2322     FunctionPrefixWorklist.pop_back();
2323   }
2324 
2325   while (!FunctionPrologueWorklist.empty()) {
2326     unsigned ValID = FunctionPrologueWorklist.back().second;
2327     if (ValID >= ValueList.size()) {
2328       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2329     } else {
2330       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2331         FunctionPrologueWorklist.back().first->setPrologueData(C);
2332       else
2333         return error("Expected a constant");
2334     }
2335     FunctionPrologueWorklist.pop_back();
2336   }
2337 
2338   while (!FunctionPersonalityFnWorklist.empty()) {
2339     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2340     if (ValID >= ValueList.size()) {
2341       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2342     } else {
2343       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2344         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2345       else
2346         return error("Expected a constant");
2347     }
2348     FunctionPersonalityFnWorklist.pop_back();
2349   }
2350 
2351   return Error::success();
2352 }
2353 
readWideAPInt(ArrayRef<uint64_t> Vals,unsigned TypeBits)2354 APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2355   SmallVector<uint64_t, 8> Words(Vals.size());
2356   transform(Vals, Words.begin(),
2357                  BitcodeReader::decodeSignRotatedValue);
2358 
2359   return APInt(TypeBits, Words);
2360 }
2361 
parseConstants()2362 Error BitcodeReader::parseConstants() {
2363   if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2364     return Err;
2365 
2366   SmallVector<uint64_t, 64> Record;
2367 
2368   // Read all the records for this value table.
2369   Type *CurTy = Type::getInt32Ty(Context);
2370   Type *CurFullTy = Type::getInt32Ty(Context);
2371   unsigned NextCstNo = ValueList.size();
2372 
2373   struct DelayedShufTy {
2374     VectorType *OpTy;
2375     VectorType *RTy;
2376     Type *CurFullTy;
2377     uint64_t Op0Idx;
2378     uint64_t Op1Idx;
2379     uint64_t Op2Idx;
2380     unsigned CstNo;
2381   };
2382   std::vector<DelayedShufTy> DelayedShuffles;
2383   while (true) {
2384     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2385     if (!MaybeEntry)
2386       return MaybeEntry.takeError();
2387     BitstreamEntry Entry = MaybeEntry.get();
2388 
2389     switch (Entry.Kind) {
2390     case BitstreamEntry::SubBlock: // Handled for us already.
2391     case BitstreamEntry::Error:
2392       return error("Malformed block");
2393     case BitstreamEntry::EndBlock:
2394       // Once all the constants have been read, go through and resolve forward
2395       // references.
2396       //
2397       // We have to treat shuffles specially because they don't have three
2398       // operands anymore.  We need to convert the shuffle mask into an array,
2399       // and we can't convert a forward reference.
2400       for (auto &DelayedShuffle : DelayedShuffles) {
2401         VectorType *OpTy = DelayedShuffle.OpTy;
2402         VectorType *RTy = DelayedShuffle.RTy;
2403         uint64_t Op0Idx = DelayedShuffle.Op0Idx;
2404         uint64_t Op1Idx = DelayedShuffle.Op1Idx;
2405         uint64_t Op2Idx = DelayedShuffle.Op2Idx;
2406         uint64_t CstNo = DelayedShuffle.CstNo;
2407         Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, OpTy);
2408         Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy);
2409         Type *ShufTy =
2410             VectorType::get(Type::getInt32Ty(Context), RTy->getElementCount());
2411         Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, ShufTy);
2412         if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2413           return error("Invalid shufflevector operands");
2414         SmallVector<int, 16> Mask;
2415         ShuffleVectorInst::getShuffleMask(Op2, Mask);
2416         Value *V = ConstantExpr::getShuffleVector(Op0, Op1, Mask);
2417         ValueList.assignValue(V, CstNo, DelayedShuffle.CurFullTy);
2418       }
2419 
2420       if (NextCstNo != ValueList.size())
2421         return error("Invalid constant reference");
2422 
2423       ValueList.resolveConstantForwardRefs();
2424       return Error::success();
2425     case BitstreamEntry::Record:
2426       // The interesting case.
2427       break;
2428     }
2429 
2430     // Read a record.
2431     Record.clear();
2432     Type *VoidType = Type::getVoidTy(Context);
2433     Value *V = nullptr;
2434     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2435     if (!MaybeBitCode)
2436       return MaybeBitCode.takeError();
2437     switch (unsigned BitCode = MaybeBitCode.get()) {
2438     default:  // Default behavior: unknown constant
2439     case bitc::CST_CODE_UNDEF:     // UNDEF
2440       V = UndefValue::get(CurTy);
2441       break;
2442     case bitc::CST_CODE_POISON:    // POISON
2443       V = PoisonValue::get(CurTy);
2444       break;
2445     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2446       if (Record.empty())
2447         return error("Invalid record");
2448       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2449         return error("Invalid record");
2450       if (TypeList[Record[0]] == VoidType)
2451         return error("Invalid constant type");
2452       CurFullTy = TypeList[Record[0]];
2453       CurTy = flattenPointerTypes(CurFullTy);
2454       continue;  // Skip the ValueList manipulation.
2455     case bitc::CST_CODE_NULL:      // NULL
2456       if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
2457         return error("Invalid type for a constant null value");
2458       V = Constant::getNullValue(CurTy);
2459       break;
2460     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2461       if (!CurTy->isIntegerTy() || Record.empty())
2462         return error("Invalid record");
2463       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2464       break;
2465     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2466       if (!CurTy->isIntegerTy() || Record.empty())
2467         return error("Invalid record");
2468 
2469       APInt VInt =
2470           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2471       V = ConstantInt::get(Context, VInt);
2472 
2473       break;
2474     }
2475     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2476       if (Record.empty())
2477         return error("Invalid record");
2478       if (CurTy->isHalfTy())
2479         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2480                                              APInt(16, (uint16_t)Record[0])));
2481       else if (CurTy->isBFloatTy())
2482         V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
2483                                              APInt(16, (uint32_t)Record[0])));
2484       else if (CurTy->isFloatTy())
2485         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2486                                              APInt(32, (uint32_t)Record[0])));
2487       else if (CurTy->isDoubleTy())
2488         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2489                                              APInt(64, Record[0])));
2490       else if (CurTy->isX86_FP80Ty()) {
2491         // Bits are not stored the same way as a normal i80 APInt, compensate.
2492         uint64_t Rearrange[2];
2493         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2494         Rearrange[1] = Record[0] >> 48;
2495         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2496                                              APInt(80, Rearrange)));
2497       } else if (CurTy->isFP128Ty())
2498         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2499                                              APInt(128, Record)));
2500       else if (CurTy->isPPC_FP128Ty())
2501         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2502                                              APInt(128, Record)));
2503       else
2504         V = UndefValue::get(CurTy);
2505       break;
2506     }
2507 
2508     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2509       if (Record.empty())
2510         return error("Invalid record");
2511 
2512       unsigned Size = Record.size();
2513       SmallVector<Constant*, 16> Elts;
2514 
2515       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2516         for (unsigned i = 0; i != Size; ++i)
2517           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2518                                                      STy->getElementType(i)));
2519         V = ConstantStruct::get(STy, Elts);
2520       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2521         Type *EltTy = ATy->getElementType();
2522         for (unsigned i = 0; i != Size; ++i)
2523           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2524         V = ConstantArray::get(ATy, Elts);
2525       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2526         Type *EltTy = VTy->getElementType();
2527         for (unsigned i = 0; i != Size; ++i)
2528           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2529         V = ConstantVector::get(Elts);
2530       } else {
2531         V = UndefValue::get(CurTy);
2532       }
2533       break;
2534     }
2535     case bitc::CST_CODE_STRING:    // STRING: [values]
2536     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2537       if (Record.empty())
2538         return error("Invalid record");
2539 
2540       SmallString<16> Elts(Record.begin(), Record.end());
2541       V = ConstantDataArray::getString(Context, Elts,
2542                                        BitCode == bitc::CST_CODE_CSTRING);
2543       break;
2544     }
2545     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2546       if (Record.empty())
2547         return error("Invalid record");
2548 
2549       Type *EltTy;
2550       if (auto *Array = dyn_cast<ArrayType>(CurTy))
2551         EltTy = Array->getElementType();
2552       else
2553         EltTy = cast<VectorType>(CurTy)->getElementType();
2554       if (EltTy->isIntegerTy(8)) {
2555         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2556         if (isa<VectorType>(CurTy))
2557           V = ConstantDataVector::get(Context, Elts);
2558         else
2559           V = ConstantDataArray::get(Context, Elts);
2560       } else if (EltTy->isIntegerTy(16)) {
2561         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2562         if (isa<VectorType>(CurTy))
2563           V = ConstantDataVector::get(Context, Elts);
2564         else
2565           V = ConstantDataArray::get(Context, Elts);
2566       } else if (EltTy->isIntegerTy(32)) {
2567         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2568         if (isa<VectorType>(CurTy))
2569           V = ConstantDataVector::get(Context, Elts);
2570         else
2571           V = ConstantDataArray::get(Context, Elts);
2572       } else if (EltTy->isIntegerTy(64)) {
2573         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2574         if (isa<VectorType>(CurTy))
2575           V = ConstantDataVector::get(Context, Elts);
2576         else
2577           V = ConstantDataArray::get(Context, Elts);
2578       } else if (EltTy->isHalfTy()) {
2579         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2580         if (isa<VectorType>(CurTy))
2581           V = ConstantDataVector::getFP(EltTy, Elts);
2582         else
2583           V = ConstantDataArray::getFP(EltTy, Elts);
2584       } else if (EltTy->isBFloatTy()) {
2585         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2586         if (isa<VectorType>(CurTy))
2587           V = ConstantDataVector::getFP(EltTy, Elts);
2588         else
2589           V = ConstantDataArray::getFP(EltTy, Elts);
2590       } else if (EltTy->isFloatTy()) {
2591         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2592         if (isa<VectorType>(CurTy))
2593           V = ConstantDataVector::getFP(EltTy, Elts);
2594         else
2595           V = ConstantDataArray::getFP(EltTy, Elts);
2596       } else if (EltTy->isDoubleTy()) {
2597         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2598         if (isa<VectorType>(CurTy))
2599           V = ConstantDataVector::getFP(EltTy, Elts);
2600         else
2601           V = ConstantDataArray::getFP(EltTy, Elts);
2602       } else {
2603         return error("Invalid type for value");
2604       }
2605       break;
2606     }
2607     case bitc::CST_CODE_CE_UNOP: {  // CE_UNOP: [opcode, opval]
2608       if (Record.size() < 2)
2609         return error("Invalid record");
2610       int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
2611       if (Opc < 0) {
2612         V = UndefValue::get(CurTy);  // Unknown unop.
2613       } else {
2614         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2615         unsigned Flags = 0;
2616         V = ConstantExpr::get(Opc, LHS, Flags);
2617       }
2618       break;
2619     }
2620     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2621       if (Record.size() < 3)
2622         return error("Invalid record");
2623       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2624       if (Opc < 0) {
2625         V = UndefValue::get(CurTy);  // Unknown binop.
2626       } else {
2627         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2628         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2629         unsigned Flags = 0;
2630         if (Record.size() >= 4) {
2631           if (Opc == Instruction::Add ||
2632               Opc == Instruction::Sub ||
2633               Opc == Instruction::Mul ||
2634               Opc == Instruction::Shl) {
2635             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2636               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2637             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2638               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2639           } else if (Opc == Instruction::SDiv ||
2640                      Opc == Instruction::UDiv ||
2641                      Opc == Instruction::LShr ||
2642                      Opc == Instruction::AShr) {
2643             if (Record[3] & (1 << bitc::PEO_EXACT))
2644               Flags |= SDivOperator::IsExact;
2645           }
2646         }
2647         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2648       }
2649       break;
2650     }
2651     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2652       if (Record.size() < 3)
2653         return error("Invalid record");
2654       int Opc = getDecodedCastOpcode(Record[0]);
2655       if (Opc < 0) {
2656         V = UndefValue::get(CurTy);  // Unknown cast.
2657       } else {
2658         Type *OpTy = getTypeByID(Record[1]);
2659         if (!OpTy)
2660           return error("Invalid record");
2661         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2662         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2663         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2664       }
2665       break;
2666     }
2667     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2668     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2669     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2670                                                      // operands]
2671       unsigned OpNum = 0;
2672       Type *PointeeType = nullptr;
2673       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2674           Record.size() % 2)
2675         PointeeType = getTypeByID(Record[OpNum++]);
2676 
2677       bool InBounds = false;
2678       Optional<unsigned> InRangeIndex;
2679       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2680         uint64_t Op = Record[OpNum++];
2681         InBounds = Op & 1;
2682         InRangeIndex = Op >> 1;
2683       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2684         InBounds = true;
2685 
2686       SmallVector<Constant*, 16> Elts;
2687       Type *Elt0FullTy = nullptr;
2688       while (OpNum != Record.size()) {
2689         if (!Elt0FullTy)
2690           Elt0FullTy = getFullyStructuredTypeByID(Record[OpNum]);
2691         Type *ElTy = getTypeByID(Record[OpNum++]);
2692         if (!ElTy)
2693           return error("Invalid record");
2694         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2695       }
2696 
2697       if (Elts.size() < 1)
2698         return error("Invalid gep with no operands");
2699 
2700       Type *ImplicitPointeeType =
2701           getPointerElementFlatType(Elt0FullTy->getScalarType());
2702       if (!PointeeType)
2703         PointeeType = ImplicitPointeeType;
2704       else if (PointeeType != ImplicitPointeeType)
2705         return error("Explicit gep operator type does not match pointee type "
2706                      "of pointer operand");
2707 
2708       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2709       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2710                                          InBounds, InRangeIndex);
2711       break;
2712     }
2713     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2714       if (Record.size() < 3)
2715         return error("Invalid record");
2716 
2717       Type *SelectorTy = Type::getInt1Ty(Context);
2718 
2719       // The selector might be an i1, an <n x i1>, or a <vscale x n x i1>
2720       // Get the type from the ValueList before getting a forward ref.
2721       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2722         if (Value *V = ValueList[Record[0]])
2723           if (SelectorTy != V->getType())
2724             SelectorTy = VectorType::get(SelectorTy,
2725                                          VTy->getElementCount());
2726 
2727       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2728                                                               SelectorTy),
2729                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2730                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2731       break;
2732     }
2733     case bitc::CST_CODE_CE_EXTRACTELT
2734         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2735       if (Record.size() < 3)
2736         return error("Invalid record");
2737       VectorType *OpTy =
2738         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2739       if (!OpTy)
2740         return error("Invalid record");
2741       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2742       Constant *Op1 = nullptr;
2743       if (Record.size() == 4) {
2744         Type *IdxTy = getTypeByID(Record[2]);
2745         if (!IdxTy)
2746           return error("Invalid record");
2747         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2748       } else {
2749         // Deprecated, but still needed to read old bitcode files.
2750         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2751       }
2752       if (!Op1)
2753         return error("Invalid record");
2754       V = ConstantExpr::getExtractElement(Op0, Op1);
2755       break;
2756     }
2757     case bitc::CST_CODE_CE_INSERTELT
2758         : { // CE_INSERTELT: [opval, opval, opty, opval]
2759       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2760       if (Record.size() < 3 || !OpTy)
2761         return error("Invalid record");
2762       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2763       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2764                                                   OpTy->getElementType());
2765       Constant *Op2 = nullptr;
2766       if (Record.size() == 4) {
2767         Type *IdxTy = getTypeByID(Record[2]);
2768         if (!IdxTy)
2769           return error("Invalid record");
2770         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2771       } else {
2772         // Deprecated, but still needed to read old bitcode files.
2773         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2774       }
2775       if (!Op2)
2776         return error("Invalid record");
2777       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2778       break;
2779     }
2780     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2781       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2782       if (Record.size() < 3 || !OpTy)
2783         return error("Invalid record");
2784       DelayedShuffles.push_back(
2785           {OpTy, OpTy, CurFullTy, Record[0], Record[1], Record[2], NextCstNo});
2786       ++NextCstNo;
2787       continue;
2788     }
2789     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2790       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2791       VectorType *OpTy =
2792         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2793       if (Record.size() < 4 || !RTy || !OpTy)
2794         return error("Invalid record");
2795       DelayedShuffles.push_back(
2796           {OpTy, RTy, CurFullTy, Record[1], Record[2], Record[3], NextCstNo});
2797       ++NextCstNo;
2798       continue;
2799     }
2800     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2801       if (Record.size() < 4)
2802         return error("Invalid record");
2803       Type *OpTy = getTypeByID(Record[0]);
2804       if (!OpTy)
2805         return error("Invalid record");
2806       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2807       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2808 
2809       if (OpTy->isFPOrFPVectorTy())
2810         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2811       else
2812         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2813       break;
2814     }
2815     // This maintains backward compatibility, pre-asm dialect keywords.
2816     // Deprecated, but still needed to read old bitcode files.
2817     case bitc::CST_CODE_INLINEASM_OLD: {
2818       if (Record.size() < 2)
2819         return error("Invalid record");
2820       std::string AsmStr, ConstrStr;
2821       bool HasSideEffects = Record[0] & 1;
2822       bool IsAlignStack = Record[0] >> 1;
2823       unsigned AsmStrSize = Record[1];
2824       if (2+AsmStrSize >= Record.size())
2825         return error("Invalid record");
2826       unsigned ConstStrSize = Record[2+AsmStrSize];
2827       if (3+AsmStrSize+ConstStrSize > Record.size())
2828         return error("Invalid record");
2829 
2830       for (unsigned i = 0; i != AsmStrSize; ++i)
2831         AsmStr += (char)Record[2+i];
2832       for (unsigned i = 0; i != ConstStrSize; ++i)
2833         ConstrStr += (char)Record[3+AsmStrSize+i];
2834       UpgradeInlineAsmString(&AsmStr);
2835       V = InlineAsm::get(
2836           cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2837           ConstrStr, HasSideEffects, IsAlignStack);
2838       break;
2839     }
2840     // This version adds support for the asm dialect keywords (e.g.,
2841     // inteldialect).
2842     case bitc::CST_CODE_INLINEASM_OLD2: {
2843       if (Record.size() < 2)
2844         return error("Invalid record");
2845       std::string AsmStr, ConstrStr;
2846       bool HasSideEffects = Record[0] & 1;
2847       bool IsAlignStack = (Record[0] >> 1) & 1;
2848       unsigned AsmDialect = Record[0] >> 2;
2849       unsigned AsmStrSize = Record[1];
2850       if (2+AsmStrSize >= Record.size())
2851         return error("Invalid record");
2852       unsigned ConstStrSize = Record[2+AsmStrSize];
2853       if (3+AsmStrSize+ConstStrSize > Record.size())
2854         return error("Invalid record");
2855 
2856       for (unsigned i = 0; i != AsmStrSize; ++i)
2857         AsmStr += (char)Record[2+i];
2858       for (unsigned i = 0; i != ConstStrSize; ++i)
2859         ConstrStr += (char)Record[3+AsmStrSize+i];
2860       UpgradeInlineAsmString(&AsmStr);
2861       V = InlineAsm::get(
2862           cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2863           ConstrStr, HasSideEffects, IsAlignStack,
2864           InlineAsm::AsmDialect(AsmDialect));
2865       break;
2866     }
2867     // This version adds support for the unwind keyword.
2868     case bitc::CST_CODE_INLINEASM: {
2869       if (Record.size() < 2)
2870         return error("Invalid record");
2871       std::string AsmStr, ConstrStr;
2872       bool HasSideEffects = Record[0] & 1;
2873       bool IsAlignStack = (Record[0] >> 1) & 1;
2874       unsigned AsmDialect = (Record[0] >> 2) & 1;
2875       bool CanThrow = (Record[0] >> 3) & 1;
2876       unsigned AsmStrSize = Record[1];
2877       if (2 + AsmStrSize >= Record.size())
2878         return error("Invalid record");
2879       unsigned ConstStrSize = Record[2 + AsmStrSize];
2880       if (3 + AsmStrSize + ConstStrSize > Record.size())
2881         return error("Invalid record");
2882 
2883       for (unsigned i = 0; i != AsmStrSize; ++i)
2884         AsmStr += (char)Record[2 + i];
2885       for (unsigned i = 0; i != ConstStrSize; ++i)
2886         ConstrStr += (char)Record[3 + AsmStrSize + i];
2887       UpgradeInlineAsmString(&AsmStr);
2888       V = InlineAsm::get(
2889           cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2890           ConstrStr, HasSideEffects, IsAlignStack,
2891           InlineAsm::AsmDialect(AsmDialect), CanThrow);
2892       break;
2893     }
2894     case bitc::CST_CODE_BLOCKADDRESS:{
2895       if (Record.size() < 3)
2896         return error("Invalid record");
2897       Type *FnTy = getTypeByID(Record[0]);
2898       if (!FnTy)
2899         return error("Invalid record");
2900       Function *Fn =
2901         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2902       if (!Fn)
2903         return error("Invalid record");
2904 
2905       // If the function is already parsed we can insert the block address right
2906       // away.
2907       BasicBlock *BB;
2908       unsigned BBID = Record[2];
2909       if (!BBID)
2910         // Invalid reference to entry block.
2911         return error("Invalid ID");
2912       if (!Fn->empty()) {
2913         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2914         for (size_t I = 0, E = BBID; I != E; ++I) {
2915           if (BBI == BBE)
2916             return error("Invalid ID");
2917           ++BBI;
2918         }
2919         BB = &*BBI;
2920       } else {
2921         // Otherwise insert a placeholder and remember it so it can be inserted
2922         // when the function is parsed.
2923         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2924         if (FwdBBs.empty())
2925           BasicBlockFwdRefQueue.push_back(Fn);
2926         if (FwdBBs.size() < BBID + 1)
2927           FwdBBs.resize(BBID + 1);
2928         if (!FwdBBs[BBID])
2929           FwdBBs[BBID] = BasicBlock::Create(Context);
2930         BB = FwdBBs[BBID];
2931       }
2932       V = BlockAddress::get(Fn, BB);
2933       break;
2934     }
2935     case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
2936       if (Record.size() < 2)
2937         return error("Invalid record");
2938       Type *GVTy = getTypeByID(Record[0]);
2939       if (!GVTy)
2940         return error("Invalid record");
2941       GlobalValue *GV = dyn_cast_or_null<GlobalValue>(
2942           ValueList.getConstantFwdRef(Record[1], GVTy));
2943       if (!GV)
2944         return error("Invalid record");
2945 
2946       V = DSOLocalEquivalent::get(GV);
2947       break;
2948     }
2949     }
2950 
2951     assert(V->getType() == flattenPointerTypes(CurFullTy) &&
2952            "Incorrect fully structured type provided for Constant");
2953     ValueList.assignValue(V, NextCstNo, CurFullTy);
2954     ++NextCstNo;
2955   }
2956 }
2957 
parseUseLists()2958 Error BitcodeReader::parseUseLists() {
2959   if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2960     return Err;
2961 
2962   // Read all the records.
2963   SmallVector<uint64_t, 64> Record;
2964 
2965   while (true) {
2966     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2967     if (!MaybeEntry)
2968       return MaybeEntry.takeError();
2969     BitstreamEntry Entry = MaybeEntry.get();
2970 
2971     switch (Entry.Kind) {
2972     case BitstreamEntry::SubBlock: // Handled for us already.
2973     case BitstreamEntry::Error:
2974       return error("Malformed block");
2975     case BitstreamEntry::EndBlock:
2976       return Error::success();
2977     case BitstreamEntry::Record:
2978       // The interesting case.
2979       break;
2980     }
2981 
2982     // Read a use list record.
2983     Record.clear();
2984     bool IsBB = false;
2985     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2986     if (!MaybeRecord)
2987       return MaybeRecord.takeError();
2988     switch (MaybeRecord.get()) {
2989     default:  // Default behavior: unknown type.
2990       break;
2991     case bitc::USELIST_CODE_BB:
2992       IsBB = true;
2993       LLVM_FALLTHROUGH;
2994     case bitc::USELIST_CODE_DEFAULT: {
2995       unsigned RecordLength = Record.size();
2996       if (RecordLength < 3)
2997         // Records should have at least an ID and two indexes.
2998         return error("Invalid record");
2999       unsigned ID = Record.pop_back_val();
3000 
3001       Value *V;
3002       if (IsBB) {
3003         assert(ID < FunctionBBs.size() && "Basic block not found");
3004         V = FunctionBBs[ID];
3005       } else
3006         V = ValueList[ID];
3007       unsigned NumUses = 0;
3008       SmallDenseMap<const Use *, unsigned, 16> Order;
3009       for (const Use &U : V->materialized_uses()) {
3010         if (++NumUses > Record.size())
3011           break;
3012         Order[&U] = Record[NumUses - 1];
3013       }
3014       if (Order.size() != Record.size() || NumUses > Record.size())
3015         // Mismatches can happen if the functions are being materialized lazily
3016         // (out-of-order), or a value has been upgraded.
3017         break;
3018 
3019       V->sortUseList([&](const Use &L, const Use &R) {
3020         return Order.lookup(&L) < Order.lookup(&R);
3021       });
3022       break;
3023     }
3024     }
3025   }
3026 }
3027 
3028 /// When we see the block for metadata, remember where it is and then skip it.
3029 /// This lets us lazily deserialize the metadata.
rememberAndSkipMetadata()3030 Error BitcodeReader::rememberAndSkipMetadata() {
3031   // Save the current stream state.
3032   uint64_t CurBit = Stream.GetCurrentBitNo();
3033   DeferredMetadataInfo.push_back(CurBit);
3034 
3035   // Skip over the block for now.
3036   if (Error Err = Stream.SkipBlock())
3037     return Err;
3038   return Error::success();
3039 }
3040 
materializeMetadata()3041 Error BitcodeReader::materializeMetadata() {
3042   for (uint64_t BitPos : DeferredMetadataInfo) {
3043     // Move the bit stream to the saved position.
3044     if (Error JumpFailed = Stream.JumpToBit(BitPos))
3045       return JumpFailed;
3046     if (Error Err = MDLoader->parseModuleMetadata())
3047       return Err;
3048   }
3049 
3050   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3051   // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3052   // multiple times.
3053   if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3054     if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3055       NamedMDNode *LinkerOpts =
3056           TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3057       for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3058         LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3059     }
3060   }
3061 
3062   DeferredMetadataInfo.clear();
3063   return Error::success();
3064 }
3065 
setStripDebugInfo()3066 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3067 
3068 /// When we see the block for a function body, remember where it is and then
3069 /// skip it.  This lets us lazily deserialize the functions.
rememberAndSkipFunctionBody()3070 Error BitcodeReader::rememberAndSkipFunctionBody() {
3071   // Get the function we are talking about.
3072   if (FunctionsWithBodies.empty())
3073     return error("Insufficient function protos");
3074 
3075   Function *Fn = FunctionsWithBodies.back();
3076   FunctionsWithBodies.pop_back();
3077 
3078   // Save the current stream state.
3079   uint64_t CurBit = Stream.GetCurrentBitNo();
3080   assert(
3081       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3082       "Mismatch between VST and scanned function offsets");
3083   DeferredFunctionInfo[Fn] = CurBit;
3084 
3085   // Skip over the function block for now.
3086   if (Error Err = Stream.SkipBlock())
3087     return Err;
3088   return Error::success();
3089 }
3090 
globalCleanup()3091 Error BitcodeReader::globalCleanup() {
3092   // Patch the initializers for globals and aliases up.
3093   if (Error Err = resolveGlobalAndIndirectSymbolInits())
3094     return Err;
3095   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3096     return error("Malformed global initializer set");
3097 
3098   // Look for intrinsic functions which need to be upgraded at some point
3099   // and functions that need to have their function attributes upgraded.
3100   for (Function &F : *TheModule) {
3101     MDLoader->upgradeDebugIntrinsics(F);
3102     Function *NewFn;
3103     if (UpgradeIntrinsicFunction(&F, NewFn))
3104       UpgradedIntrinsics[&F] = NewFn;
3105     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3106       // Some types could be renamed during loading if several modules are
3107       // loaded in the same LLVMContext (LTO scenario). In this case we should
3108       // remangle intrinsics names as well.
3109       RemangledIntrinsics[&F] = Remangled.getValue();
3110     // Look for functions that rely on old function attribute behavior.
3111     UpgradeFunctionAttributes(F);
3112   }
3113 
3114   // Look for global variables which need to be renamed.
3115   std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3116   for (GlobalVariable &GV : TheModule->globals())
3117     if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3118       UpgradedVariables.emplace_back(&GV, Upgraded);
3119   for (auto &Pair : UpgradedVariables) {
3120     Pair.first->eraseFromParent();
3121     TheModule->getGlobalList().push_back(Pair.second);
3122   }
3123 
3124   // Force deallocation of memory for these vectors to favor the client that
3125   // want lazy deserialization.
3126   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3127   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
3128       IndirectSymbolInits);
3129   return Error::success();
3130 }
3131 
3132 /// Support for lazy parsing of function bodies. This is required if we
3133 /// either have an old bitcode file without a VST forward declaration record,
3134 /// or if we have an anonymous function being materialized, since anonymous
3135 /// functions do not have a name and are therefore not in the VST.
rememberAndSkipFunctionBodies()3136 Error BitcodeReader::rememberAndSkipFunctionBodies() {
3137   if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3138     return JumpFailed;
3139 
3140   if (Stream.AtEndOfStream())
3141     return error("Could not find function in stream");
3142 
3143   if (!SeenFirstFunctionBody)
3144     return error("Trying to materialize functions before seeing function blocks");
3145 
3146   // An old bitcode file with the symbol table at the end would have
3147   // finished the parse greedily.
3148   assert(SeenValueSymbolTable);
3149 
3150   SmallVector<uint64_t, 64> Record;
3151 
3152   while (true) {
3153     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3154     if (!MaybeEntry)
3155       return MaybeEntry.takeError();
3156     llvm::BitstreamEntry Entry = MaybeEntry.get();
3157 
3158     switch (Entry.Kind) {
3159     default:
3160       return error("Expect SubBlock");
3161     case BitstreamEntry::SubBlock:
3162       switch (Entry.ID) {
3163       default:
3164         return error("Expect function block");
3165       case bitc::FUNCTION_BLOCK_ID:
3166         if (Error Err = rememberAndSkipFunctionBody())
3167           return Err;
3168         NextUnreadBit = Stream.GetCurrentBitNo();
3169         return Error::success();
3170       }
3171     }
3172   }
3173 }
3174 
readBlockInfo()3175 bool BitcodeReaderBase::readBlockInfo() {
3176   Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3177       Stream.ReadBlockInfoBlock();
3178   if (!MaybeNewBlockInfo)
3179     return true; // FIXME Handle the error.
3180   Optional<BitstreamBlockInfo> NewBlockInfo =
3181       std::move(MaybeNewBlockInfo.get());
3182   if (!NewBlockInfo)
3183     return true;
3184   BlockInfo = std::move(*NewBlockInfo);
3185   return false;
3186 }
3187 
parseComdatRecord(ArrayRef<uint64_t> Record)3188 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3189   // v1: [selection_kind, name]
3190   // v2: [strtab_offset, strtab_size, selection_kind]
3191   StringRef Name;
3192   std::tie(Name, Record) = readNameFromStrtab(Record);
3193 
3194   if (Record.empty())
3195     return error("Invalid record");
3196   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3197   std::string OldFormatName;
3198   if (!UseStrtab) {
3199     if (Record.size() < 2)
3200       return error("Invalid record");
3201     unsigned ComdatNameSize = Record[1];
3202     OldFormatName.reserve(ComdatNameSize);
3203     for (unsigned i = 0; i != ComdatNameSize; ++i)
3204       OldFormatName += (char)Record[2 + i];
3205     Name = OldFormatName;
3206   }
3207   Comdat *C = TheModule->getOrInsertComdat(Name);
3208   C->setSelectionKind(SK);
3209   ComdatList.push_back(C);
3210   return Error::success();
3211 }
3212 
inferDSOLocal(GlobalValue * GV)3213 static void inferDSOLocal(GlobalValue *GV) {
3214   // infer dso_local from linkage and visibility if it is not encoded.
3215   if (GV->hasLocalLinkage() ||
3216       (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3217     GV->setDSOLocal(true);
3218 }
3219 
parseGlobalVarRecord(ArrayRef<uint64_t> Record)3220 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3221   // v1: [pointer type, isconst, initid, linkage, alignment, section,
3222   // visibility, threadlocal, unnamed_addr, externally_initialized,
3223   // dllstorageclass, comdat, attributes, preemption specifier,
3224   // partition strtab offset, partition strtab size] (name in VST)
3225   // v2: [strtab_offset, strtab_size, v1]
3226   StringRef Name;
3227   std::tie(Name, Record) = readNameFromStrtab(Record);
3228 
3229   if (Record.size() < 6)
3230     return error("Invalid record");
3231   Type *FullTy = getFullyStructuredTypeByID(Record[0]);
3232   Type *Ty = flattenPointerTypes(FullTy);
3233   if (!Ty)
3234     return error("Invalid record");
3235   bool isConstant = Record[1] & 1;
3236   bool explicitType = Record[1] & 2;
3237   unsigned AddressSpace;
3238   if (explicitType) {
3239     AddressSpace = Record[1] >> 2;
3240   } else {
3241     if (!Ty->isPointerTy())
3242       return error("Invalid type for value");
3243     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3244     std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
3245   }
3246 
3247   uint64_t RawLinkage = Record[3];
3248   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3249   MaybeAlign Alignment;
3250   if (Error Err = parseAlignmentValue(Record[4], Alignment))
3251     return Err;
3252   std::string Section;
3253   if (Record[5]) {
3254     if (Record[5] - 1 >= SectionTable.size())
3255       return error("Invalid ID");
3256     Section = SectionTable[Record[5] - 1];
3257   }
3258   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3259   // Local linkage must have default visibility.
3260   // auto-upgrade `hidden` and `protected` for old bitcode.
3261   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3262     Visibility = getDecodedVisibility(Record[6]);
3263 
3264   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3265   if (Record.size() > 7)
3266     TLM = getDecodedThreadLocalMode(Record[7]);
3267 
3268   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3269   if (Record.size() > 8)
3270     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3271 
3272   bool ExternallyInitialized = false;
3273   if (Record.size() > 9)
3274     ExternallyInitialized = Record[9];
3275 
3276   GlobalVariable *NewGV =
3277       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
3278                          nullptr, TLM, AddressSpace, ExternallyInitialized);
3279   NewGV->setAlignment(Alignment);
3280   if (!Section.empty())
3281     NewGV->setSection(Section);
3282   NewGV->setVisibility(Visibility);
3283   NewGV->setUnnamedAddr(UnnamedAddr);
3284 
3285   if (Record.size() > 10)
3286     NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3287   else
3288     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3289 
3290   FullTy = PointerType::get(FullTy, AddressSpace);
3291   assert(NewGV->getType() == flattenPointerTypes(FullTy) &&
3292          "Incorrect fully specified type for GlobalVariable");
3293   ValueList.push_back(NewGV, FullTy);
3294 
3295   // Remember which value to use for the global initializer.
3296   if (unsigned InitID = Record[2])
3297     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
3298 
3299   if (Record.size() > 11) {
3300     if (unsigned ComdatID = Record[11]) {
3301       if (ComdatID > ComdatList.size())
3302         return error("Invalid global variable comdat ID");
3303       NewGV->setComdat(ComdatList[ComdatID - 1]);
3304     }
3305   } else if (hasImplicitComdat(RawLinkage)) {
3306     NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3307   }
3308 
3309   if (Record.size() > 12) {
3310     auto AS = getAttributes(Record[12]).getFnAttributes();
3311     NewGV->setAttributes(AS);
3312   }
3313 
3314   if (Record.size() > 13) {
3315     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3316   }
3317   inferDSOLocal(NewGV);
3318 
3319   // Check whether we have enough values to read a partition name.
3320   if (Record.size() > 15)
3321     NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3322 
3323   return Error::success();
3324 }
3325 
parseFunctionRecord(ArrayRef<uint64_t> Record)3326 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3327   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3328   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3329   // prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)
3330   // v2: [strtab_offset, strtab_size, v1]
3331   StringRef Name;
3332   std::tie(Name, Record) = readNameFromStrtab(Record);
3333 
3334   if (Record.size() < 8)
3335     return error("Invalid record");
3336   Type *FullFTy = getFullyStructuredTypeByID(Record[0]);
3337   Type *FTy = flattenPointerTypes(FullFTy);
3338   if (!FTy)
3339     return error("Invalid record");
3340   if (isa<PointerType>(FTy))
3341     std::tie(FullFTy, FTy) = getPointerElementTypes(FullFTy);
3342 
3343   if (!isa<FunctionType>(FTy))
3344     return error("Invalid type for value");
3345   auto CC = static_cast<CallingConv::ID>(Record[1]);
3346   if (CC & ~CallingConv::MaxID)
3347     return error("Invalid calling convention ID");
3348 
3349   unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3350   if (Record.size() > 16)
3351     AddrSpace = Record[16];
3352 
3353   Function *Func =
3354       Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
3355                        AddrSpace, Name, TheModule);
3356 
3357   assert(Func->getFunctionType() == flattenPointerTypes(FullFTy) &&
3358          "Incorrect fully specified type provided for function");
3359   FunctionTypes[Func] = cast<FunctionType>(FullFTy);
3360 
3361   Func->setCallingConv(CC);
3362   bool isProto = Record[2];
3363   uint64_t RawLinkage = Record[3];
3364   Func->setLinkage(getDecodedLinkage(RawLinkage));
3365   Func->setAttributes(getAttributes(Record[4]));
3366 
3367   // Upgrade any old-style byval or sret without a type by propagating the
3368   // argument's pointee type. There should be no opaque pointers where the byval
3369   // type is implicit.
3370   for (unsigned i = 0; i != Func->arg_size(); ++i) {
3371     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3372                                      Attribute::InAlloca}) {
3373       if (!Func->hasParamAttribute(i, Kind))
3374         continue;
3375 
3376       Func->removeParamAttr(i, Kind);
3377 
3378       Type *PTy = cast<FunctionType>(FullFTy)->getParamType(i);
3379       Type *PtrEltTy = getPointerElementFlatType(PTy);
3380       Attribute NewAttr;
3381       switch (Kind) {
3382       case Attribute::ByVal:
3383         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3384         break;
3385       case Attribute::StructRet:
3386         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3387         break;
3388       case Attribute::InAlloca:
3389         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3390         break;
3391       default:
3392         llvm_unreachable("not an upgraded type attribute");
3393       }
3394 
3395       Func->addParamAttr(i, NewAttr);
3396     }
3397   }
3398 
3399   MaybeAlign Alignment;
3400   if (Error Err = parseAlignmentValue(Record[5], Alignment))
3401     return Err;
3402   Func->setAlignment(Alignment);
3403   if (Record[6]) {
3404     if (Record[6] - 1 >= SectionTable.size())
3405       return error("Invalid ID");
3406     Func->setSection(SectionTable[Record[6] - 1]);
3407   }
3408   // Local linkage must have default visibility.
3409   // auto-upgrade `hidden` and `protected` for old bitcode.
3410   if (!Func->hasLocalLinkage())
3411     Func->setVisibility(getDecodedVisibility(Record[7]));
3412   if (Record.size() > 8 && Record[8]) {
3413     if (Record[8] - 1 >= GCTable.size())
3414       return error("Invalid ID");
3415     Func->setGC(GCTable[Record[8] - 1]);
3416   }
3417   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3418   if (Record.size() > 9)
3419     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3420   Func->setUnnamedAddr(UnnamedAddr);
3421   if (Record.size() > 10 && Record[10] != 0)
3422     FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
3423 
3424   if (Record.size() > 11)
3425     Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3426   else
3427     upgradeDLLImportExportLinkage(Func, RawLinkage);
3428 
3429   if (Record.size() > 12) {
3430     if (unsigned ComdatID = Record[12]) {
3431       if (ComdatID > ComdatList.size())
3432         return error("Invalid function comdat ID");
3433       Func->setComdat(ComdatList[ComdatID - 1]);
3434     }
3435   } else if (hasImplicitComdat(RawLinkage)) {
3436     Func->setComdat(reinterpret_cast<Comdat *>(1));
3437   }
3438 
3439   if (Record.size() > 13 && Record[13] != 0)
3440     FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
3441 
3442   if (Record.size() > 14 && Record[14] != 0)
3443     FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3444 
3445   if (Record.size() > 15) {
3446     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3447   }
3448   inferDSOLocal(Func);
3449 
3450   // Record[16] is the address space number.
3451 
3452   // Check whether we have enough values to read a partition name.
3453   if (Record.size() > 18)
3454     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3455 
3456   Type *FullTy = PointerType::get(FullFTy, AddrSpace);
3457   assert(Func->getType() == flattenPointerTypes(FullTy) &&
3458          "Incorrect fully specified type provided for Function");
3459   ValueList.push_back(Func, FullTy);
3460 
3461   // If this is a function with a body, remember the prototype we are
3462   // creating now, so that we can match up the body with them later.
3463   if (!isProto) {
3464     Func->setIsMaterializable(true);
3465     FunctionsWithBodies.push_back(Func);
3466     DeferredFunctionInfo[Func] = 0;
3467   }
3468   return Error::success();
3469 }
3470 
parseGlobalIndirectSymbolRecord(unsigned BitCode,ArrayRef<uint64_t> Record)3471 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3472     unsigned BitCode, ArrayRef<uint64_t> Record) {
3473   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3474   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3475   // dllstorageclass, threadlocal, unnamed_addr,
3476   // preemption specifier] (name in VST)
3477   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3478   // visibility, dllstorageclass, threadlocal, unnamed_addr,
3479   // preemption specifier] (name in VST)
3480   // v2: [strtab_offset, strtab_size, v1]
3481   StringRef Name;
3482   std::tie(Name, Record) = readNameFromStrtab(Record);
3483 
3484   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3485   if (Record.size() < (3 + (unsigned)NewRecord))
3486     return error("Invalid record");
3487   unsigned OpNum = 0;
3488   Type *FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
3489   Type *Ty = flattenPointerTypes(FullTy);
3490   if (!Ty)
3491     return error("Invalid record");
3492 
3493   unsigned AddrSpace;
3494   if (!NewRecord) {
3495     auto *PTy = dyn_cast<PointerType>(Ty);
3496     if (!PTy)
3497       return error("Invalid type for value");
3498     std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
3499     AddrSpace = PTy->getAddressSpace();
3500   } else {
3501     AddrSpace = Record[OpNum++];
3502   }
3503 
3504   auto Val = Record[OpNum++];
3505   auto Linkage = Record[OpNum++];
3506   GlobalIndirectSymbol *NewGA;
3507   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3508       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3509     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3510                                 TheModule);
3511   else
3512     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3513                                 nullptr, TheModule);
3514 
3515   assert(NewGA->getValueType() == flattenPointerTypes(FullTy) &&
3516          "Incorrect fully structured type provided for GlobalIndirectSymbol");
3517   // Local linkage must have default visibility.
3518   // auto-upgrade `hidden` and `protected` for old bitcode.
3519   if (OpNum != Record.size()) {
3520     auto VisInd = OpNum++;
3521     if (!NewGA->hasLocalLinkage())
3522       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3523   }
3524   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3525       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
3526     if (OpNum != Record.size())
3527       NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3528     else
3529       upgradeDLLImportExportLinkage(NewGA, Linkage);
3530     if (OpNum != Record.size())
3531       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3532     if (OpNum != Record.size())
3533       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3534   }
3535   if (OpNum != Record.size())
3536     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3537   inferDSOLocal(NewGA);
3538 
3539   // Check whether we have enough values to read a partition name.
3540   if (OpNum + 1 < Record.size()) {
3541     NewGA->setPartition(
3542         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
3543     OpNum += 2;
3544   }
3545 
3546   FullTy = PointerType::get(FullTy, AddrSpace);
3547   assert(NewGA->getType() == flattenPointerTypes(FullTy) &&
3548          "Incorrect fully structured type provided for GlobalIndirectSymbol");
3549   ValueList.push_back(NewGA, FullTy);
3550   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3551   return Error::success();
3552 }
3553 
parseModule(uint64_t ResumeBit,bool ShouldLazyLoadMetadata,DataLayoutCallbackTy DataLayoutCallback)3554 Error BitcodeReader::parseModule(uint64_t ResumeBit,
3555                                  bool ShouldLazyLoadMetadata,
3556                                  DataLayoutCallbackTy DataLayoutCallback) {
3557   if (ResumeBit) {
3558     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
3559       return JumpFailed;
3560   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3561     return Err;
3562 
3563   SmallVector<uint64_t, 64> Record;
3564 
3565   // Parts of bitcode parsing depend on the datalayout.  Make sure we
3566   // finalize the datalayout before we run any of that code.
3567   bool ResolvedDataLayout = false;
3568   auto ResolveDataLayout = [&] {
3569     if (ResolvedDataLayout)
3570       return;
3571 
3572     // datalayout and triple can't be parsed after this point.
3573     ResolvedDataLayout = true;
3574 
3575     // Upgrade data layout string.
3576     std::string DL = llvm::UpgradeDataLayoutString(
3577         TheModule->getDataLayoutStr(), TheModule->getTargetTriple());
3578     TheModule->setDataLayout(DL);
3579 
3580     if (auto LayoutOverride =
3581             DataLayoutCallback(TheModule->getTargetTriple()))
3582       TheModule->setDataLayout(*LayoutOverride);
3583   };
3584 
3585   // Read all the records for this module.
3586   while (true) {
3587     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3588     if (!MaybeEntry)
3589       return MaybeEntry.takeError();
3590     llvm::BitstreamEntry Entry = MaybeEntry.get();
3591 
3592     switch (Entry.Kind) {
3593     case BitstreamEntry::Error:
3594       return error("Malformed block");
3595     case BitstreamEntry::EndBlock:
3596       ResolveDataLayout();
3597       return globalCleanup();
3598 
3599     case BitstreamEntry::SubBlock:
3600       switch (Entry.ID) {
3601       default:  // Skip unknown content.
3602         if (Error Err = Stream.SkipBlock())
3603           return Err;
3604         break;
3605       case bitc::BLOCKINFO_BLOCK_ID:
3606         if (readBlockInfo())
3607           return error("Malformed block");
3608         break;
3609       case bitc::PARAMATTR_BLOCK_ID:
3610         if (Error Err = parseAttributeBlock())
3611           return Err;
3612         break;
3613       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3614         if (Error Err = parseAttributeGroupBlock())
3615           return Err;
3616         break;
3617       case bitc::TYPE_BLOCK_ID_NEW:
3618         if (Error Err = parseTypeTable())
3619           return Err;
3620         break;
3621       case bitc::VALUE_SYMTAB_BLOCK_ID:
3622         if (!SeenValueSymbolTable) {
3623           // Either this is an old form VST without function index and an
3624           // associated VST forward declaration record (which would have caused
3625           // the VST to be jumped to and parsed before it was encountered
3626           // normally in the stream), or there were no function blocks to
3627           // trigger an earlier parsing of the VST.
3628           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3629           if (Error Err = parseValueSymbolTable())
3630             return Err;
3631           SeenValueSymbolTable = true;
3632         } else {
3633           // We must have had a VST forward declaration record, which caused
3634           // the parser to jump to and parse the VST earlier.
3635           assert(VSTOffset > 0);
3636           if (Error Err = Stream.SkipBlock())
3637             return Err;
3638         }
3639         break;
3640       case bitc::CONSTANTS_BLOCK_ID:
3641         if (Error Err = parseConstants())
3642           return Err;
3643         if (Error Err = resolveGlobalAndIndirectSymbolInits())
3644           return Err;
3645         break;
3646       case bitc::METADATA_BLOCK_ID:
3647         if (ShouldLazyLoadMetadata) {
3648           if (Error Err = rememberAndSkipMetadata())
3649             return Err;
3650           break;
3651         }
3652         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3653         if (Error Err = MDLoader->parseModuleMetadata())
3654           return Err;
3655         break;
3656       case bitc::METADATA_KIND_BLOCK_ID:
3657         if (Error Err = MDLoader->parseMetadataKinds())
3658           return Err;
3659         break;
3660       case bitc::FUNCTION_BLOCK_ID:
3661         ResolveDataLayout();
3662 
3663         // If this is the first function body we've seen, reverse the
3664         // FunctionsWithBodies list.
3665         if (!SeenFirstFunctionBody) {
3666           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3667           if (Error Err = globalCleanup())
3668             return Err;
3669           SeenFirstFunctionBody = true;
3670         }
3671 
3672         if (VSTOffset > 0) {
3673           // If we have a VST forward declaration record, make sure we
3674           // parse the VST now if we haven't already. It is needed to
3675           // set up the DeferredFunctionInfo vector for lazy reading.
3676           if (!SeenValueSymbolTable) {
3677             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3678               return Err;
3679             SeenValueSymbolTable = true;
3680             // Fall through so that we record the NextUnreadBit below.
3681             // This is necessary in case we have an anonymous function that
3682             // is later materialized. Since it will not have a VST entry we
3683             // need to fall back to the lazy parse to find its offset.
3684           } else {
3685             // If we have a VST forward declaration record, but have already
3686             // parsed the VST (just above, when the first function body was
3687             // encountered here), then we are resuming the parse after
3688             // materializing functions. The ResumeBit points to the
3689             // start of the last function block recorded in the
3690             // DeferredFunctionInfo map. Skip it.
3691             if (Error Err = Stream.SkipBlock())
3692               return Err;
3693             continue;
3694           }
3695         }
3696 
3697         // Support older bitcode files that did not have the function
3698         // index in the VST, nor a VST forward declaration record, as
3699         // well as anonymous functions that do not have VST entries.
3700         // Build the DeferredFunctionInfo vector on the fly.
3701         if (Error Err = rememberAndSkipFunctionBody())
3702           return Err;
3703 
3704         // Suspend parsing when we reach the function bodies. Subsequent
3705         // materialization calls will resume it when necessary. If the bitcode
3706         // file is old, the symbol table will be at the end instead and will not
3707         // have been seen yet. In this case, just finish the parse now.
3708         if (SeenValueSymbolTable) {
3709           NextUnreadBit = Stream.GetCurrentBitNo();
3710           // After the VST has been parsed, we need to make sure intrinsic name
3711           // are auto-upgraded.
3712           return globalCleanup();
3713         }
3714         break;
3715       case bitc::USELIST_BLOCK_ID:
3716         if (Error Err = parseUseLists())
3717           return Err;
3718         break;
3719       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3720         if (Error Err = parseOperandBundleTags())
3721           return Err;
3722         break;
3723       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3724         if (Error Err = parseSyncScopeNames())
3725           return Err;
3726         break;
3727       }
3728       continue;
3729 
3730     case BitstreamEntry::Record:
3731       // The interesting case.
3732       break;
3733     }
3734 
3735     // Read a record.
3736     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3737     if (!MaybeBitCode)
3738       return MaybeBitCode.takeError();
3739     switch (unsigned BitCode = MaybeBitCode.get()) {
3740     default: break;  // Default behavior, ignore unknown content.
3741     case bitc::MODULE_CODE_VERSION: {
3742       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3743       if (!VersionOrErr)
3744         return VersionOrErr.takeError();
3745       UseRelativeIDs = *VersionOrErr >= 1;
3746       break;
3747     }
3748     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3749       if (ResolvedDataLayout)
3750         return error("target triple too late in module");
3751       std::string S;
3752       if (convertToString(Record, 0, S))
3753         return error("Invalid record");
3754       TheModule->setTargetTriple(S);
3755       break;
3756     }
3757     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3758       if (ResolvedDataLayout)
3759         return error("datalayout too late in module");
3760       std::string S;
3761       if (convertToString(Record, 0, S))
3762         return error("Invalid record");
3763       TheModule->setDataLayout(S);
3764       break;
3765     }
3766     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3767       std::string S;
3768       if (convertToString(Record, 0, S))
3769         return error("Invalid record");
3770       TheModule->setModuleInlineAsm(S);
3771       break;
3772     }
3773     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3774       // Deprecated, but still needed to read old bitcode files.
3775       std::string S;
3776       if (convertToString(Record, 0, S))
3777         return error("Invalid record");
3778       // Ignore value.
3779       break;
3780     }
3781     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3782       std::string S;
3783       if (convertToString(Record, 0, S))
3784         return error("Invalid record");
3785       SectionTable.push_back(S);
3786       break;
3787     }
3788     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3789       std::string S;
3790       if (convertToString(Record, 0, S))
3791         return error("Invalid record");
3792       GCTable.push_back(S);
3793       break;
3794     }
3795     case bitc::MODULE_CODE_COMDAT:
3796       if (Error Err = parseComdatRecord(Record))
3797         return Err;
3798       break;
3799     case bitc::MODULE_CODE_GLOBALVAR:
3800       if (Error Err = parseGlobalVarRecord(Record))
3801         return Err;
3802       break;
3803     case bitc::MODULE_CODE_FUNCTION:
3804       ResolveDataLayout();
3805       if (Error Err = parseFunctionRecord(Record))
3806         return Err;
3807       break;
3808     case bitc::MODULE_CODE_IFUNC:
3809     case bitc::MODULE_CODE_ALIAS:
3810     case bitc::MODULE_CODE_ALIAS_OLD:
3811       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3812         return Err;
3813       break;
3814     /// MODULE_CODE_VSTOFFSET: [offset]
3815     case bitc::MODULE_CODE_VSTOFFSET:
3816       if (Record.empty())
3817         return error("Invalid record");
3818       // Note that we subtract 1 here because the offset is relative to one word
3819       // before the start of the identification or module block, which was
3820       // historically always the start of the regular bitcode header.
3821       VSTOffset = Record[0] - 1;
3822       break;
3823     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3824     case bitc::MODULE_CODE_SOURCE_FILENAME:
3825       SmallString<128> ValueName;
3826       if (convertToString(Record, 0, ValueName))
3827         return error("Invalid record");
3828       TheModule->setSourceFileName(ValueName);
3829       break;
3830     }
3831     Record.clear();
3832   }
3833 }
3834 
parseBitcodeInto(Module * M,bool ShouldLazyLoadMetadata,bool IsImporting,DataLayoutCallbackTy DataLayoutCallback)3835 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3836                                       bool IsImporting,
3837                                       DataLayoutCallbackTy DataLayoutCallback) {
3838   TheModule = M;
3839   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3840                             [&](unsigned ID) { return getTypeByID(ID); });
3841   return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback);
3842 }
3843 
typeCheckLoadStoreInst(Type * ValType,Type * PtrType)3844 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3845   if (!isa<PointerType>(PtrType))
3846     return error("Load/Store operand is not a pointer type");
3847 
3848   if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType))
3849     return error("Explicit load/store type does not match pointee "
3850                  "type of pointer operand");
3851   if (!PointerType::isLoadableOrStorableType(ValType))
3852     return error("Cannot load/store from pointer");
3853   return Error::success();
3854 }
3855 
propagateByValSRetTypes(CallBase * CB,ArrayRef<Type * > ArgsFullTys)3856 void BitcodeReader::propagateByValSRetTypes(CallBase *CB,
3857                                             ArrayRef<Type *> ArgsFullTys) {
3858   for (unsigned i = 0; i != CB->arg_size(); ++i) {
3859     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3860                                      Attribute::InAlloca}) {
3861       if (!CB->paramHasAttr(i, Kind))
3862         continue;
3863 
3864       CB->removeParamAttr(i, Kind);
3865 
3866       Type *PtrEltTy = getPointerElementFlatType(ArgsFullTys[i]);
3867       Attribute NewAttr;
3868       switch (Kind) {
3869       case Attribute::ByVal:
3870         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3871         break;
3872       case Attribute::StructRet:
3873         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3874         break;
3875       case Attribute::InAlloca:
3876         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3877         break;
3878       default:
3879         llvm_unreachable("not an upgraded type attribute");
3880       }
3881 
3882       CB->addParamAttr(i, NewAttr);
3883     }
3884   }
3885 }
3886 
3887 /// Lazily parse the specified function body block.
parseFunctionBody(Function * F)3888 Error BitcodeReader::parseFunctionBody(Function *F) {
3889   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3890     return Err;
3891 
3892   // Unexpected unresolved metadata when parsing function.
3893   if (MDLoader->hasFwdRefs())
3894     return error("Invalid function metadata: incoming forward references");
3895 
3896   InstructionList.clear();
3897   unsigned ModuleValueListSize = ValueList.size();
3898   unsigned ModuleMDLoaderSize = MDLoader->size();
3899 
3900   // Add all the function arguments to the value table.
3901   unsigned ArgNo = 0;
3902   FunctionType *FullFTy = FunctionTypes[F];
3903   for (Argument &I : F->args()) {
3904     assert(I.getType() == flattenPointerTypes(FullFTy->getParamType(ArgNo)) &&
3905            "Incorrect fully specified type for Function Argument");
3906     ValueList.push_back(&I, FullFTy->getParamType(ArgNo++));
3907   }
3908   unsigned NextValueNo = ValueList.size();
3909   BasicBlock *CurBB = nullptr;
3910   unsigned CurBBNo = 0;
3911 
3912   DebugLoc LastLoc;
3913   auto getLastInstruction = [&]() -> Instruction * {
3914     if (CurBB && !CurBB->empty())
3915       return &CurBB->back();
3916     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3917              !FunctionBBs[CurBBNo - 1]->empty())
3918       return &FunctionBBs[CurBBNo - 1]->back();
3919     return nullptr;
3920   };
3921 
3922   std::vector<OperandBundleDef> OperandBundles;
3923 
3924   // Read all the records.
3925   SmallVector<uint64_t, 64> Record;
3926 
3927   while (true) {
3928     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3929     if (!MaybeEntry)
3930       return MaybeEntry.takeError();
3931     llvm::BitstreamEntry Entry = MaybeEntry.get();
3932 
3933     switch (Entry.Kind) {
3934     case BitstreamEntry::Error:
3935       return error("Malformed block");
3936     case BitstreamEntry::EndBlock:
3937       goto OutOfRecordLoop;
3938 
3939     case BitstreamEntry::SubBlock:
3940       switch (Entry.ID) {
3941       default:  // Skip unknown content.
3942         if (Error Err = Stream.SkipBlock())
3943           return Err;
3944         break;
3945       case bitc::CONSTANTS_BLOCK_ID:
3946         if (Error Err = parseConstants())
3947           return Err;
3948         NextValueNo = ValueList.size();
3949         break;
3950       case bitc::VALUE_SYMTAB_BLOCK_ID:
3951         if (Error Err = parseValueSymbolTable())
3952           return Err;
3953         break;
3954       case bitc::METADATA_ATTACHMENT_ID:
3955         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3956           return Err;
3957         break;
3958       case bitc::METADATA_BLOCK_ID:
3959         assert(DeferredMetadataInfo.empty() &&
3960                "Must read all module-level metadata before function-level");
3961         if (Error Err = MDLoader->parseFunctionMetadata())
3962           return Err;
3963         break;
3964       case bitc::USELIST_BLOCK_ID:
3965         if (Error Err = parseUseLists())
3966           return Err;
3967         break;
3968       }
3969       continue;
3970 
3971     case BitstreamEntry::Record:
3972       // The interesting case.
3973       break;
3974     }
3975 
3976     // Read a record.
3977     Record.clear();
3978     Instruction *I = nullptr;
3979     Type *FullTy = nullptr;
3980     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3981     if (!MaybeBitCode)
3982       return MaybeBitCode.takeError();
3983     switch (unsigned BitCode = MaybeBitCode.get()) {
3984     default: // Default behavior: reject
3985       return error("Invalid value");
3986     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3987       if (Record.empty() || Record[0] == 0)
3988         return error("Invalid record");
3989       // Create all the basic blocks for the function.
3990       FunctionBBs.resize(Record[0]);
3991 
3992       // See if anything took the address of blocks in this function.
3993       auto BBFRI = BasicBlockFwdRefs.find(F);
3994       if (BBFRI == BasicBlockFwdRefs.end()) {
3995         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3996           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3997       } else {
3998         auto &BBRefs = BBFRI->second;
3999         // Check for invalid basic block references.
4000         if (BBRefs.size() > FunctionBBs.size())
4001           return error("Invalid ID");
4002         assert(!BBRefs.empty() && "Unexpected empty array");
4003         assert(!BBRefs.front() && "Invalid reference to entry block");
4004         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4005              ++I)
4006           if (I < RE && BBRefs[I]) {
4007             BBRefs[I]->insertInto(F);
4008             FunctionBBs[I] = BBRefs[I];
4009           } else {
4010             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4011           }
4012 
4013         // Erase from the table.
4014         BasicBlockFwdRefs.erase(BBFRI);
4015       }
4016 
4017       CurBB = FunctionBBs[0];
4018       continue;
4019     }
4020 
4021     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4022       // This record indicates that the last instruction is at the same
4023       // location as the previous instruction with a location.
4024       I = getLastInstruction();
4025 
4026       if (!I)
4027         return error("Invalid record");
4028       I->setDebugLoc(LastLoc);
4029       I = nullptr;
4030       continue;
4031 
4032     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4033       I = getLastInstruction();
4034       if (!I || Record.size() < 4)
4035         return error("Invalid record");
4036 
4037       unsigned Line = Record[0], Col = Record[1];
4038       unsigned ScopeID = Record[2], IAID = Record[3];
4039       bool isImplicitCode = Record.size() == 5 && Record[4];
4040 
4041       MDNode *Scope = nullptr, *IA = nullptr;
4042       if (ScopeID) {
4043         Scope = dyn_cast_or_null<MDNode>(
4044             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
4045         if (!Scope)
4046           return error("Invalid record");
4047       }
4048       if (IAID) {
4049         IA = dyn_cast_or_null<MDNode>(
4050             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
4051         if (!IA)
4052           return error("Invalid record");
4053       }
4054       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4055                                 isImplicitCode);
4056       I->setDebugLoc(LastLoc);
4057       I = nullptr;
4058       continue;
4059     }
4060     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
4061       unsigned OpNum = 0;
4062       Value *LHS;
4063       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4064           OpNum+1 > Record.size())
4065         return error("Invalid record");
4066 
4067       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
4068       if (Opc == -1)
4069         return error("Invalid record");
4070       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
4071       InstructionList.push_back(I);
4072       if (OpNum < Record.size()) {
4073         if (isa<FPMathOperator>(I)) {
4074           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4075           if (FMF.any())
4076             I->setFastMathFlags(FMF);
4077         }
4078       }
4079       break;
4080     }
4081     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4082       unsigned OpNum = 0;
4083       Value *LHS, *RHS;
4084       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4085           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4086           OpNum+1 > Record.size())
4087         return error("Invalid record");
4088 
4089       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4090       if (Opc == -1)
4091         return error("Invalid record");
4092       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4093       InstructionList.push_back(I);
4094       if (OpNum < Record.size()) {
4095         if (Opc == Instruction::Add ||
4096             Opc == Instruction::Sub ||
4097             Opc == Instruction::Mul ||
4098             Opc == Instruction::Shl) {
4099           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4100             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4101           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4102             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4103         } else if (Opc == Instruction::SDiv ||
4104                    Opc == Instruction::UDiv ||
4105                    Opc == Instruction::LShr ||
4106                    Opc == Instruction::AShr) {
4107           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4108             cast<BinaryOperator>(I)->setIsExact(true);
4109         } else if (isa<FPMathOperator>(I)) {
4110           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4111           if (FMF.any())
4112             I->setFastMathFlags(FMF);
4113         }
4114 
4115       }
4116       break;
4117     }
4118     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4119       unsigned OpNum = 0;
4120       Value *Op;
4121       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4122           OpNum+2 != Record.size())
4123         return error("Invalid record");
4124 
4125       FullTy = getFullyStructuredTypeByID(Record[OpNum]);
4126       Type *ResTy = flattenPointerTypes(FullTy);
4127       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4128       if (Opc == -1 || !ResTy)
4129         return error("Invalid record");
4130       Instruction *Temp = nullptr;
4131       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4132         if (Temp) {
4133           InstructionList.push_back(Temp);
4134           assert(CurBB && "No current BB?");
4135           CurBB->getInstList().push_back(Temp);
4136         }
4137       } else {
4138         auto CastOp = (Instruction::CastOps)Opc;
4139         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4140           return error("Invalid cast");
4141         I = CastInst::Create(CastOp, Op, ResTy);
4142       }
4143       InstructionList.push_back(I);
4144       break;
4145     }
4146     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4147     case bitc::FUNC_CODE_INST_GEP_OLD:
4148     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4149       unsigned OpNum = 0;
4150 
4151       Type *Ty;
4152       bool InBounds;
4153 
4154       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4155         InBounds = Record[OpNum++];
4156         FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
4157         Ty = flattenPointerTypes(FullTy);
4158       } else {
4159         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4160         Ty = nullptr;
4161       }
4162 
4163       Value *BasePtr;
4164       Type *FullBaseTy = nullptr;
4165       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, &FullBaseTy))
4166         return error("Invalid record");
4167 
4168       if (!Ty) {
4169         std::tie(FullTy, Ty) =
4170             getPointerElementTypes(FullBaseTy->getScalarType());
4171       } else if (!cast<PointerType>(FullBaseTy->getScalarType())
4172                       ->isOpaqueOrPointeeTypeMatches(Ty))
4173         return error(
4174             "Explicit gep type does not match pointee type of pointer operand");
4175 
4176       SmallVector<Value*, 16> GEPIdx;
4177       while (OpNum != Record.size()) {
4178         Value *Op;
4179         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4180           return error("Invalid record");
4181         GEPIdx.push_back(Op);
4182       }
4183 
4184       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4185       FullTy = GetElementPtrInst::getGEPReturnType(FullTy, I, GEPIdx);
4186 
4187       InstructionList.push_back(I);
4188       if (InBounds)
4189         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4190       break;
4191     }
4192 
4193     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4194                                        // EXTRACTVAL: [opty, opval, n x indices]
4195       unsigned OpNum = 0;
4196       Value *Agg;
4197       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy))
4198         return error("Invalid record");
4199 
4200       unsigned RecSize = Record.size();
4201       if (OpNum == RecSize)
4202         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4203 
4204       SmallVector<unsigned, 4> EXTRACTVALIdx;
4205       for (; OpNum != RecSize; ++OpNum) {
4206         bool IsArray = FullTy->isArrayTy();
4207         bool IsStruct = FullTy->isStructTy();
4208         uint64_t Index = Record[OpNum];
4209 
4210         if (!IsStruct && !IsArray)
4211           return error("EXTRACTVAL: Invalid type");
4212         if ((unsigned)Index != Index)
4213           return error("Invalid value");
4214         if (IsStruct && Index >= FullTy->getStructNumElements())
4215           return error("EXTRACTVAL: Invalid struct index");
4216         if (IsArray && Index >= FullTy->getArrayNumElements())
4217           return error("EXTRACTVAL: Invalid array index");
4218         EXTRACTVALIdx.push_back((unsigned)Index);
4219 
4220         if (IsStruct)
4221           FullTy = FullTy->getStructElementType(Index);
4222         else
4223           FullTy = FullTy->getArrayElementType();
4224       }
4225 
4226       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4227       InstructionList.push_back(I);
4228       break;
4229     }
4230 
4231     case bitc::FUNC_CODE_INST_INSERTVAL: {
4232                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4233       unsigned OpNum = 0;
4234       Value *Agg;
4235       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy))
4236         return error("Invalid record");
4237       Value *Val;
4238       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4239         return error("Invalid record");
4240 
4241       unsigned RecSize = Record.size();
4242       if (OpNum == RecSize)
4243         return error("INSERTVAL: Invalid instruction with 0 indices");
4244 
4245       SmallVector<unsigned, 4> INSERTVALIdx;
4246       Type *CurTy = Agg->getType();
4247       for (; OpNum != RecSize; ++OpNum) {
4248         bool IsArray = CurTy->isArrayTy();
4249         bool IsStruct = CurTy->isStructTy();
4250         uint64_t Index = Record[OpNum];
4251 
4252         if (!IsStruct && !IsArray)
4253           return error("INSERTVAL: Invalid type");
4254         if ((unsigned)Index != Index)
4255           return error("Invalid value");
4256         if (IsStruct && Index >= CurTy->getStructNumElements())
4257           return error("INSERTVAL: Invalid struct index");
4258         if (IsArray && Index >= CurTy->getArrayNumElements())
4259           return error("INSERTVAL: Invalid array index");
4260 
4261         INSERTVALIdx.push_back((unsigned)Index);
4262         if (IsStruct)
4263           CurTy = CurTy->getStructElementType(Index);
4264         else
4265           CurTy = CurTy->getArrayElementType();
4266       }
4267 
4268       if (CurTy != Val->getType())
4269         return error("Inserted value type doesn't match aggregate type");
4270 
4271       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4272       InstructionList.push_back(I);
4273       break;
4274     }
4275 
4276     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4277       // obsolete form of select
4278       // handles select i1 ... in old bitcode
4279       unsigned OpNum = 0;
4280       Value *TrueVal, *FalseVal, *Cond;
4281       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) ||
4282           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4283           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4284         return error("Invalid record");
4285 
4286       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4287       InstructionList.push_back(I);
4288       break;
4289     }
4290 
4291     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4292       // new form of select
4293       // handles select i1 or select [N x i1]
4294       unsigned OpNum = 0;
4295       Value *TrueVal, *FalseVal, *Cond;
4296       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) ||
4297           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4298           getValueTypePair(Record, OpNum, NextValueNo, Cond))
4299         return error("Invalid record");
4300 
4301       // select condition can be either i1 or [N x i1]
4302       if (VectorType* vector_type =
4303           dyn_cast<VectorType>(Cond->getType())) {
4304         // expect <n x i1>
4305         if (vector_type->getElementType() != Type::getInt1Ty(Context))
4306           return error("Invalid type for value");
4307       } else {
4308         // expect i1
4309         if (Cond->getType() != Type::getInt1Ty(Context))
4310           return error("Invalid type for value");
4311       }
4312 
4313       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4314       InstructionList.push_back(I);
4315       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
4316         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4317         if (FMF.any())
4318           I->setFastMathFlags(FMF);
4319       }
4320       break;
4321     }
4322 
4323     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4324       unsigned OpNum = 0;
4325       Value *Vec, *Idx;
4326       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy) ||
4327           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4328         return error("Invalid record");
4329       if (!Vec->getType()->isVectorTy())
4330         return error("Invalid type for value");
4331       I = ExtractElementInst::Create(Vec, Idx);
4332       FullTy = cast<VectorType>(FullTy)->getElementType();
4333       InstructionList.push_back(I);
4334       break;
4335     }
4336 
4337     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4338       unsigned OpNum = 0;
4339       Value *Vec, *Elt, *Idx;
4340       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy))
4341         return error("Invalid record");
4342       if (!Vec->getType()->isVectorTy())
4343         return error("Invalid type for value");
4344       if (popValue(Record, OpNum, NextValueNo,
4345                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4346           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4347         return error("Invalid record");
4348       I = InsertElementInst::Create(Vec, Elt, Idx);
4349       InstructionList.push_back(I);
4350       break;
4351     }
4352 
4353     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4354       unsigned OpNum = 0;
4355       Value *Vec1, *Vec2, *Mask;
4356       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, &FullTy) ||
4357           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4358         return error("Invalid record");
4359 
4360       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4361         return error("Invalid record");
4362       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4363         return error("Invalid type for value");
4364 
4365       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4366       FullTy =
4367           VectorType::get(cast<VectorType>(FullTy)->getElementType(),
4368                           cast<VectorType>(Mask->getType())->getElementCount());
4369       InstructionList.push_back(I);
4370       break;
4371     }
4372 
4373     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
4374       // Old form of ICmp/FCmp returning bool
4375       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4376       // both legal on vectors but had different behaviour.
4377     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4378       // FCmp/ICmp returning bool or vector of bool
4379 
4380       unsigned OpNum = 0;
4381       Value *LHS, *RHS;
4382       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4383           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4384         return error("Invalid record");
4385 
4386       if (OpNum >= Record.size())
4387         return error(
4388             "Invalid record: operand number exceeded available operands");
4389 
4390       unsigned PredVal = Record[OpNum];
4391       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4392       FastMathFlags FMF;
4393       if (IsFP && Record.size() > OpNum+1)
4394         FMF = getDecodedFastMathFlags(Record[++OpNum]);
4395 
4396       if (OpNum+1 != Record.size())
4397         return error("Invalid record");
4398 
4399       if (LHS->getType()->isFPOrFPVectorTy())
4400         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4401       else
4402         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4403 
4404       if (FMF.any())
4405         I->setFastMathFlags(FMF);
4406       InstructionList.push_back(I);
4407       break;
4408     }
4409 
4410     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4411       {
4412         unsigned Size = Record.size();
4413         if (Size == 0) {
4414           I = ReturnInst::Create(Context);
4415           InstructionList.push_back(I);
4416           break;
4417         }
4418 
4419         unsigned OpNum = 0;
4420         Value *Op = nullptr;
4421         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4422           return error("Invalid record");
4423         if (OpNum != Record.size())
4424           return error("Invalid record");
4425 
4426         I = ReturnInst::Create(Context, Op);
4427         InstructionList.push_back(I);
4428         break;
4429       }
4430     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4431       if (Record.size() != 1 && Record.size() != 3)
4432         return error("Invalid record");
4433       BasicBlock *TrueDest = getBasicBlock(Record[0]);
4434       if (!TrueDest)
4435         return error("Invalid record");
4436 
4437       if (Record.size() == 1) {
4438         I = BranchInst::Create(TrueDest);
4439         InstructionList.push_back(I);
4440       }
4441       else {
4442         BasicBlock *FalseDest = getBasicBlock(Record[1]);
4443         Value *Cond = getValue(Record, 2, NextValueNo,
4444                                Type::getInt1Ty(Context));
4445         if (!FalseDest || !Cond)
4446           return error("Invalid record");
4447         I = BranchInst::Create(TrueDest, FalseDest, Cond);
4448         InstructionList.push_back(I);
4449       }
4450       break;
4451     }
4452     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4453       if (Record.size() != 1 && Record.size() != 2)
4454         return error("Invalid record");
4455       unsigned Idx = 0;
4456       Value *CleanupPad =
4457           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4458       if (!CleanupPad)
4459         return error("Invalid record");
4460       BasicBlock *UnwindDest = nullptr;
4461       if (Record.size() == 2) {
4462         UnwindDest = getBasicBlock(Record[Idx++]);
4463         if (!UnwindDest)
4464           return error("Invalid record");
4465       }
4466 
4467       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4468       InstructionList.push_back(I);
4469       break;
4470     }
4471     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4472       if (Record.size() != 2)
4473         return error("Invalid record");
4474       unsigned Idx = 0;
4475       Value *CatchPad =
4476           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4477       if (!CatchPad)
4478         return error("Invalid record");
4479       BasicBlock *BB = getBasicBlock(Record[Idx++]);
4480       if (!BB)
4481         return error("Invalid record");
4482 
4483       I = CatchReturnInst::Create(CatchPad, BB);
4484       InstructionList.push_back(I);
4485       break;
4486     }
4487     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4488       // We must have, at minimum, the outer scope and the number of arguments.
4489       if (Record.size() < 2)
4490         return error("Invalid record");
4491 
4492       unsigned Idx = 0;
4493 
4494       Value *ParentPad =
4495           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4496 
4497       unsigned NumHandlers = Record[Idx++];
4498 
4499       SmallVector<BasicBlock *, 2> Handlers;
4500       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4501         BasicBlock *BB = getBasicBlock(Record[Idx++]);
4502         if (!BB)
4503           return error("Invalid record");
4504         Handlers.push_back(BB);
4505       }
4506 
4507       BasicBlock *UnwindDest = nullptr;
4508       if (Idx + 1 == Record.size()) {
4509         UnwindDest = getBasicBlock(Record[Idx++]);
4510         if (!UnwindDest)
4511           return error("Invalid record");
4512       }
4513 
4514       if (Record.size() != Idx)
4515         return error("Invalid record");
4516 
4517       auto *CatchSwitch =
4518           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4519       for (BasicBlock *Handler : Handlers)
4520         CatchSwitch->addHandler(Handler);
4521       I = CatchSwitch;
4522       InstructionList.push_back(I);
4523       break;
4524     }
4525     case bitc::FUNC_CODE_INST_CATCHPAD:
4526     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4527       // We must have, at minimum, the outer scope and the number of arguments.
4528       if (Record.size() < 2)
4529         return error("Invalid record");
4530 
4531       unsigned Idx = 0;
4532 
4533       Value *ParentPad =
4534           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4535 
4536       unsigned NumArgOperands = Record[Idx++];
4537 
4538       SmallVector<Value *, 2> Args;
4539       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4540         Value *Val;
4541         if (getValueTypePair(Record, Idx, NextValueNo, Val))
4542           return error("Invalid record");
4543         Args.push_back(Val);
4544       }
4545 
4546       if (Record.size() != Idx)
4547         return error("Invalid record");
4548 
4549       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4550         I = CleanupPadInst::Create(ParentPad, Args);
4551       else
4552         I = CatchPadInst::Create(ParentPad, Args);
4553       InstructionList.push_back(I);
4554       break;
4555     }
4556     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4557       // Check magic
4558       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4559         // "New" SwitchInst format with case ranges. The changes to write this
4560         // format were reverted but we still recognize bitcode that uses it.
4561         // Hopefully someday we will have support for case ranges and can use
4562         // this format again.
4563 
4564         Type *OpTy = getTypeByID(Record[1]);
4565         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4566 
4567         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4568         BasicBlock *Default = getBasicBlock(Record[3]);
4569         if (!OpTy || !Cond || !Default)
4570           return error("Invalid record");
4571 
4572         unsigned NumCases = Record[4];
4573 
4574         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4575         InstructionList.push_back(SI);
4576 
4577         unsigned CurIdx = 5;
4578         for (unsigned i = 0; i != NumCases; ++i) {
4579           SmallVector<ConstantInt*, 1> CaseVals;
4580           unsigned NumItems = Record[CurIdx++];
4581           for (unsigned ci = 0; ci != NumItems; ++ci) {
4582             bool isSingleNumber = Record[CurIdx++];
4583 
4584             APInt Low;
4585             unsigned ActiveWords = 1;
4586             if (ValueBitWidth > 64)
4587               ActiveWords = Record[CurIdx++];
4588             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4589                                 ValueBitWidth);
4590             CurIdx += ActiveWords;
4591 
4592             if (!isSingleNumber) {
4593               ActiveWords = 1;
4594               if (ValueBitWidth > 64)
4595                 ActiveWords = Record[CurIdx++];
4596               APInt High = readWideAPInt(
4597                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4598               CurIdx += ActiveWords;
4599 
4600               // FIXME: It is not clear whether values in the range should be
4601               // compared as signed or unsigned values. The partially
4602               // implemented changes that used this format in the past used
4603               // unsigned comparisons.
4604               for ( ; Low.ule(High); ++Low)
4605                 CaseVals.push_back(ConstantInt::get(Context, Low));
4606             } else
4607               CaseVals.push_back(ConstantInt::get(Context, Low));
4608           }
4609           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4610           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4611                  cve = CaseVals.end(); cvi != cve; ++cvi)
4612             SI->addCase(*cvi, DestBB);
4613         }
4614         I = SI;
4615         break;
4616       }
4617 
4618       // Old SwitchInst format without case ranges.
4619 
4620       if (Record.size() < 3 || (Record.size() & 1) == 0)
4621         return error("Invalid record");
4622       Type *OpTy = getTypeByID(Record[0]);
4623       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4624       BasicBlock *Default = getBasicBlock(Record[2]);
4625       if (!OpTy || !Cond || !Default)
4626         return error("Invalid record");
4627       unsigned NumCases = (Record.size()-3)/2;
4628       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4629       InstructionList.push_back(SI);
4630       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4631         ConstantInt *CaseVal =
4632           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4633         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4634         if (!CaseVal || !DestBB) {
4635           delete SI;
4636           return error("Invalid record");
4637         }
4638         SI->addCase(CaseVal, DestBB);
4639       }
4640       I = SI;
4641       break;
4642     }
4643     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4644       if (Record.size() < 2)
4645         return error("Invalid record");
4646       Type *OpTy = getTypeByID(Record[0]);
4647       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4648       if (!OpTy || !Address)
4649         return error("Invalid record");
4650       unsigned NumDests = Record.size()-2;
4651       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4652       InstructionList.push_back(IBI);
4653       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4654         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4655           IBI->addDestination(DestBB);
4656         } else {
4657           delete IBI;
4658           return error("Invalid record");
4659         }
4660       }
4661       I = IBI;
4662       break;
4663     }
4664 
4665     case bitc::FUNC_CODE_INST_INVOKE: {
4666       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4667       if (Record.size() < 4)
4668         return error("Invalid record");
4669       unsigned OpNum = 0;
4670       AttributeList PAL = getAttributes(Record[OpNum++]);
4671       unsigned CCInfo = Record[OpNum++];
4672       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4673       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4674 
4675       FunctionType *FTy = nullptr;
4676       FunctionType *FullFTy = nullptr;
4677       if ((CCInfo >> 13) & 1) {
4678         FullFTy =
4679             dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
4680         if (!FullFTy)
4681           return error("Explicit invoke type is not a function type");
4682         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4683       }
4684 
4685       Value *Callee;
4686       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
4687         return error("Invalid record");
4688 
4689       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4690       if (!CalleeTy)
4691         return error("Callee is not a pointer");
4692       if (!FTy) {
4693         FullFTy =
4694             dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
4695         if (!FullFTy)
4696           return error("Callee is not of pointer to function type");
4697         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4698       } else if (getPointerElementFlatType(FullTy) != FTy)
4699         return error("Explicit invoke type does not match pointee type of "
4700                      "callee operand");
4701       if (Record.size() < FTy->getNumParams() + OpNum)
4702         return error("Insufficient operands to call");
4703 
4704       SmallVector<Value*, 16> Ops;
4705       SmallVector<Type *, 16> ArgsFullTys;
4706       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4707         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4708                                FTy->getParamType(i)));
4709         ArgsFullTys.push_back(FullFTy->getParamType(i));
4710         if (!Ops.back())
4711           return error("Invalid record");
4712       }
4713 
4714       if (!FTy->isVarArg()) {
4715         if (Record.size() != OpNum)
4716           return error("Invalid record");
4717       } else {
4718         // Read type/value pairs for varargs params.
4719         while (OpNum != Record.size()) {
4720           Value *Op;
4721           Type *FullTy;
4722           if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
4723             return error("Invalid record");
4724           Ops.push_back(Op);
4725           ArgsFullTys.push_back(FullTy);
4726         }
4727       }
4728 
4729       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
4730                              OperandBundles);
4731       FullTy = FullFTy->getReturnType();
4732       OperandBundles.clear();
4733       InstructionList.push_back(I);
4734       cast<InvokeInst>(I)->setCallingConv(
4735           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4736       cast<InvokeInst>(I)->setAttributes(PAL);
4737       propagateByValSRetTypes(cast<CallBase>(I), ArgsFullTys);
4738 
4739       break;
4740     }
4741     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4742       unsigned Idx = 0;
4743       Value *Val = nullptr;
4744       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4745         return error("Invalid record");
4746       I = ResumeInst::Create(Val);
4747       InstructionList.push_back(I);
4748       break;
4749     }
4750     case bitc::FUNC_CODE_INST_CALLBR: {
4751       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
4752       unsigned OpNum = 0;
4753       AttributeList PAL = getAttributes(Record[OpNum++]);
4754       unsigned CCInfo = Record[OpNum++];
4755 
4756       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
4757       unsigned NumIndirectDests = Record[OpNum++];
4758       SmallVector<BasicBlock *, 16> IndirectDests;
4759       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
4760         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
4761 
4762       FunctionType *FTy = nullptr;
4763       FunctionType *FullFTy = nullptr;
4764       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
4765         FullFTy =
4766             dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
4767         if (!FullFTy)
4768           return error("Explicit call type is not a function type");
4769         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4770       }
4771 
4772       Value *Callee;
4773       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
4774         return error("Invalid record");
4775 
4776       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4777       if (!OpTy)
4778         return error("Callee is not a pointer type");
4779       if (!FTy) {
4780         FullFTy =
4781             dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
4782         if (!FullFTy)
4783           return error("Callee is not of pointer to function type");
4784         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4785       } else if (getPointerElementFlatType(FullTy) != FTy)
4786         return error("Explicit call type does not match pointee type of "
4787                      "callee operand");
4788       if (Record.size() < FTy->getNumParams() + OpNum)
4789         return error("Insufficient operands to call");
4790 
4791       SmallVector<Value*, 16> Args;
4792       // Read the fixed params.
4793       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4794         if (FTy->getParamType(i)->isLabelTy())
4795           Args.push_back(getBasicBlock(Record[OpNum]));
4796         else
4797           Args.push_back(getValue(Record, OpNum, NextValueNo,
4798                                   FTy->getParamType(i)));
4799         if (!Args.back())
4800           return error("Invalid record");
4801       }
4802 
4803       // Read type/value pairs for varargs params.
4804       if (!FTy->isVarArg()) {
4805         if (OpNum != Record.size())
4806           return error("Invalid record");
4807       } else {
4808         while (OpNum != Record.size()) {
4809           Value *Op;
4810           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4811             return error("Invalid record");
4812           Args.push_back(Op);
4813         }
4814       }
4815 
4816       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
4817                              OperandBundles);
4818       FullTy = FullFTy->getReturnType();
4819       OperandBundles.clear();
4820       InstructionList.push_back(I);
4821       cast<CallBrInst>(I)->setCallingConv(
4822           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4823       cast<CallBrInst>(I)->setAttributes(PAL);
4824       break;
4825     }
4826     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4827       I = new UnreachableInst(Context);
4828       InstructionList.push_back(I);
4829       break;
4830     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4831       if (Record.empty())
4832         return error("Invalid record");
4833       // The first record specifies the type.
4834       FullTy = getFullyStructuredTypeByID(Record[0]);
4835       Type *Ty = flattenPointerTypes(FullTy);
4836       if (!Ty)
4837         return error("Invalid record");
4838 
4839       // Phi arguments are pairs of records of [value, basic block].
4840       // There is an optional final record for fast-math-flags if this phi has a
4841       // floating-point type.
4842       size_t NumArgs = (Record.size() - 1) / 2;
4843       PHINode *PN = PHINode::Create(Ty, NumArgs);
4844       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN))
4845         return error("Invalid record");
4846       InstructionList.push_back(PN);
4847 
4848       for (unsigned i = 0; i != NumArgs; i++) {
4849         Value *V;
4850         // With the new function encoding, it is possible that operands have
4851         // negative IDs (for forward references).  Use a signed VBR
4852         // representation to keep the encoding small.
4853         if (UseRelativeIDs)
4854           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty);
4855         else
4856           V = getValue(Record, i * 2 + 1, NextValueNo, Ty);
4857         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
4858         if (!V || !BB)
4859           return error("Invalid record");
4860         PN->addIncoming(V, BB);
4861       }
4862       I = PN;
4863 
4864       // If there are an even number of records, the final record must be FMF.
4865       if (Record.size() % 2 == 0) {
4866         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
4867         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
4868         if (FMF.any())
4869           I->setFastMathFlags(FMF);
4870       }
4871 
4872       break;
4873     }
4874 
4875     case bitc::FUNC_CODE_INST_LANDINGPAD:
4876     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4877       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4878       unsigned Idx = 0;
4879       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4880         if (Record.size() < 3)
4881           return error("Invalid record");
4882       } else {
4883         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4884         if (Record.size() < 4)
4885           return error("Invalid record");
4886       }
4887       FullTy = getFullyStructuredTypeByID(Record[Idx++]);
4888       Type *Ty = flattenPointerTypes(FullTy);
4889       if (!Ty)
4890         return error("Invalid record");
4891       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4892         Value *PersFn = nullptr;
4893         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4894           return error("Invalid record");
4895 
4896         if (!F->hasPersonalityFn())
4897           F->setPersonalityFn(cast<Constant>(PersFn));
4898         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4899           return error("Personality function mismatch");
4900       }
4901 
4902       bool IsCleanup = !!Record[Idx++];
4903       unsigned NumClauses = Record[Idx++];
4904       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4905       LP->setCleanup(IsCleanup);
4906       for (unsigned J = 0; J != NumClauses; ++J) {
4907         LandingPadInst::ClauseType CT =
4908           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4909         Value *Val;
4910 
4911         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4912           delete LP;
4913           return error("Invalid record");
4914         }
4915 
4916         assert((CT != LandingPadInst::Catch ||
4917                 !isa<ArrayType>(Val->getType())) &&
4918                "Catch clause has a invalid type!");
4919         assert((CT != LandingPadInst::Filter ||
4920                 isa<ArrayType>(Val->getType())) &&
4921                "Filter clause has invalid type!");
4922         LP->addClause(cast<Constant>(Val));
4923       }
4924 
4925       I = LP;
4926       InstructionList.push_back(I);
4927       break;
4928     }
4929 
4930     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4931       if (Record.size() != 4)
4932         return error("Invalid record");
4933       using APV = AllocaPackedValues;
4934       const uint64_t Rec = Record[3];
4935       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
4936       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
4937       FullTy = getFullyStructuredTypeByID(Record[0]);
4938       Type *Ty = flattenPointerTypes(FullTy);
4939       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
4940         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4941         if (!PTy)
4942           return error("Old-style alloca with a non-pointer type");
4943         std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
4944       }
4945       Type *OpTy = getTypeByID(Record[1]);
4946       Value *Size = getFnValueByID(Record[2], OpTy);
4947       MaybeAlign Align;
4948       if (Error Err =
4949               parseAlignmentValue(Bitfield::get<APV::Align>(Rec), Align)) {
4950         return Err;
4951       }
4952       if (!Ty || !Size)
4953         return error("Invalid record");
4954 
4955       // FIXME: Make this an optional field.
4956       const DataLayout &DL = TheModule->getDataLayout();
4957       unsigned AS = DL.getAllocaAddrSpace();
4958 
4959       SmallPtrSet<Type *, 4> Visited;
4960       if (!Align && !Ty->isSized(&Visited))
4961         return error("alloca of unsized type");
4962       if (!Align)
4963         Align = DL.getPrefTypeAlign(Ty);
4964 
4965       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
4966       AI->setUsedWithInAlloca(InAlloca);
4967       AI->setSwiftError(SwiftError);
4968       I = AI;
4969       FullTy = PointerType::get(FullTy, AS);
4970       InstructionList.push_back(I);
4971       break;
4972     }
4973     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4974       unsigned OpNum = 0;
4975       Value *Op;
4976       if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) ||
4977           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4978         return error("Invalid record");
4979 
4980       if (!isa<PointerType>(Op->getType()))
4981         return error("Load operand is not a pointer type");
4982 
4983       Type *Ty = nullptr;
4984       if (OpNum + 3 == Record.size()) {
4985         FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
4986         Ty = flattenPointerTypes(FullTy);
4987       } else
4988         std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
4989 
4990       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4991         return Err;
4992 
4993       MaybeAlign Align;
4994       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4995         return Err;
4996       SmallPtrSet<Type *, 4> Visited;
4997       if (!Align && !Ty->isSized(&Visited))
4998         return error("load of unsized type");
4999       if (!Align)
5000         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
5001       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
5002       InstructionList.push_back(I);
5003       break;
5004     }
5005     case bitc::FUNC_CODE_INST_LOADATOMIC: {
5006        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
5007       unsigned OpNum = 0;
5008       Value *Op;
5009       if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) ||
5010           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5011         return error("Invalid record");
5012 
5013       if (!isa<PointerType>(Op->getType()))
5014         return error("Load operand is not a pointer type");
5015 
5016       Type *Ty = nullptr;
5017       if (OpNum + 5 == Record.size()) {
5018         FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
5019         Ty = flattenPointerTypes(FullTy);
5020       } else
5021         std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
5022 
5023       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5024         return Err;
5025 
5026       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5027       if (Ordering == AtomicOrdering::NotAtomic ||
5028           Ordering == AtomicOrdering::Release ||
5029           Ordering == AtomicOrdering::AcquireRelease)
5030         return error("Invalid record");
5031       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5032         return error("Invalid record");
5033       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5034 
5035       MaybeAlign Align;
5036       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5037         return Err;
5038       if (!Align)
5039         return error("Alignment missing from atomic load");
5040       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
5041       InstructionList.push_back(I);
5042       break;
5043     }
5044     case bitc::FUNC_CODE_INST_STORE:
5045     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5046       unsigned OpNum = 0;
5047       Value *Val, *Ptr;
5048       Type *FullTy;
5049       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) ||
5050           (BitCode == bitc::FUNC_CODE_INST_STORE
5051                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5052                : popValue(Record, OpNum, NextValueNo,
5053                           getPointerElementFlatType(FullTy), Val)) ||
5054           OpNum + 2 != Record.size())
5055         return error("Invalid record");
5056 
5057       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5058         return Err;
5059       MaybeAlign Align;
5060       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5061         return Err;
5062       SmallPtrSet<Type *, 4> Visited;
5063       if (!Align && !Val->getType()->isSized(&Visited))
5064         return error("store of unsized type");
5065       if (!Align)
5066         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
5067       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
5068       InstructionList.push_back(I);
5069       break;
5070     }
5071     case bitc::FUNC_CODE_INST_STOREATOMIC:
5072     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5073       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
5074       unsigned OpNum = 0;
5075       Value *Val, *Ptr;
5076       Type *FullTy;
5077       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) ||
5078           !isa<PointerType>(Ptr->getType()) ||
5079           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5080                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5081                : popValue(Record, OpNum, NextValueNo,
5082                           getPointerElementFlatType(FullTy), Val)) ||
5083           OpNum + 4 != Record.size())
5084         return error("Invalid record");
5085 
5086       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5087         return Err;
5088       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5089       if (Ordering == AtomicOrdering::NotAtomic ||
5090           Ordering == AtomicOrdering::Acquire ||
5091           Ordering == AtomicOrdering::AcquireRelease)
5092         return error("Invalid record");
5093       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5094       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5095         return error("Invalid record");
5096 
5097       MaybeAlign Align;
5098       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5099         return Err;
5100       if (!Align)
5101         return error("Alignment missing from atomic store");
5102       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
5103       InstructionList.push_back(I);
5104       break;
5105     }
5106     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
5107       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
5108       // failure_ordering?, weak?]
5109       const size_t NumRecords = Record.size();
5110       unsigned OpNum = 0;
5111       Value *Ptr = nullptr;
5112       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy))
5113         return error("Invalid record");
5114 
5115       if (!isa<PointerType>(Ptr->getType()))
5116         return error("Cmpxchg operand is not a pointer type");
5117 
5118       Value *Cmp = nullptr;
5119       if (popValue(Record, OpNum, NextValueNo,
5120                    getPointerElementFlatType(FullTy), Cmp))
5121         return error("Invalid record");
5122 
5123       FullTy = cast<PointerType>(FullTy)->getElementType();
5124 
5125       Value *New = nullptr;
5126       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5127           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
5128         return error("Invalid record");
5129 
5130       const AtomicOrdering SuccessOrdering =
5131           getDecodedOrdering(Record[OpNum + 1]);
5132       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5133           SuccessOrdering == AtomicOrdering::Unordered)
5134         return error("Invalid record");
5135 
5136       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5137 
5138       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5139         return Err;
5140 
5141       const AtomicOrdering FailureOrdering =
5142           NumRecords < 7
5143               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
5144               : getDecodedOrdering(Record[OpNum + 3]);
5145 
5146       if (FailureOrdering == AtomicOrdering::NotAtomic ||
5147           FailureOrdering == AtomicOrdering::Unordered)
5148         return error("Invalid record");
5149 
5150       const Align Alignment(
5151           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5152 
5153       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
5154                                 FailureOrdering, SSID);
5155       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5156       FullTy = StructType::get(Context, {FullTy, Type::getInt1Ty(Context)});
5157 
5158       if (NumRecords < 8) {
5159         // Before weak cmpxchgs existed, the instruction simply returned the
5160         // value loaded from memory, so bitcode files from that era will be
5161         // expecting the first component of a modern cmpxchg.
5162         CurBB->getInstList().push_back(I);
5163         I = ExtractValueInst::Create(I, 0);
5164         FullTy = cast<StructType>(FullTy)->getElementType(0);
5165       } else {
5166         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
5167       }
5168 
5169       InstructionList.push_back(I);
5170       break;
5171     }
5172     case bitc::FUNC_CODE_INST_CMPXCHG: {
5173       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
5174       // failure_ordering, weak, align?]
5175       const size_t NumRecords = Record.size();
5176       unsigned OpNum = 0;
5177       Value *Ptr = nullptr;
5178       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy))
5179         return error("Invalid record");
5180 
5181       if (!isa<PointerType>(Ptr->getType()))
5182         return error("Cmpxchg operand is not a pointer type");
5183 
5184       Value *Cmp = nullptr;
5185       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, &FullTy))
5186         return error("Invalid record");
5187 
5188       Value *Val = nullptr;
5189       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), Val))
5190         return error("Invalid record");
5191 
5192       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
5193         return error("Invalid record");
5194 
5195       const bool IsVol = Record[OpNum];
5196 
5197       const AtomicOrdering SuccessOrdering =
5198           getDecodedOrdering(Record[OpNum + 1]);
5199       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
5200         return error("Invalid cmpxchg success ordering");
5201 
5202       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5203 
5204       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5205         return Err;
5206 
5207       const AtomicOrdering FailureOrdering =
5208           getDecodedOrdering(Record[OpNum + 3]);
5209       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
5210         return error("Invalid cmpxchg failure ordering");
5211 
5212       const bool IsWeak = Record[OpNum + 4];
5213 
5214       MaybeAlign Alignment;
5215 
5216       if (NumRecords == (OpNum + 6)) {
5217         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
5218           return Err;
5219       }
5220       if (!Alignment)
5221         Alignment =
5222             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5223 
5224       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
5225                                 FailureOrdering, SSID);
5226       FullTy = StructType::get(Context, {FullTy, Type::getInt1Ty(Context)});
5227       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
5228       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
5229 
5230       InstructionList.push_back(I);
5231       break;
5232     }
5233     case bitc::FUNC_CODE_INST_ATOMICRMW: {
5234       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid, align?]
5235       const size_t NumRecords = Record.size();
5236       unsigned OpNum = 0;
5237 
5238       Value *Ptr = nullptr;
5239       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr))
5240         return error("Invalid record");
5241 
5242       if (!isa<PointerType>(Ptr->getType()))
5243         return error("Invalid record");
5244 
5245       Value *Val = nullptr;
5246       if (popValue(Record, OpNum, NextValueNo, nullptr, Val))
5247         return error("Invalid record");
5248 
5249       if (!cast<PointerType>(Ptr->getType())
5250                ->isOpaqueOrPointeeTypeMatches(Val->getType()))
5251         return error("Invalid record");
5252 
5253       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
5254         return error("Invalid record");
5255 
5256       const AtomicRMWInst::BinOp Operation =
5257           getDecodedRMWOperation(Record[OpNum]);
5258       if (Operation < AtomicRMWInst::FIRST_BINOP ||
5259           Operation > AtomicRMWInst::LAST_BINOP)
5260         return error("Invalid record");
5261 
5262       const bool IsVol = Record[OpNum + 1];
5263 
5264       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5265       if (Ordering == AtomicOrdering::NotAtomic ||
5266           Ordering == AtomicOrdering::Unordered)
5267         return error("Invalid record");
5268 
5269       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5270 
5271       MaybeAlign Alignment;
5272 
5273       if (NumRecords == (OpNum + 5)) {
5274         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
5275           return Err;
5276       }
5277 
5278       if (!Alignment)
5279         Alignment =
5280             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
5281 
5282       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
5283       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
5284 
5285       InstructionList.push_back(I);
5286       break;
5287     }
5288     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
5289       if (2 != Record.size())
5290         return error("Invalid record");
5291       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5292       if (Ordering == AtomicOrdering::NotAtomic ||
5293           Ordering == AtomicOrdering::Unordered ||
5294           Ordering == AtomicOrdering::Monotonic)
5295         return error("Invalid record");
5296       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
5297       I = new FenceInst(Context, Ordering, SSID);
5298       InstructionList.push_back(I);
5299       break;
5300     }
5301     case bitc::FUNC_CODE_INST_CALL: {
5302       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5303       if (Record.size() < 3)
5304         return error("Invalid record");
5305 
5306       unsigned OpNum = 0;
5307       AttributeList PAL = getAttributes(Record[OpNum++]);
5308       unsigned CCInfo = Record[OpNum++];
5309 
5310       FastMathFlags FMF;
5311       if ((CCInfo >> bitc::CALL_FMF) & 1) {
5312         FMF = getDecodedFastMathFlags(Record[OpNum++]);
5313         if (!FMF.any())
5314           return error("Fast math flags indicator set for call with no FMF");
5315       }
5316 
5317       FunctionType *FTy = nullptr;
5318       FunctionType *FullFTy = nullptr;
5319       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5320         FullFTy =
5321             dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
5322         if (!FullFTy)
5323           return error("Explicit call type is not a function type");
5324         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
5325       }
5326 
5327       Value *Callee;
5328       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
5329         return error("Invalid record");
5330 
5331       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5332       if (!OpTy)
5333         return error("Callee is not a pointer type");
5334       if (!FTy) {
5335         FullFTy =
5336             dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
5337         if (!FullFTy)
5338           return error("Callee is not of pointer to function type");
5339         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
5340       } else if (getPointerElementFlatType(FullTy) != FTy)
5341         return error("Explicit call type does not match pointee type of "
5342                      "callee operand");
5343       if (Record.size() < FTy->getNumParams() + OpNum)
5344         return error("Insufficient operands to call");
5345 
5346       SmallVector<Value*, 16> Args;
5347       SmallVector<Type*, 16> ArgsFullTys;
5348       // Read the fixed params.
5349       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5350         if (FTy->getParamType(i)->isLabelTy())
5351           Args.push_back(getBasicBlock(Record[OpNum]));
5352         else
5353           Args.push_back(getValue(Record, OpNum, NextValueNo,
5354                                   FTy->getParamType(i)));
5355         ArgsFullTys.push_back(FullFTy->getParamType(i));
5356         if (!Args.back())
5357           return error("Invalid record");
5358       }
5359 
5360       // Read type/value pairs for varargs params.
5361       if (!FTy->isVarArg()) {
5362         if (OpNum != Record.size())
5363           return error("Invalid record");
5364       } else {
5365         while (OpNum != Record.size()) {
5366           Value *Op;
5367           Type *FullTy;
5368           if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
5369             return error("Invalid record");
5370           Args.push_back(Op);
5371           ArgsFullTys.push_back(FullTy);
5372         }
5373       }
5374 
5375       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5376       FullTy = FullFTy->getReturnType();
5377       OperandBundles.clear();
5378       InstructionList.push_back(I);
5379       cast<CallInst>(I)->setCallingConv(
5380           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5381       CallInst::TailCallKind TCK = CallInst::TCK_None;
5382       if (CCInfo & 1 << bitc::CALL_TAIL)
5383         TCK = CallInst::TCK_Tail;
5384       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5385         TCK = CallInst::TCK_MustTail;
5386       if (CCInfo & (1 << bitc::CALL_NOTAIL))
5387         TCK = CallInst::TCK_NoTail;
5388       cast<CallInst>(I)->setTailCallKind(TCK);
5389       cast<CallInst>(I)->setAttributes(PAL);
5390       propagateByValSRetTypes(cast<CallBase>(I), ArgsFullTys);
5391       if (FMF.any()) {
5392         if (!isa<FPMathOperator>(I))
5393           return error("Fast-math-flags specified for call without "
5394                        "floating-point scalar or vector return type");
5395         I->setFastMathFlags(FMF);
5396       }
5397       break;
5398     }
5399     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5400       if (Record.size() < 3)
5401         return error("Invalid record");
5402       Type *OpTy = getTypeByID(Record[0]);
5403       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5404       FullTy = getFullyStructuredTypeByID(Record[2]);
5405       Type *ResTy = flattenPointerTypes(FullTy);
5406       if (!OpTy || !Op || !ResTy)
5407         return error("Invalid record");
5408       I = new VAArgInst(Op, ResTy);
5409       InstructionList.push_back(I);
5410       break;
5411     }
5412 
5413     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5414       // A call or an invoke can be optionally prefixed with some variable
5415       // number of operand bundle blocks.  These blocks are read into
5416       // OperandBundles and consumed at the next call or invoke instruction.
5417 
5418       if (Record.empty() || Record[0] >= BundleTags.size())
5419         return error("Invalid record");
5420 
5421       std::vector<Value *> Inputs;
5422 
5423       unsigned OpNum = 1;
5424       while (OpNum != Record.size()) {
5425         Value *Op;
5426         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5427           return error("Invalid record");
5428         Inputs.push_back(Op);
5429       }
5430 
5431       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5432       continue;
5433     }
5434 
5435     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
5436       unsigned OpNum = 0;
5437       Value *Op = nullptr;
5438       if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
5439         return error("Invalid record");
5440       if (OpNum != Record.size())
5441         return error("Invalid record");
5442 
5443       I = new FreezeInst(Op);
5444       InstructionList.push_back(I);
5445       break;
5446     }
5447     }
5448 
5449     // Add instruction to end of current BB.  If there is no current BB, reject
5450     // this file.
5451     if (!CurBB) {
5452       I->deleteValue();
5453       return error("Invalid instruction with no BB");
5454     }
5455     if (!OperandBundles.empty()) {
5456       I->deleteValue();
5457       return error("Operand bundles found with no consumer");
5458     }
5459     CurBB->getInstList().push_back(I);
5460 
5461     // If this was a terminator instruction, move to the next block.
5462     if (I->isTerminator()) {
5463       ++CurBBNo;
5464       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5465     }
5466 
5467     // Non-void values get registered in the value table for future use.
5468     if (!I->getType()->isVoidTy()) {
5469       if (!FullTy) {
5470         FullTy = I->getType();
5471         assert(
5472             !FullTy->isPointerTy() && !isa<StructType>(FullTy) &&
5473             !isa<ArrayType>(FullTy) &&
5474             (!isa<VectorType>(FullTy) ||
5475              cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() ||
5476              cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) &&
5477             "Structured types must be assigned with corresponding non-opaque "
5478             "pointer type");
5479       }
5480 
5481       assert(I->getType() == flattenPointerTypes(FullTy) &&
5482              "Incorrect fully structured type provided for Instruction");
5483       ValueList.assignValue(I, NextValueNo++, FullTy);
5484     }
5485   }
5486 
5487 OutOfRecordLoop:
5488 
5489   if (!OperandBundles.empty())
5490     return error("Operand bundles found with no consumer");
5491 
5492   // Check the function list for unresolved values.
5493   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5494     if (!A->getParent()) {
5495       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5496       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5497         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5498           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5499           delete A;
5500         }
5501       }
5502       return error("Never resolved value found in function");
5503     }
5504   }
5505 
5506   // Unexpected unresolved metadata about to be dropped.
5507   if (MDLoader->hasFwdRefs())
5508     return error("Invalid function metadata: outgoing forward refs");
5509 
5510   // Trim the value list down to the size it was before we parsed this function.
5511   ValueList.shrinkTo(ModuleValueListSize);
5512   MDLoader->shrinkTo(ModuleMDLoaderSize);
5513   std::vector<BasicBlock*>().swap(FunctionBBs);
5514   return Error::success();
5515 }
5516 
5517 /// Find the function body in the bitcode stream
findFunctionInStream(Function * F,DenseMap<Function *,uint64_t>::iterator DeferredFunctionInfoIterator)5518 Error BitcodeReader::findFunctionInStream(
5519     Function *F,
5520     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5521   while (DeferredFunctionInfoIterator->second == 0) {
5522     // This is the fallback handling for the old format bitcode that
5523     // didn't contain the function index in the VST, or when we have
5524     // an anonymous function which would not have a VST entry.
5525     // Assert that we have one of those two cases.
5526     assert(VSTOffset == 0 || !F->hasName());
5527     // Parse the next body in the stream and set its position in the
5528     // DeferredFunctionInfo map.
5529     if (Error Err = rememberAndSkipFunctionBodies())
5530       return Err;
5531   }
5532   return Error::success();
5533 }
5534 
getDecodedSyncScopeID(unsigned Val)5535 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
5536   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
5537     return SyncScope::ID(Val);
5538   if (Val >= SSIDs.size())
5539     return SyncScope::System; // Map unknown synchronization scopes to system.
5540   return SSIDs[Val];
5541 }
5542 
5543 //===----------------------------------------------------------------------===//
5544 // GVMaterializer implementation
5545 //===----------------------------------------------------------------------===//
5546 
materialize(GlobalValue * GV)5547 Error BitcodeReader::materialize(GlobalValue *GV) {
5548   Function *F = dyn_cast<Function>(GV);
5549   // If it's not a function or is already material, ignore the request.
5550   if (!F || !F->isMaterializable())
5551     return Error::success();
5552 
5553   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5554   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5555   // If its position is recorded as 0, its body is somewhere in the stream
5556   // but we haven't seen it yet.
5557   if (DFII->second == 0)
5558     if (Error Err = findFunctionInStream(F, DFII))
5559       return Err;
5560 
5561   // Materialize metadata before parsing any function bodies.
5562   if (Error Err = materializeMetadata())
5563     return Err;
5564 
5565   // Move the bit stream to the saved position of the deferred function body.
5566   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
5567     return JumpFailed;
5568   if (Error Err = parseFunctionBody(F))
5569     return Err;
5570   F->setIsMaterializable(false);
5571 
5572   if (StripDebugInfo)
5573     stripDebugInfo(*F);
5574 
5575   // Upgrade any old intrinsic calls in the function.
5576   for (auto &I : UpgradedIntrinsics) {
5577     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5578          UI != UE;) {
5579       User *U = *UI;
5580       ++UI;
5581       if (CallInst *CI = dyn_cast<CallInst>(U))
5582         UpgradeIntrinsicCall(CI, I.second);
5583     }
5584   }
5585 
5586   // Update calls to the remangled intrinsics
5587   for (auto &I : RemangledIntrinsics)
5588     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5589          UI != UE;)
5590       // Don't expect any other users than call sites
5591       cast<CallBase>(*UI++)->setCalledFunction(I.second);
5592 
5593   // Finish fn->subprogram upgrade for materialized functions.
5594   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
5595     F->setSubprogram(SP);
5596 
5597   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
5598   if (!MDLoader->isStrippingTBAA()) {
5599     for (auto &I : instructions(F)) {
5600       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
5601       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
5602         continue;
5603       MDLoader->setStripTBAA(true);
5604       stripTBAA(F->getParent());
5605     }
5606   }
5607 
5608   for (auto &I : instructions(F)) {
5609     // "Upgrade" older incorrect branch weights by dropping them.
5610     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
5611       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
5612         MDString *MDS = cast<MDString>(MD->getOperand(0));
5613         StringRef ProfName = MDS->getString();
5614         // Check consistency of !prof branch_weights metadata.
5615         if (!ProfName.equals("branch_weights"))
5616           continue;
5617         unsigned ExpectedNumOperands = 0;
5618         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
5619           ExpectedNumOperands = BI->getNumSuccessors();
5620         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
5621           ExpectedNumOperands = SI->getNumSuccessors();
5622         else if (isa<CallInst>(&I))
5623           ExpectedNumOperands = 1;
5624         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
5625           ExpectedNumOperands = IBI->getNumDestinations();
5626         else if (isa<SelectInst>(&I))
5627           ExpectedNumOperands = 2;
5628         else
5629           continue; // ignore and continue.
5630 
5631         // If branch weight doesn't match, just strip branch weight.
5632         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
5633           I.setMetadata(LLVMContext::MD_prof, nullptr);
5634       }
5635     }
5636 
5637     // Remove incompatible attributes on function calls.
5638     if (auto *CI = dyn_cast<CallBase>(&I)) {
5639       CI->removeAttributes(AttributeList::ReturnIndex,
5640                            AttributeFuncs::typeIncompatible(
5641                                CI->getFunctionType()->getReturnType()));
5642 
5643       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
5644         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
5645                                         CI->getArgOperand(ArgNo)->getType()));
5646     }
5647   }
5648 
5649   // Look for functions that rely on old function attribute behavior.
5650   UpgradeFunctionAttributes(*F);
5651 
5652   // Bring in any functions that this function forward-referenced via
5653   // blockaddresses.
5654   return materializeForwardReferencedFunctions();
5655 }
5656 
materializeModule()5657 Error BitcodeReader::materializeModule() {
5658   if (Error Err = materializeMetadata())
5659     return Err;
5660 
5661   // Promise to materialize all forward references.
5662   WillMaterializeAllForwardRefs = true;
5663 
5664   // Iterate over the module, deserializing any functions that are still on
5665   // disk.
5666   for (Function &F : *TheModule) {
5667     if (Error Err = materialize(&F))
5668       return Err;
5669   }
5670   // At this point, if there are any function bodies, parse the rest of
5671   // the bits in the module past the last function block we have recorded
5672   // through either lazy scanning or the VST.
5673   if (LastFunctionBlockBit || NextUnreadBit)
5674     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
5675                                     ? LastFunctionBlockBit
5676                                     : NextUnreadBit))
5677       return Err;
5678 
5679   // Check that all block address forward references got resolved (as we
5680   // promised above).
5681   if (!BasicBlockFwdRefs.empty())
5682     return error("Never resolved function from blockaddress");
5683 
5684   // Upgrade any intrinsic calls that slipped through (should not happen!) and
5685   // delete the old functions to clean up. We can't do this unless the entire
5686   // module is materialized because there could always be another function body
5687   // with calls to the old function.
5688   for (auto &I : UpgradedIntrinsics) {
5689     for (auto *U : I.first->users()) {
5690       if (CallInst *CI = dyn_cast<CallInst>(U))
5691         UpgradeIntrinsicCall(CI, I.second);
5692     }
5693     if (!I.first->use_empty())
5694       I.first->replaceAllUsesWith(I.second);
5695     I.first->eraseFromParent();
5696   }
5697   UpgradedIntrinsics.clear();
5698   // Do the same for remangled intrinsics
5699   for (auto &I : RemangledIntrinsics) {
5700     I.first->replaceAllUsesWith(I.second);
5701     I.first->eraseFromParent();
5702   }
5703   RemangledIntrinsics.clear();
5704 
5705   UpgradeDebugInfo(*TheModule);
5706 
5707   UpgradeModuleFlags(*TheModule);
5708 
5709   UpgradeARCRuntime(*TheModule);
5710 
5711   return Error::success();
5712 }
5713 
getIdentifiedStructTypes() const5714 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5715   return IdentifiedStructTypes;
5716 }
5717 
ModuleSummaryIndexBitcodeReader(BitstreamCursor Cursor,StringRef Strtab,ModuleSummaryIndex & TheIndex,StringRef ModulePath,unsigned ModuleId)5718 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5719     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
5720     StringRef ModulePath, unsigned ModuleId)
5721     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
5722       ModulePath(ModulePath), ModuleId(ModuleId) {}
5723 
addThisModule()5724 void ModuleSummaryIndexBitcodeReader::addThisModule() {
5725   TheIndex.addModule(ModulePath, ModuleId);
5726 }
5727 
5728 ModuleSummaryIndex::ModuleInfo *
getThisModule()5729 ModuleSummaryIndexBitcodeReader::getThisModule() {
5730   return TheIndex.getModule(ModulePath);
5731 }
5732 
5733 std::pair<ValueInfo, GlobalValue::GUID>
getValueInfoFromValueId(unsigned ValueId)5734 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
5735   auto VGI = ValueIdToValueInfoMap[ValueId];
5736   assert(VGI.first);
5737   return VGI;
5738 }
5739 
setValueGUID(uint64_t ValueID,StringRef ValueName,GlobalValue::LinkageTypes Linkage,StringRef SourceFileName)5740 void ModuleSummaryIndexBitcodeReader::setValueGUID(
5741     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
5742     StringRef SourceFileName) {
5743   std::string GlobalId =
5744       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
5745   auto ValueGUID = GlobalValue::getGUID(GlobalId);
5746   auto OriginalNameID = ValueGUID;
5747   if (GlobalValue::isLocalLinkage(Linkage))
5748     OriginalNameID = GlobalValue::getGUID(ValueName);
5749   if (PrintSummaryGUIDs)
5750     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5751            << ValueName << "\n";
5752 
5753   // UseStrtab is false for legacy summary formats and value names are
5754   // created on stack. In that case we save the name in a string saver in
5755   // the index so that the value name can be recorded.
5756   ValueIdToValueInfoMap[ValueID] = std::make_pair(
5757       TheIndex.getOrInsertValueInfo(
5758           ValueGUID,
5759           UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
5760       OriginalNameID);
5761 }
5762 
5763 // Specialized value symbol table parser used when reading module index
5764 // blocks where we don't actually create global values. The parsed information
5765 // is saved in the bitcode reader for use when later parsing summaries.
parseValueSymbolTable(uint64_t Offset,DenseMap<unsigned,GlobalValue::LinkageTypes> & ValueIdToLinkageMap)5766 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5767     uint64_t Offset,
5768     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5769   // With a strtab the VST is not required to parse the summary.
5770   if (UseStrtab)
5771     return Error::success();
5772 
5773   assert(Offset > 0 && "Expected non-zero VST offset");
5774   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
5775   if (!MaybeCurrentBit)
5776     return MaybeCurrentBit.takeError();
5777   uint64_t CurrentBit = MaybeCurrentBit.get();
5778 
5779   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5780     return Err;
5781 
5782   SmallVector<uint64_t, 64> Record;
5783 
5784   // Read all the records for this value table.
5785   SmallString<128> ValueName;
5786 
5787   while (true) {
5788     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
5789     if (!MaybeEntry)
5790       return MaybeEntry.takeError();
5791     BitstreamEntry Entry = MaybeEntry.get();
5792 
5793     switch (Entry.Kind) {
5794     case BitstreamEntry::SubBlock: // Handled for us already.
5795     case BitstreamEntry::Error:
5796       return error("Malformed block");
5797     case BitstreamEntry::EndBlock:
5798       // Done parsing VST, jump back to wherever we came from.
5799       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
5800         return JumpFailed;
5801       return Error::success();
5802     case BitstreamEntry::Record:
5803       // The interesting case.
5804       break;
5805     }
5806 
5807     // Read a record.
5808     Record.clear();
5809     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
5810     if (!MaybeRecord)
5811       return MaybeRecord.takeError();
5812     switch (MaybeRecord.get()) {
5813     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5814       break;
5815     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5816       if (convertToString(Record, 1, ValueName))
5817         return error("Invalid record");
5818       unsigned ValueID = Record[0];
5819       assert(!SourceFileName.empty());
5820       auto VLI = ValueIdToLinkageMap.find(ValueID);
5821       assert(VLI != ValueIdToLinkageMap.end() &&
5822              "No linkage found for VST entry?");
5823       auto Linkage = VLI->second;
5824       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5825       ValueName.clear();
5826       break;
5827     }
5828     case bitc::VST_CODE_FNENTRY: {
5829       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5830       if (convertToString(Record, 2, ValueName))
5831         return error("Invalid record");
5832       unsigned ValueID = Record[0];
5833       assert(!SourceFileName.empty());
5834       auto VLI = ValueIdToLinkageMap.find(ValueID);
5835       assert(VLI != ValueIdToLinkageMap.end() &&
5836              "No linkage found for VST entry?");
5837       auto Linkage = VLI->second;
5838       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5839       ValueName.clear();
5840       break;
5841     }
5842     case bitc::VST_CODE_COMBINED_ENTRY: {
5843       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5844       unsigned ValueID = Record[0];
5845       GlobalValue::GUID RefGUID = Record[1];
5846       // The "original name", which is the second value of the pair will be
5847       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5848       ValueIdToValueInfoMap[ValueID] =
5849           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5850       break;
5851     }
5852     }
5853   }
5854 }
5855 
5856 // Parse just the blocks needed for building the index out of the module.
5857 // At the end of this routine the module Index is populated with a map
5858 // from global value id to GlobalValueSummary objects.
parseModule()5859 Error ModuleSummaryIndexBitcodeReader::parseModule() {
5860   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5861     return Err;
5862 
5863   SmallVector<uint64_t, 64> Record;
5864   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5865   unsigned ValueId = 0;
5866 
5867   // Read the index for this module.
5868   while (true) {
5869     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5870     if (!MaybeEntry)
5871       return MaybeEntry.takeError();
5872     llvm::BitstreamEntry Entry = MaybeEntry.get();
5873 
5874     switch (Entry.Kind) {
5875     case BitstreamEntry::Error:
5876       return error("Malformed block");
5877     case BitstreamEntry::EndBlock:
5878       return Error::success();
5879 
5880     case BitstreamEntry::SubBlock:
5881       switch (Entry.ID) {
5882       default: // Skip unknown content.
5883         if (Error Err = Stream.SkipBlock())
5884           return Err;
5885         break;
5886       case bitc::BLOCKINFO_BLOCK_ID:
5887         // Need to parse these to get abbrev ids (e.g. for VST)
5888         if (readBlockInfo())
5889           return error("Malformed block");
5890         break;
5891       case bitc::VALUE_SYMTAB_BLOCK_ID:
5892         // Should have been parsed earlier via VSTOffset, unless there
5893         // is no summary section.
5894         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5895                 !SeenGlobalValSummary) &&
5896                "Expected early VST parse via VSTOffset record");
5897         if (Error Err = Stream.SkipBlock())
5898           return Err;
5899         break;
5900       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5901       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
5902         // Add the module if it is a per-module index (has a source file name).
5903         if (!SourceFileName.empty())
5904           addThisModule();
5905         assert(!SeenValueSymbolTable &&
5906                "Already read VST when parsing summary block?");
5907         // We might not have a VST if there were no values in the
5908         // summary. An empty summary block generated when we are
5909         // performing ThinLTO compiles so we don't later invoke
5910         // the regular LTO process on them.
5911         if (VSTOffset > 0) {
5912           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5913             return Err;
5914           SeenValueSymbolTable = true;
5915         }
5916         SeenGlobalValSummary = true;
5917         if (Error Err = parseEntireSummary(Entry.ID))
5918           return Err;
5919         break;
5920       case bitc::MODULE_STRTAB_BLOCK_ID:
5921         if (Error Err = parseModuleStringTable())
5922           return Err;
5923         break;
5924       }
5925       continue;
5926 
5927     case BitstreamEntry::Record: {
5928         Record.clear();
5929         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5930         if (!MaybeBitCode)
5931           return MaybeBitCode.takeError();
5932         switch (MaybeBitCode.get()) {
5933         default:
5934           break; // Default behavior, ignore unknown content.
5935         case bitc::MODULE_CODE_VERSION: {
5936           if (Error Err = parseVersionRecord(Record).takeError())
5937             return Err;
5938           break;
5939         }
5940         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5941         case bitc::MODULE_CODE_SOURCE_FILENAME: {
5942           SmallString<128> ValueName;
5943           if (convertToString(Record, 0, ValueName))
5944             return error("Invalid record");
5945           SourceFileName = ValueName.c_str();
5946           break;
5947         }
5948         /// MODULE_CODE_HASH: [5*i32]
5949         case bitc::MODULE_CODE_HASH: {
5950           if (Record.size() != 5)
5951             return error("Invalid hash length " + Twine(Record.size()).str());
5952           auto &Hash = getThisModule()->second.second;
5953           int Pos = 0;
5954           for (auto &Val : Record) {
5955             assert(!(Val >> 32) && "Unexpected high bits set");
5956             Hash[Pos++] = Val;
5957           }
5958           break;
5959         }
5960         /// MODULE_CODE_VSTOFFSET: [offset]
5961         case bitc::MODULE_CODE_VSTOFFSET:
5962           if (Record.empty())
5963             return error("Invalid record");
5964           // Note that we subtract 1 here because the offset is relative to one
5965           // word before the start of the identification or module block, which
5966           // was historically always the start of the regular bitcode header.
5967           VSTOffset = Record[0] - 1;
5968           break;
5969         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
5970         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
5971         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
5972         // v2: [strtab offset, strtab size, v1]
5973         case bitc::MODULE_CODE_GLOBALVAR:
5974         case bitc::MODULE_CODE_FUNCTION:
5975         case bitc::MODULE_CODE_ALIAS: {
5976           StringRef Name;
5977           ArrayRef<uint64_t> GVRecord;
5978           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5979           if (GVRecord.size() <= 3)
5980             return error("Invalid record");
5981           uint64_t RawLinkage = GVRecord[3];
5982           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5983           if (!UseStrtab) {
5984             ValueIdToLinkageMap[ValueId++] = Linkage;
5985             break;
5986           }
5987 
5988           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
5989           break;
5990         }
5991         }
5992       }
5993       continue;
5994     }
5995   }
5996 }
5997 
5998 std::vector<ValueInfo>
makeRefList(ArrayRef<uint64_t> Record)5999 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
6000   std::vector<ValueInfo> Ret;
6001   Ret.reserve(Record.size());
6002   for (uint64_t RefValueId : Record)
6003     Ret.push_back(getValueInfoFromValueId(RefValueId).first);
6004   return Ret;
6005 }
6006 
6007 std::vector<FunctionSummary::EdgeTy>
makeCallList(ArrayRef<uint64_t> Record,bool IsOldProfileFormat,bool HasProfile,bool HasRelBF)6008 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
6009                                               bool IsOldProfileFormat,
6010                                               bool HasProfile, bool HasRelBF) {
6011   std::vector<FunctionSummary::EdgeTy> Ret;
6012   Ret.reserve(Record.size());
6013   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
6014     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
6015     uint64_t RelBF = 0;
6016     ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6017     if (IsOldProfileFormat) {
6018       I += 1; // Skip old callsitecount field
6019       if (HasProfile)
6020         I += 1; // Skip old profilecount field
6021     } else if (HasProfile)
6022       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
6023     else if (HasRelBF)
6024       RelBF = Record[++I];
6025     Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
6026   }
6027   return Ret;
6028 }
6029 
6030 static void
parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record,size_t & Slot,WholeProgramDevirtResolution & Wpd)6031 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
6032                                        WholeProgramDevirtResolution &Wpd) {
6033   uint64_t ArgNum = Record[Slot++];
6034   WholeProgramDevirtResolution::ByArg &B =
6035       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
6036   Slot += ArgNum;
6037 
6038   B.TheKind =
6039       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
6040   B.Info = Record[Slot++];
6041   B.Byte = Record[Slot++];
6042   B.Bit = Record[Slot++];
6043 }
6044 
parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,StringRef Strtab,size_t & Slot,TypeIdSummary & TypeId)6045 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
6046                                               StringRef Strtab, size_t &Slot,
6047                                               TypeIdSummary &TypeId) {
6048   uint64_t Id = Record[Slot++];
6049   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
6050 
6051   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
6052   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
6053                         static_cast<size_t>(Record[Slot + 1])};
6054   Slot += 2;
6055 
6056   uint64_t ResByArgNum = Record[Slot++];
6057   for (uint64_t I = 0; I != ResByArgNum; ++I)
6058     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
6059 }
6060 
parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,StringRef Strtab,ModuleSummaryIndex & TheIndex)6061 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
6062                                      StringRef Strtab,
6063                                      ModuleSummaryIndex &TheIndex) {
6064   size_t Slot = 0;
6065   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
6066       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
6067   Slot += 2;
6068 
6069   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
6070   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
6071   TypeId.TTRes.AlignLog2 = Record[Slot++];
6072   TypeId.TTRes.SizeM1 = Record[Slot++];
6073   TypeId.TTRes.BitMask = Record[Slot++];
6074   TypeId.TTRes.InlineBits = Record[Slot++];
6075 
6076   while (Slot < Record.size())
6077     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
6078 }
6079 
6080 std::vector<FunctionSummary::ParamAccess>
parseParamAccesses(ArrayRef<uint64_t> Record)6081 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
6082   auto ReadRange = [&]() {
6083     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
6084                 BitcodeReader::decodeSignRotatedValue(Record.front()));
6085     Record = Record.drop_front();
6086     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
6087                 BitcodeReader::decodeSignRotatedValue(Record.front()));
6088     Record = Record.drop_front();
6089     ConstantRange Range{Lower, Upper};
6090     assert(!Range.isFullSet());
6091     assert(!Range.isUpperSignWrapped());
6092     return Range;
6093   };
6094 
6095   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6096   while (!Record.empty()) {
6097     PendingParamAccesses.emplace_back();
6098     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
6099     ParamAccess.ParamNo = Record.front();
6100     Record = Record.drop_front();
6101     ParamAccess.Use = ReadRange();
6102     ParamAccess.Calls.resize(Record.front());
6103     Record = Record.drop_front();
6104     for (auto &Call : ParamAccess.Calls) {
6105       Call.ParamNo = Record.front();
6106       Record = Record.drop_front();
6107       Call.Callee = getValueInfoFromValueId(Record.front()).first;
6108       Record = Record.drop_front();
6109       Call.Offsets = ReadRange();
6110     }
6111   }
6112   return PendingParamAccesses;
6113 }
6114 
parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,size_t & Slot,TypeIdCompatibleVtableInfo & TypeId)6115 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
6116     ArrayRef<uint64_t> Record, size_t &Slot,
6117     TypeIdCompatibleVtableInfo &TypeId) {
6118   uint64_t Offset = Record[Slot++];
6119   ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;
6120   TypeId.push_back({Offset, Callee});
6121 }
6122 
parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record)6123 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
6124     ArrayRef<uint64_t> Record) {
6125   size_t Slot = 0;
6126   TypeIdCompatibleVtableInfo &TypeId =
6127       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
6128           {Strtab.data() + Record[Slot],
6129            static_cast<size_t>(Record[Slot + 1])});
6130   Slot += 2;
6131 
6132   while (Slot < Record.size())
6133     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
6134 }
6135 
setSpecialRefs(std::vector<ValueInfo> & Refs,unsigned ROCnt,unsigned WOCnt)6136 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
6137                            unsigned WOCnt) {
6138   // Readonly and writeonly refs are in the end of the refs list.
6139   assert(ROCnt + WOCnt <= Refs.size());
6140   unsigned FirstWORef = Refs.size() - WOCnt;
6141   unsigned RefNo = FirstWORef - ROCnt;
6142   for (; RefNo < FirstWORef; ++RefNo)
6143     Refs[RefNo].setReadOnly();
6144   for (; RefNo < Refs.size(); ++RefNo)
6145     Refs[RefNo].setWriteOnly();
6146 }
6147 
6148 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
6149 // objects in the index.
parseEntireSummary(unsigned ID)6150 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
6151   if (Error Err = Stream.EnterSubBlock(ID))
6152     return Err;
6153   SmallVector<uint64_t, 64> Record;
6154 
6155   // Parse version
6156   {
6157     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6158     if (!MaybeEntry)
6159       return MaybeEntry.takeError();
6160     BitstreamEntry Entry = MaybeEntry.get();
6161 
6162     if (Entry.Kind != BitstreamEntry::Record)
6163       return error("Invalid Summary Block: record for version expected");
6164     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6165     if (!MaybeRecord)
6166       return MaybeRecord.takeError();
6167     if (MaybeRecord.get() != bitc::FS_VERSION)
6168       return error("Invalid Summary Block: version expected");
6169   }
6170   const uint64_t Version = Record[0];
6171   const bool IsOldProfileFormat = Version == 1;
6172   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
6173     return error("Invalid summary version " + Twine(Version) +
6174                  ". Version should be in the range [1-" +
6175                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
6176                  "].");
6177   Record.clear();
6178 
6179   // Keep around the last seen summary to be used when we see an optional
6180   // "OriginalName" attachement.
6181   GlobalValueSummary *LastSeenSummary = nullptr;
6182   GlobalValue::GUID LastSeenGUID = 0;
6183 
6184   // We can expect to see any number of type ID information records before
6185   // each function summary records; these variables store the information
6186   // collected so far so that it can be used to create the summary object.
6187   std::vector<GlobalValue::GUID> PendingTypeTests;
6188   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
6189       PendingTypeCheckedLoadVCalls;
6190   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
6191       PendingTypeCheckedLoadConstVCalls;
6192   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6193 
6194   while (true) {
6195     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6196     if (!MaybeEntry)
6197       return MaybeEntry.takeError();
6198     BitstreamEntry Entry = MaybeEntry.get();
6199 
6200     switch (Entry.Kind) {
6201     case BitstreamEntry::SubBlock: // Handled for us already.
6202     case BitstreamEntry::Error:
6203       return error("Malformed block");
6204     case BitstreamEntry::EndBlock:
6205       return Error::success();
6206     case BitstreamEntry::Record:
6207       // The interesting case.
6208       break;
6209     }
6210 
6211     // Read a record. The record format depends on whether this
6212     // is a per-module index or a combined index file. In the per-module
6213     // case the records contain the associated value's ID for correlation
6214     // with VST entries. In the combined index the correlation is done
6215     // via the bitcode offset of the summary records (which were saved
6216     // in the combined index VST entries). The records also contain
6217     // information used for ThinLTO renaming and importing.
6218     Record.clear();
6219     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6220     if (!MaybeBitCode)
6221       return MaybeBitCode.takeError();
6222     switch (unsigned BitCode = MaybeBitCode.get()) {
6223     default: // Default behavior: ignore.
6224       break;
6225     case bitc::FS_FLAGS: {  // [flags]
6226       TheIndex.setFlags(Record[0]);
6227       break;
6228     }
6229     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
6230       uint64_t ValueID = Record[0];
6231       GlobalValue::GUID RefGUID = Record[1];
6232       ValueIdToValueInfoMap[ValueID] =
6233           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
6234       break;
6235     }
6236     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
6237     //                numrefs x valueid, n x (valueid)]
6238     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
6239     //                        numrefs x valueid,
6240     //                        n x (valueid, hotness)]
6241     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
6242     //                      numrefs x valueid,
6243     //                      n x (valueid, relblockfreq)]
6244     case bitc::FS_PERMODULE:
6245     case bitc::FS_PERMODULE_RELBF:
6246     case bitc::FS_PERMODULE_PROFILE: {
6247       unsigned ValueID = Record[0];
6248       uint64_t RawFlags = Record[1];
6249       unsigned InstCount = Record[2];
6250       uint64_t RawFunFlags = 0;
6251       unsigned NumRefs = Record[3];
6252       unsigned NumRORefs = 0, NumWORefs = 0;
6253       int RefListStartIndex = 4;
6254       if (Version >= 4) {
6255         RawFunFlags = Record[3];
6256         NumRefs = Record[4];
6257         RefListStartIndex = 5;
6258         if (Version >= 5) {
6259           NumRORefs = Record[5];
6260           RefListStartIndex = 6;
6261           if (Version >= 7) {
6262             NumWORefs = Record[6];
6263             RefListStartIndex = 7;
6264           }
6265         }
6266       }
6267 
6268       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6269       // The module path string ref set in the summary must be owned by the
6270       // index's module string table. Since we don't have a module path
6271       // string table section in the per-module index, we create a single
6272       // module path string table entry with an empty (0) ID to take
6273       // ownership.
6274       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6275       assert(Record.size() >= RefListStartIndex + NumRefs &&
6276              "Record size inconsistent with number of references");
6277       std::vector<ValueInfo> Refs = makeRefList(
6278           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6279       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6280       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
6281       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
6282           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6283           IsOldProfileFormat, HasProfile, HasRelBF);
6284       setSpecialRefs(Refs, NumRORefs, NumWORefs);
6285       auto FS = std::make_unique<FunctionSummary>(
6286           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
6287           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
6288           std::move(PendingTypeTestAssumeVCalls),
6289           std::move(PendingTypeCheckedLoadVCalls),
6290           std::move(PendingTypeTestAssumeConstVCalls),
6291           std::move(PendingTypeCheckedLoadConstVCalls),
6292           std::move(PendingParamAccesses));
6293       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
6294       FS->setModulePath(getThisModule()->first());
6295       FS->setOriginalName(VIAndOriginalGUID.second);
6296       TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
6297       break;
6298     }
6299     // FS_ALIAS: [valueid, flags, valueid]
6300     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6301     // they expect all aliasee summaries to be available.
6302     case bitc::FS_ALIAS: {
6303       unsigned ValueID = Record[0];
6304       uint64_t RawFlags = Record[1];
6305       unsigned AliaseeID = Record[2];
6306       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6307       auto AS = std::make_unique<AliasSummary>(Flags);
6308       // The module path string ref set in the summary must be owned by the
6309       // index's module string table. Since we don't have a module path
6310       // string table section in the per-module index, we create a single
6311       // module path string table entry with an empty (0) ID to take
6312       // ownership.
6313       AS->setModulePath(getThisModule()->first());
6314 
6315       auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
6316       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
6317       if (!AliaseeInModule)
6318         return error("Alias expects aliasee summary to be parsed");
6319       AS->setAliasee(AliaseeVI, AliaseeInModule);
6320 
6321       auto GUID = getValueInfoFromValueId(ValueID);
6322       AS->setOriginalName(GUID.second);
6323       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
6324       break;
6325     }
6326     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
6327     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6328       unsigned ValueID = Record[0];
6329       uint64_t RawFlags = Record[1];
6330       unsigned RefArrayStart = 2;
6331       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6332                                       /* WriteOnly */ false,
6333                                       /* Constant */ false,
6334                                       GlobalObject::VCallVisibilityPublic);
6335       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6336       if (Version >= 5) {
6337         GVF = getDecodedGVarFlags(Record[2]);
6338         RefArrayStart = 3;
6339       }
6340       std::vector<ValueInfo> Refs =
6341           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6342       auto FS =
6343           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6344       FS->setModulePath(getThisModule()->first());
6345       auto GUID = getValueInfoFromValueId(ValueID);
6346       FS->setOriginalName(GUID.second);
6347       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
6348       break;
6349     }
6350     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
6351     //                        numrefs, numrefs x valueid,
6352     //                        n x (valueid, offset)]
6353     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
6354       unsigned ValueID = Record[0];
6355       uint64_t RawFlags = Record[1];
6356       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
6357       unsigned NumRefs = Record[3];
6358       unsigned RefListStartIndex = 4;
6359       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
6360       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6361       std::vector<ValueInfo> Refs = makeRefList(
6362           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6363       VTableFuncList VTableFuncs;
6364       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
6365         ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6366         uint64_t Offset = Record[++I];
6367         VTableFuncs.push_back({Callee, Offset});
6368       }
6369       auto VS =
6370           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6371       VS->setModulePath(getThisModule()->first());
6372       VS->setVTableFuncs(VTableFuncs);
6373       auto GUID = getValueInfoFromValueId(ValueID);
6374       VS->setOriginalName(GUID.second);
6375       TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));
6376       break;
6377     }
6378     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
6379     //               numrefs x valueid, n x (valueid)]
6380     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
6381     //                       numrefs x valueid, n x (valueid, hotness)]
6382     case bitc::FS_COMBINED:
6383     case bitc::FS_COMBINED_PROFILE: {
6384       unsigned ValueID = Record[0];
6385       uint64_t ModuleId = Record[1];
6386       uint64_t RawFlags = Record[2];
6387       unsigned InstCount = Record[3];
6388       uint64_t RawFunFlags = 0;
6389       uint64_t EntryCount = 0;
6390       unsigned NumRefs = Record[4];
6391       unsigned NumRORefs = 0, NumWORefs = 0;
6392       int RefListStartIndex = 5;
6393 
6394       if (Version >= 4) {
6395         RawFunFlags = Record[4];
6396         RefListStartIndex = 6;
6397         size_t NumRefsIndex = 5;
6398         if (Version >= 5) {
6399           unsigned NumRORefsOffset = 1;
6400           RefListStartIndex = 7;
6401           if (Version >= 6) {
6402             NumRefsIndex = 6;
6403             EntryCount = Record[5];
6404             RefListStartIndex = 8;
6405             if (Version >= 7) {
6406               RefListStartIndex = 9;
6407               NumWORefs = Record[8];
6408               NumRORefsOffset = 2;
6409             }
6410           }
6411           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
6412         }
6413         NumRefs = Record[NumRefsIndex];
6414       }
6415 
6416       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6417       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6418       assert(Record.size() >= RefListStartIndex + NumRefs &&
6419              "Record size inconsistent with number of references");
6420       std::vector<ValueInfo> Refs = makeRefList(
6421           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6422       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6423       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
6424           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6425           IsOldProfileFormat, HasProfile, false);
6426       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6427       setSpecialRefs(Refs, NumRORefs, NumWORefs);
6428       auto FS = std::make_unique<FunctionSummary>(
6429           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
6430           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
6431           std::move(PendingTypeTestAssumeVCalls),
6432           std::move(PendingTypeCheckedLoadVCalls),
6433           std::move(PendingTypeTestAssumeConstVCalls),
6434           std::move(PendingTypeCheckedLoadConstVCalls),
6435           std::move(PendingParamAccesses));
6436       LastSeenSummary = FS.get();
6437       LastSeenGUID = VI.getGUID();
6438       FS->setModulePath(ModuleIdMap[ModuleId]);
6439       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6440       break;
6441     }
6442     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6443     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6444     // they expect all aliasee summaries to be available.
6445     case bitc::FS_COMBINED_ALIAS: {
6446       unsigned ValueID = Record[0];
6447       uint64_t ModuleId = Record[1];
6448       uint64_t RawFlags = Record[2];
6449       unsigned AliaseeValueId = Record[3];
6450       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6451       auto AS = std::make_unique<AliasSummary>(Flags);
6452       LastSeenSummary = AS.get();
6453       AS->setModulePath(ModuleIdMap[ModuleId]);
6454 
6455       auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
6456       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
6457       AS->setAliasee(AliaseeVI, AliaseeInModule);
6458 
6459       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6460       LastSeenGUID = VI.getGUID();
6461       TheIndex.addGlobalValueSummary(VI, std::move(AS));
6462       break;
6463     }
6464     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6465     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6466       unsigned ValueID = Record[0];
6467       uint64_t ModuleId = Record[1];
6468       uint64_t RawFlags = Record[2];
6469       unsigned RefArrayStart = 3;
6470       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6471                                       /* WriteOnly */ false,
6472                                       /* Constant */ false,
6473                                       GlobalObject::VCallVisibilityPublic);
6474       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6475       if (Version >= 5) {
6476         GVF = getDecodedGVarFlags(Record[3]);
6477         RefArrayStart = 4;
6478       }
6479       std::vector<ValueInfo> Refs =
6480           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6481       auto FS =
6482           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6483       LastSeenSummary = FS.get();
6484       FS->setModulePath(ModuleIdMap[ModuleId]);
6485       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6486       LastSeenGUID = VI.getGUID();
6487       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6488       break;
6489     }
6490     // FS_COMBINED_ORIGINAL_NAME: [original_name]
6491     case bitc::FS_COMBINED_ORIGINAL_NAME: {
6492       uint64_t OriginalName = Record[0];
6493       if (!LastSeenSummary)
6494         return error("Name attachment that does not follow a combined record");
6495       LastSeenSummary->setOriginalName(OriginalName);
6496       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
6497       // Reset the LastSeenSummary
6498       LastSeenSummary = nullptr;
6499       LastSeenGUID = 0;
6500       break;
6501     }
6502     case bitc::FS_TYPE_TESTS:
6503       assert(PendingTypeTests.empty());
6504       llvm::append_range(PendingTypeTests, Record);
6505       break;
6506 
6507     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
6508       assert(PendingTypeTestAssumeVCalls.empty());
6509       for (unsigned I = 0; I != Record.size(); I += 2)
6510         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
6511       break;
6512 
6513     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
6514       assert(PendingTypeCheckedLoadVCalls.empty());
6515       for (unsigned I = 0; I != Record.size(); I += 2)
6516         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
6517       break;
6518 
6519     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
6520       PendingTypeTestAssumeConstVCalls.push_back(
6521           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6522       break;
6523 
6524     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
6525       PendingTypeCheckedLoadConstVCalls.push_back(
6526           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6527       break;
6528 
6529     case bitc::FS_CFI_FUNCTION_DEFS: {
6530       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
6531       for (unsigned I = 0; I != Record.size(); I += 2)
6532         CfiFunctionDefs.insert(
6533             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6534       break;
6535     }
6536 
6537     case bitc::FS_CFI_FUNCTION_DECLS: {
6538       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
6539       for (unsigned I = 0; I != Record.size(); I += 2)
6540         CfiFunctionDecls.insert(
6541             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6542       break;
6543     }
6544 
6545     case bitc::FS_TYPE_ID:
6546       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
6547       break;
6548 
6549     case bitc::FS_TYPE_ID_METADATA:
6550       parseTypeIdCompatibleVtableSummaryRecord(Record);
6551       break;
6552 
6553     case bitc::FS_BLOCK_COUNT:
6554       TheIndex.addBlockCount(Record[0]);
6555       break;
6556 
6557     case bitc::FS_PARAM_ACCESS: {
6558       PendingParamAccesses = parseParamAccesses(Record);
6559       break;
6560     }
6561     }
6562   }
6563   llvm_unreachable("Exit infinite loop");
6564 }
6565 
6566 // Parse the  module string table block into the Index.
6567 // This populates the ModulePathStringTable map in the index.
parseModuleStringTable()6568 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6569   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6570     return Err;
6571 
6572   SmallVector<uint64_t, 64> Record;
6573 
6574   SmallString<128> ModulePath;
6575   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
6576 
6577   while (true) {
6578     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6579     if (!MaybeEntry)
6580       return MaybeEntry.takeError();
6581     BitstreamEntry Entry = MaybeEntry.get();
6582 
6583     switch (Entry.Kind) {
6584     case BitstreamEntry::SubBlock: // Handled for us already.
6585     case BitstreamEntry::Error:
6586       return error("Malformed block");
6587     case BitstreamEntry::EndBlock:
6588       return Error::success();
6589     case BitstreamEntry::Record:
6590       // The interesting case.
6591       break;
6592     }
6593 
6594     Record.clear();
6595     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6596     if (!MaybeRecord)
6597       return MaybeRecord.takeError();
6598     switch (MaybeRecord.get()) {
6599     default: // Default behavior: ignore.
6600       break;
6601     case bitc::MST_CODE_ENTRY: {
6602       // MST_ENTRY: [modid, namechar x N]
6603       uint64_t ModuleId = Record[0];
6604 
6605       if (convertToString(Record, 1, ModulePath))
6606         return error("Invalid record");
6607 
6608       LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
6609       ModuleIdMap[ModuleId] = LastSeenModule->first();
6610 
6611       ModulePath.clear();
6612       break;
6613     }
6614     /// MST_CODE_HASH: [5*i32]
6615     case bitc::MST_CODE_HASH: {
6616       if (Record.size() != 5)
6617         return error("Invalid hash length " + Twine(Record.size()).str());
6618       if (!LastSeenModule)
6619         return error("Invalid hash that does not follow a module path");
6620       int Pos = 0;
6621       for (auto &Val : Record) {
6622         assert(!(Val >> 32) && "Unexpected high bits set");
6623         LastSeenModule->second.second[Pos++] = Val;
6624       }
6625       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
6626       LastSeenModule = nullptr;
6627       break;
6628     }
6629     }
6630   }
6631   llvm_unreachable("Exit infinite loop");
6632 }
6633 
6634 namespace {
6635 
6636 // FIXME: This class is only here to support the transition to llvm::Error. It
6637 // will be removed once this transition is complete. Clients should prefer to
6638 // deal with the Error value directly, rather than converting to error_code.
6639 class BitcodeErrorCategoryType : public std::error_category {
name() const6640   const char *name() const noexcept override {
6641     return "llvm.bitcode";
6642   }
6643 
message(int IE) const6644   std::string message(int IE) const override {
6645     BitcodeError E = static_cast<BitcodeError>(IE);
6646     switch (E) {
6647     case BitcodeError::CorruptedBitcode:
6648       return "Corrupted bitcode";
6649     }
6650     llvm_unreachable("Unknown error type!");
6651   }
6652 };
6653 
6654 } // end anonymous namespace
6655 
6656 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6657 
BitcodeErrorCategory()6658 const std::error_category &llvm::BitcodeErrorCategory() {
6659   return *ErrorCategory;
6660 }
6661 
readBlobInRecord(BitstreamCursor & Stream,unsigned Block,unsigned RecordID)6662 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
6663                                             unsigned Block, unsigned RecordID) {
6664   if (Error Err = Stream.EnterSubBlock(Block))
6665     return std::move(Err);
6666 
6667   StringRef Strtab;
6668   while (true) {
6669     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6670     if (!MaybeEntry)
6671       return MaybeEntry.takeError();
6672     llvm::BitstreamEntry Entry = MaybeEntry.get();
6673 
6674     switch (Entry.Kind) {
6675     case BitstreamEntry::EndBlock:
6676       return Strtab;
6677 
6678     case BitstreamEntry::Error:
6679       return error("Malformed block");
6680 
6681     case BitstreamEntry::SubBlock:
6682       if (Error Err = Stream.SkipBlock())
6683         return std::move(Err);
6684       break;
6685 
6686     case BitstreamEntry::Record:
6687       StringRef Blob;
6688       SmallVector<uint64_t, 1> Record;
6689       Expected<unsigned> MaybeRecord =
6690           Stream.readRecord(Entry.ID, Record, &Blob);
6691       if (!MaybeRecord)
6692         return MaybeRecord.takeError();
6693       if (MaybeRecord.get() == RecordID)
6694         Strtab = Blob;
6695       break;
6696     }
6697   }
6698 }
6699 
6700 //===----------------------------------------------------------------------===//
6701 // External interface
6702 //===----------------------------------------------------------------------===//
6703 
6704 Expected<std::vector<BitcodeModule>>
getBitcodeModuleList(MemoryBufferRef Buffer)6705 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
6706   auto FOrErr = getBitcodeFileContents(Buffer);
6707   if (!FOrErr)
6708     return FOrErr.takeError();
6709   return std::move(FOrErr->Mods);
6710 }
6711 
6712 Expected<BitcodeFileContents>
getBitcodeFileContents(MemoryBufferRef Buffer)6713 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
6714   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6715   if (!StreamOrErr)
6716     return StreamOrErr.takeError();
6717   BitstreamCursor &Stream = *StreamOrErr;
6718 
6719   BitcodeFileContents F;
6720   while (true) {
6721     uint64_t BCBegin = Stream.getCurrentByteNo();
6722 
6723     // We may be consuming bitcode from a client that leaves garbage at the end
6724     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
6725     // the end that there cannot possibly be another module, stop looking.
6726     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
6727       return F;
6728 
6729     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6730     if (!MaybeEntry)
6731       return MaybeEntry.takeError();
6732     llvm::BitstreamEntry Entry = MaybeEntry.get();
6733 
6734     switch (Entry.Kind) {
6735     case BitstreamEntry::EndBlock:
6736     case BitstreamEntry::Error:
6737       return error("Malformed block");
6738 
6739     case BitstreamEntry::SubBlock: {
6740       uint64_t IdentificationBit = -1ull;
6741       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
6742         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6743         if (Error Err = Stream.SkipBlock())
6744           return std::move(Err);
6745 
6746         {
6747           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6748           if (!MaybeEntry)
6749             return MaybeEntry.takeError();
6750           Entry = MaybeEntry.get();
6751         }
6752 
6753         if (Entry.Kind != BitstreamEntry::SubBlock ||
6754             Entry.ID != bitc::MODULE_BLOCK_ID)
6755           return error("Malformed block");
6756       }
6757 
6758       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
6759         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6760         if (Error Err = Stream.SkipBlock())
6761           return std::move(Err);
6762 
6763         F.Mods.push_back({Stream.getBitcodeBytes().slice(
6764                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
6765                           Buffer.getBufferIdentifier(), IdentificationBit,
6766                           ModuleBit});
6767         continue;
6768       }
6769 
6770       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
6771         Expected<StringRef> Strtab =
6772             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
6773         if (!Strtab)
6774           return Strtab.takeError();
6775         // This string table is used by every preceding bitcode module that does
6776         // not have its own string table. A bitcode file may have multiple
6777         // string tables if it was created by binary concatenation, for example
6778         // with "llvm-cat -b".
6779         for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
6780           if (!I->Strtab.empty())
6781             break;
6782           I->Strtab = *Strtab;
6783         }
6784         // Similarly, the string table is used by every preceding symbol table;
6785         // normally there will be just one unless the bitcode file was created
6786         // by binary concatenation.
6787         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
6788           F.StrtabForSymtab = *Strtab;
6789         continue;
6790       }
6791 
6792       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
6793         Expected<StringRef> SymtabOrErr =
6794             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
6795         if (!SymtabOrErr)
6796           return SymtabOrErr.takeError();
6797 
6798         // We can expect the bitcode file to have multiple symbol tables if it
6799         // was created by binary concatenation. In that case we silently
6800         // ignore any subsequent symbol tables, which is fine because this is a
6801         // low level function. The client is expected to notice that the number
6802         // of modules in the symbol table does not match the number of modules
6803         // in the input file and regenerate the symbol table.
6804         if (F.Symtab.empty())
6805           F.Symtab = *SymtabOrErr;
6806         continue;
6807       }
6808 
6809       if (Error Err = Stream.SkipBlock())
6810         return std::move(Err);
6811       continue;
6812     }
6813     case BitstreamEntry::Record:
6814       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
6815         continue;
6816       else
6817         return StreamFailed.takeError();
6818     }
6819   }
6820 }
6821 
6822 /// Get a lazy one-at-time loading module from bitcode.
6823 ///
6824 /// This isn't always used in a lazy context.  In particular, it's also used by
6825 /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
6826 /// in forward-referenced functions from block address references.
6827 ///
6828 /// \param[in] MaterializeAll Set to \c true if we should materialize
6829 /// everything.
6830 Expected<std::unique_ptr<Module>>
getModuleImpl(LLVMContext & Context,bool MaterializeAll,bool ShouldLazyLoadMetadata,bool IsImporting,DataLayoutCallbackTy DataLayoutCallback)6831 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
6832                              bool ShouldLazyLoadMetadata, bool IsImporting,
6833                              DataLayoutCallbackTy DataLayoutCallback) {
6834   BitstreamCursor Stream(Buffer);
6835 
6836   std::string ProducerIdentification;
6837   if (IdentificationBit != -1ull) {
6838     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
6839       return std::move(JumpFailed);
6840     Expected<std::string> ProducerIdentificationOrErr =
6841         readIdentificationBlock(Stream);
6842     if (!ProducerIdentificationOrErr)
6843       return ProducerIdentificationOrErr.takeError();
6844 
6845     ProducerIdentification = *ProducerIdentificationOrErr;
6846   }
6847 
6848   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6849     return std::move(JumpFailed);
6850   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
6851                               Context);
6852 
6853   std::unique_ptr<Module> M =
6854       std::make_unique<Module>(ModuleIdentifier, Context);
6855   M->setMaterializer(R);
6856 
6857   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6858   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
6859                                       IsImporting, DataLayoutCallback))
6860     return std::move(Err);
6861 
6862   if (MaterializeAll) {
6863     // Read in the entire module, and destroy the BitcodeReader.
6864     if (Error Err = M->materializeAll())
6865       return std::move(Err);
6866   } else {
6867     // Resolve forward references from blockaddresses.
6868     if (Error Err = R->materializeForwardReferencedFunctions())
6869       return std::move(Err);
6870   }
6871   return std::move(M);
6872 }
6873 
6874 Expected<std::unique_ptr<Module>>
getLazyModule(LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting)6875 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
6876                              bool IsImporting) {
6877   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
6878                        [](StringRef) { return None; });
6879 }
6880 
6881 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
6882 // We don't use ModuleIdentifier here because the client may need to control the
6883 // module path used in the combined summary (e.g. when reading summaries for
6884 // regular LTO modules).
readSummary(ModuleSummaryIndex & CombinedIndex,StringRef ModulePath,uint64_t ModuleId)6885 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
6886                                  StringRef ModulePath, uint64_t ModuleId) {
6887   BitstreamCursor Stream(Buffer);
6888   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6889     return JumpFailed;
6890 
6891   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
6892                                     ModulePath, ModuleId);
6893   return R.parseModule();
6894 }
6895 
6896 // Parse the specified bitcode buffer, returning the function info index.
getSummary()6897 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
6898   BitstreamCursor Stream(Buffer);
6899   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6900     return std::move(JumpFailed);
6901 
6902   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
6903   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
6904                                     ModuleIdentifier, 0);
6905 
6906   if (Error Err = R.parseModule())
6907     return std::move(Err);
6908 
6909   return std::move(Index);
6910 }
6911 
getEnableSplitLTOUnitFlag(BitstreamCursor & Stream,unsigned ID)6912 static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
6913                                                 unsigned ID) {
6914   if (Error Err = Stream.EnterSubBlock(ID))
6915     return std::move(Err);
6916   SmallVector<uint64_t, 64> Record;
6917 
6918   while (true) {
6919     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6920     if (!MaybeEntry)
6921       return MaybeEntry.takeError();
6922     BitstreamEntry Entry = MaybeEntry.get();
6923 
6924     switch (Entry.Kind) {
6925     case BitstreamEntry::SubBlock: // Handled for us already.
6926     case BitstreamEntry::Error:
6927       return error("Malformed block");
6928     case BitstreamEntry::EndBlock:
6929       // If no flags record found, conservatively return true to mimic
6930       // behavior before this flag was added.
6931       return true;
6932     case BitstreamEntry::Record:
6933       // The interesting case.
6934       break;
6935     }
6936 
6937     // Look for the FS_FLAGS record.
6938     Record.clear();
6939     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6940     if (!MaybeBitCode)
6941       return MaybeBitCode.takeError();
6942     switch (MaybeBitCode.get()) {
6943     default: // Default behavior: ignore.
6944       break;
6945     case bitc::FS_FLAGS: { // [flags]
6946       uint64_t Flags = Record[0];
6947       // Scan flags.
6948       assert(Flags <= 0x7f && "Unexpected bits in flag");
6949 
6950       return Flags & 0x8;
6951     }
6952     }
6953   }
6954   llvm_unreachable("Exit infinite loop");
6955 }
6956 
6957 // Check if the given bitcode buffer contains a global value summary block.
getLTOInfo()6958 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
6959   BitstreamCursor Stream(Buffer);
6960   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6961     return std::move(JumpFailed);
6962 
6963   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6964     return std::move(Err);
6965 
6966   while (true) {
6967     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6968     if (!MaybeEntry)
6969       return MaybeEntry.takeError();
6970     llvm::BitstreamEntry Entry = MaybeEntry.get();
6971 
6972     switch (Entry.Kind) {
6973     case BitstreamEntry::Error:
6974       return error("Malformed block");
6975     case BitstreamEntry::EndBlock:
6976       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
6977                             /*EnableSplitLTOUnit=*/false};
6978 
6979     case BitstreamEntry::SubBlock:
6980       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
6981         Expected<bool> EnableSplitLTOUnit =
6982             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
6983         if (!EnableSplitLTOUnit)
6984           return EnableSplitLTOUnit.takeError();
6985         return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
6986                               *EnableSplitLTOUnit};
6987       }
6988 
6989       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
6990         Expected<bool> EnableSplitLTOUnit =
6991             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
6992         if (!EnableSplitLTOUnit)
6993           return EnableSplitLTOUnit.takeError();
6994         return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
6995                               *EnableSplitLTOUnit};
6996       }
6997 
6998       // Ignore other sub-blocks.
6999       if (Error Err = Stream.SkipBlock())
7000         return std::move(Err);
7001       continue;
7002 
7003     case BitstreamEntry::Record:
7004       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
7005         continue;
7006       else
7007         return StreamFailed.takeError();
7008     }
7009   }
7010 }
7011 
getSingleModule(MemoryBufferRef Buffer)7012 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
7013   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
7014   if (!MsOrErr)
7015     return MsOrErr.takeError();
7016 
7017   if (MsOrErr->size() != 1)
7018     return error("Expected a single module");
7019 
7020   return (*MsOrErr)[0];
7021 }
7022 
7023 Expected<std::unique_ptr<Module>>
getLazyBitcodeModule(MemoryBufferRef Buffer,LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting)7024 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
7025                            bool ShouldLazyLoadMetadata, bool IsImporting) {
7026   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7027   if (!BM)
7028     return BM.takeError();
7029 
7030   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
7031 }
7032 
getOwningLazyBitcodeModule(std::unique_ptr<MemoryBuffer> && Buffer,LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting)7033 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
7034     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
7035     bool ShouldLazyLoadMetadata, bool IsImporting) {
7036   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
7037                                      IsImporting);
7038   if (MOrErr)
7039     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
7040   return MOrErr;
7041 }
7042 
7043 Expected<std::unique_ptr<Module>>
parseModule(LLVMContext & Context,DataLayoutCallbackTy DataLayoutCallback)7044 BitcodeModule::parseModule(LLVMContext &Context,
7045                            DataLayoutCallbackTy DataLayoutCallback) {
7046   return getModuleImpl(Context, true, false, false, DataLayoutCallback);
7047   // TODO: Restore the use-lists to the in-memory state when the bitcode was
7048   // written.  We must defer until the Module has been fully materialized.
7049 }
7050 
7051 Expected<std::unique_ptr<Module>>
parseBitcodeFile(MemoryBufferRef Buffer,LLVMContext & Context,DataLayoutCallbackTy DataLayoutCallback)7052 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
7053                        DataLayoutCallbackTy DataLayoutCallback) {
7054   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7055   if (!BM)
7056     return BM.takeError();
7057 
7058   return BM->parseModule(Context, DataLayoutCallback);
7059 }
7060 
getBitcodeTargetTriple(MemoryBufferRef Buffer)7061 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
7062   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7063   if (!StreamOrErr)
7064     return StreamOrErr.takeError();
7065 
7066   return readTriple(*StreamOrErr);
7067 }
7068 
isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)7069 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
7070   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7071   if (!StreamOrErr)
7072     return StreamOrErr.takeError();
7073 
7074   return hasObjCCategory(*StreamOrErr);
7075 }
7076 
getBitcodeProducerString(MemoryBufferRef Buffer)7077 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
7078   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7079   if (!StreamOrErr)
7080     return StreamOrErr.takeError();
7081 
7082   return readIdentificationCode(*StreamOrErr);
7083 }
7084 
readModuleSummaryIndex(MemoryBufferRef Buffer,ModuleSummaryIndex & CombinedIndex,uint64_t ModuleId)7085 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
7086                                    ModuleSummaryIndex &CombinedIndex,
7087                                    uint64_t ModuleId) {
7088   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7089   if (!BM)
7090     return BM.takeError();
7091 
7092   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
7093 }
7094 
7095 Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndex(MemoryBufferRef Buffer)7096 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
7097   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7098   if (!BM)
7099     return BM.takeError();
7100 
7101   return BM->getSummary();
7102 }
7103 
getBitcodeLTOInfo(MemoryBufferRef Buffer)7104 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
7105   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7106   if (!BM)
7107     return BM.takeError();
7108 
7109   return BM->getLTOInfo();
7110 }
7111 
7112 Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndexForFile(StringRef Path,bool IgnoreEmptyThinLTOIndexFile)7113 llvm::getModuleSummaryIndexForFile(StringRef Path,
7114                                    bool IgnoreEmptyThinLTOIndexFile) {
7115   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
7116       MemoryBuffer::getFileOrSTDIN(Path);
7117   if (!FileOrErr)
7118     return errorCodeToError(FileOrErr.getError());
7119   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
7120     return nullptr;
7121   return getModuleSummaryIndex(**FileOrErr);
7122 }
7123