1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/Bitcode/BitcodeReader.h"
11 #include "MetadataLoader.h"
12 #include "ValueList.h"
13 
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Bitcode/BitstreamReader.h"
26 #include "llvm/Bitcode/LLVMBitCodes.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/CallSite.h"
33 #include "llvm/IR/Comdat.h"
34 #include "llvm/IR/Constant.h"
35 #include "llvm/IR/Constants.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/DiagnosticInfo.h"
41 #include "llvm/IR/DiagnosticPrinter.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalIFunc.h"
45 #include "llvm/IR/GlobalIndirectSymbol.h"
46 #include "llvm/IR/GlobalObject.h"
47 #include "llvm/IR/GlobalValue.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/GVMaterializer.h"
50 #include "llvm/IR/InlineAsm.h"
51 #include "llvm/IR/InstIterator.h"
52 #include "llvm/IR/InstrTypes.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/Intrinsics.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/ModuleSummaryIndex.h"
59 #include "llvm/IR/OperandTraits.h"
60 #include "llvm/IR/Operator.h"
61 #include "llvm/IR/TrackingMDRef.h"
62 #include "llvm/IR/Type.h"
63 #include "llvm/IR/ValueHandle.h"
64 #include "llvm/IR/Verifier.h"
65 #include "llvm/Support/AtomicOrdering.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/Error.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/ManagedStatic.h"
73 #include "llvm/Support/MemoryBuffer.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <cstdint>
79 #include <deque>
80 #include <limits>
81 #include <map>
82 #include <memory>
83 #include <string>
84 #include <system_error>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 static cl::opt<bool> PrintSummaryGUIDs(
92     "print-summary-global-ids", cl::init(false), cl::Hidden,
93     cl::desc(
94         "Print the global id for each value when reading the module summary"));
95 
96 // FIXME: This flag should either be removed or moved to clang as a driver flag.
97 static llvm::cl::opt<bool> IgnoreEmptyThinLTOIndexFile(
98     "ignore-empty-index-file", llvm::cl::ZeroOrMore,
99     llvm::cl::desc(
100         "Ignore an empty index file and perform non-ThinLTO compilation"),
101     llvm::cl::init(false));
102 
103 namespace {
104 
105 enum {
106   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
107 };
108 
109 Error error(const Twine &Message) {
110   return make_error<StringError>(
111       Message, make_error_code(BitcodeError::CorruptedBitcode));
112 }
113 
114 /// Helper to read the header common to all bitcode files.
115 bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
116   // Sniff for the signature.
117   if (!Stream.canSkipToPos(4) ||
118       Stream.Read(8) != 'B' ||
119       Stream.Read(8) != 'C' ||
120       Stream.Read(4) != 0x0 ||
121       Stream.Read(4) != 0xC ||
122       Stream.Read(4) != 0xE ||
123       Stream.Read(4) != 0xD)
124     return false;
125   return true;
126 }
127 
128 Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
129   const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
130   const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
131 
132   if (Buffer.getBufferSize() & 3)
133     return error("Invalid bitcode signature");
134 
135   // If we have a wrapper header, parse it and ignore the non-bc file contents.
136   // The magic number is 0x0B17C0DE stored in little endian.
137   if (isBitcodeWrapper(BufPtr, BufEnd))
138     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
139       return error("Invalid bitcode wrapper header");
140 
141   BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
142   if (!hasValidBitcodeHeader(Stream))
143     return error("Invalid bitcode signature");
144 
145   return std::move(Stream);
146 }
147 
148 /// Convert a string from a record into an std::string, return true on failure.
149 template <typename StrTy>
150 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
151                             StrTy &Result) {
152   if (Idx > Record.size())
153     return true;
154 
155   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
156     Result += (char)Record[i];
157   return false;
158 }
159 
160 // Strip all the TBAA attachment for the module.
161 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.
172 Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
173   if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
174     return error("Invalid record");
175 
176   // Read all the records.
177   SmallVector<uint64_t, 64> Record;
178 
179   std::string ProducerIdentification;
180 
181   while (true) {
182     BitstreamEntry Entry = Stream.advance();
183 
184     switch (Entry.Kind) {
185     default:
186     case BitstreamEntry::Error:
187       return error("Malformed block");
188     case BitstreamEntry::EndBlock:
189       return ProducerIdentification;
190     case BitstreamEntry::Record:
191       // The interesting case.
192       break;
193     }
194 
195     // Read a record.
196     Record.clear();
197     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
198     switch (BitCode) {
199     default: // Default behavior: reject
200       return error("Invalid value");
201     case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
202       convertToString(Record, 0, ProducerIdentification);
203       break;
204     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
205       unsigned epoch = (unsigned)Record[0];
206       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
207         return error(
208           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
209           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
210       }
211     }
212     }
213   }
214 }
215 
216 Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
217   // We expect a number of well-defined blocks, though we don't necessarily
218   // need to understand them all.
219   while (true) {
220     if (Stream.AtEndOfStream())
221       return "";
222 
223     BitstreamEntry Entry = Stream.advance();
224     switch (Entry.Kind) {
225     case BitstreamEntry::EndBlock:
226     case BitstreamEntry::Error:
227       return error("Malformed block");
228 
229     case BitstreamEntry::SubBlock:
230       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
231         return readIdentificationBlock(Stream);
232 
233       // Ignore other sub-blocks.
234       if (Stream.SkipBlock())
235         return error("Malformed block");
236       continue;
237     case BitstreamEntry::Record:
238       Stream.skipRecord(Entry.ID);
239       continue;
240     }
241   }
242 }
243 
244 Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
245   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
246     return error("Invalid record");
247 
248   SmallVector<uint64_t, 64> Record;
249   // Read all the records for this module.
250 
251   while (true) {
252     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
253 
254     switch (Entry.Kind) {
255     case BitstreamEntry::SubBlock: // Handled for us already.
256     case BitstreamEntry::Error:
257       return error("Malformed block");
258     case BitstreamEntry::EndBlock:
259       return false;
260     case BitstreamEntry::Record:
261       // The interesting case.
262       break;
263     }
264 
265     // Read a record.
266     switch (Stream.readRecord(Entry.ID, Record)) {
267     default:
268       break; // Default behavior, ignore unknown content.
269     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
270       std::string S;
271       if (convertToString(Record, 0, S))
272         return error("Invalid record");
273       // Check for the i386 and other (x86_64, ARM) conventions
274       if (S.find("__DATA, __objc_catlist") != std::string::npos ||
275           S.find("__OBJC,__category") != std::string::npos)
276         return true;
277       break;
278     }
279     }
280     Record.clear();
281   }
282   llvm_unreachable("Exit infinite loop");
283 }
284 
285 Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
286   // We expect a number of well-defined blocks, though we don't necessarily
287   // need to understand them all.
288   while (true) {
289     BitstreamEntry Entry = Stream.advance();
290 
291     switch (Entry.Kind) {
292     case BitstreamEntry::Error:
293       return error("Malformed block");
294     case BitstreamEntry::EndBlock:
295       return false;
296 
297     case BitstreamEntry::SubBlock:
298       if (Entry.ID == bitc::MODULE_BLOCK_ID)
299         return hasObjCCategoryInModule(Stream);
300 
301       // Ignore other sub-blocks.
302       if (Stream.SkipBlock())
303         return error("Malformed block");
304       continue;
305 
306     case BitstreamEntry::Record:
307       Stream.skipRecord(Entry.ID);
308       continue;
309     }
310   }
311 }
312 
313 Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
314   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
315     return error("Invalid record");
316 
317   SmallVector<uint64_t, 64> Record;
318 
319   std::string Triple;
320 
321   // Read all the records for this module.
322   while (true) {
323     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
324 
325     switch (Entry.Kind) {
326     case BitstreamEntry::SubBlock: // Handled for us already.
327     case BitstreamEntry::Error:
328       return error("Malformed block");
329     case BitstreamEntry::EndBlock:
330       return Triple;
331     case BitstreamEntry::Record:
332       // The interesting case.
333       break;
334     }
335 
336     // Read a record.
337     switch (Stream.readRecord(Entry.ID, Record)) {
338     default: break;  // Default behavior, ignore unknown content.
339     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
340       std::string S;
341       if (convertToString(Record, 0, S))
342         return error("Invalid record");
343       Triple = S;
344       break;
345     }
346     }
347     Record.clear();
348   }
349   llvm_unreachable("Exit infinite loop");
350 }
351 
352 Expected<std::string> readTriple(BitstreamCursor &Stream) {
353   // We expect a number of well-defined blocks, though we don't necessarily
354   // need to understand them all.
355   while (true) {
356     BitstreamEntry Entry = Stream.advance();
357 
358     switch (Entry.Kind) {
359     case BitstreamEntry::Error:
360       return error("Malformed block");
361     case BitstreamEntry::EndBlock:
362       return "";
363 
364     case BitstreamEntry::SubBlock:
365       if (Entry.ID == bitc::MODULE_BLOCK_ID)
366         return readModuleTriple(Stream);
367 
368       // Ignore other sub-blocks.
369       if (Stream.SkipBlock())
370         return error("Malformed block");
371       continue;
372 
373     case BitstreamEntry::Record:
374       Stream.skipRecord(Entry.ID);
375       continue;
376     }
377   }
378 }
379 
380 class BitcodeReaderBase {
381 protected:
382   BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
383       : Stream(std::move(Stream)), Strtab(Strtab) {
384     this->Stream.setBlockInfo(&BlockInfo);
385   }
386 
387   BitstreamBlockInfo BlockInfo;
388   BitstreamCursor Stream;
389   StringRef Strtab;
390 
391   /// In version 2 of the bitcode we store names of global values and comdats in
392   /// a string table rather than in the VST.
393   bool UseStrtab = false;
394 
395   Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
396 
397   /// If this module uses a string table, pop the reference to the string table
398   /// and return the referenced string and the rest of the record. Otherwise
399   /// just return the record itself.
400   std::pair<StringRef, ArrayRef<uint64_t>>
401   readNameFromStrtab(ArrayRef<uint64_t> Record);
402 
403   bool readBlockInfo();
404 
405   // Contains an arbitrary and optional string identifying the bitcode producer
406   std::string ProducerIdentification;
407 
408   Error error(const Twine &Message);
409 };
410 
411 Error BitcodeReaderBase::error(const Twine &Message) {
412   std::string FullMsg = Message.str();
413   if (!ProducerIdentification.empty())
414     FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
415                LLVM_VERSION_STRING "')";
416   return ::error(FullMsg);
417 }
418 
419 Expected<unsigned>
420 BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
421   if (Record.size() < 1)
422     return error("Invalid record");
423   unsigned ModuleVersion = Record[0];
424   if (ModuleVersion > 2)
425     return error("Invalid value");
426   UseStrtab = ModuleVersion >= 2;
427   return ModuleVersion;
428 }
429 
430 std::pair<StringRef, ArrayRef<uint64_t>>
431 BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
432   if (!UseStrtab)
433     return {"", Record};
434   // Invalid reference. Let the caller complain about the record being empty.
435   if (Record[0] + Record[1] > Strtab.size())
436     return {"", {}};
437   return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
438 }
439 
440 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
441   LLVMContext &Context;
442   Module *TheModule = nullptr;
443   // Next offset to start scanning for lazy parsing of function bodies.
444   uint64_t NextUnreadBit = 0;
445   // Last function offset found in the VST.
446   uint64_t LastFunctionBlockBit = 0;
447   bool SeenValueSymbolTable = false;
448   uint64_t VSTOffset = 0;
449 
450   std::vector<std::string> SectionTable;
451   std::vector<std::string> GCTable;
452 
453   std::vector<Type*> TypeList;
454   BitcodeReaderValueList ValueList;
455   Optional<MetadataLoader> MDLoader;
456   std::vector<Comdat *> ComdatList;
457   SmallVector<Instruction *, 64> InstructionList;
458 
459   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
460   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
461   std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
462   std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
463   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
464 
465   /// The set of attributes by index.  Index zero in the file is for null, and
466   /// is thus not represented here.  As such all indices are off by one.
467   std::vector<AttributeList> MAttributes;
468 
469   /// The set of attribute groups.
470   std::map<unsigned, AttributeList> MAttributeGroups;
471 
472   /// While parsing a function body, this is a list of the basic blocks for the
473   /// function.
474   std::vector<BasicBlock*> FunctionBBs;
475 
476   // When reading the module header, this list is populated with functions that
477   // have bodies later in the file.
478   std::vector<Function*> FunctionsWithBodies;
479 
480   // When intrinsic functions are encountered which require upgrading they are
481   // stored here with their replacement function.
482   typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
483   UpdatedIntrinsicMap UpgradedIntrinsics;
484   // Intrinsics which were remangled because of types rename
485   UpdatedIntrinsicMap RemangledIntrinsics;
486 
487   // Several operations happen after the module header has been read, but
488   // before function bodies are processed. This keeps track of whether
489   // we've done this yet.
490   bool SeenFirstFunctionBody = false;
491 
492   /// When function bodies are initially scanned, this map contains info about
493   /// where to find deferred function body in the stream.
494   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
495 
496   /// When Metadata block is initially scanned when parsing the module, we may
497   /// choose to defer parsing of the metadata. This vector contains info about
498   /// which Metadata blocks are deferred.
499   std::vector<uint64_t> DeferredMetadataInfo;
500 
501   /// These are basic blocks forward-referenced by block addresses.  They are
502   /// inserted lazily into functions when they're loaded.  The basic block ID is
503   /// its index into the vector.
504   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
505   std::deque<Function *> BasicBlockFwdRefQueue;
506 
507   /// Indicates that we are using a new encoding for instruction operands where
508   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
509   /// instruction number, for a more compact encoding.  Some instruction
510   /// operands are not relative to the instruction ID: basic block numbers, and
511   /// types. Once the old style function blocks have been phased out, we would
512   /// not need this flag.
513   bool UseRelativeIDs = false;
514 
515   /// True if all functions will be materialized, negating the need to process
516   /// (e.g.) blockaddress forward references.
517   bool WillMaterializeAllForwardRefs = false;
518 
519   bool StripDebugInfo = false;
520   TBAAVerifier TBAAVerifyHelper;
521 
522   std::vector<std::string> BundleTags;
523 
524 public:
525   BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
526                 StringRef ProducerIdentification, LLVMContext &Context);
527 
528   Error materializeForwardReferencedFunctions();
529 
530   Error materialize(GlobalValue *GV) override;
531   Error materializeModule() override;
532   std::vector<StructType *> getIdentifiedStructTypes() const override;
533 
534   /// \brief Main interface to parsing a bitcode buffer.
535   /// \returns true if an error occurred.
536   Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
537                          bool IsImporting = false);
538 
539   static uint64_t decodeSignRotatedValue(uint64_t V);
540 
541   /// Materialize any deferred Metadata block.
542   Error materializeMetadata() override;
543 
544   void setStripDebugInfo() override;
545 
546 private:
547   std::vector<StructType *> IdentifiedStructTypes;
548   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
549   StructType *createIdentifiedStructType(LLVMContext &Context);
550 
551   Type *getTypeByID(unsigned ID);
552 
553   Value *getFnValueByID(unsigned ID, Type *Ty) {
554     if (Ty && Ty->isMetadataTy())
555       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
556     return ValueList.getValueFwdRef(ID, Ty);
557   }
558 
559   Metadata *getFnMetadataByID(unsigned ID) {
560     return MDLoader->getMetadataFwdRefOrLoad(ID);
561   }
562 
563   BasicBlock *getBasicBlock(unsigned ID) const {
564     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
565     return FunctionBBs[ID];
566   }
567 
568   AttributeList getAttributes(unsigned i) const {
569     if (i-1 < MAttributes.size())
570       return MAttributes[i-1];
571     return AttributeList();
572   }
573 
574   /// Read a value/type pair out of the specified record from slot 'Slot'.
575   /// Increment Slot past the number of slots used in the record. Return true on
576   /// failure.
577   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
578                         unsigned InstNum, Value *&ResVal) {
579     if (Slot == Record.size()) return true;
580     unsigned ValNo = (unsigned)Record[Slot++];
581     // Adjust the ValNo, if it was encoded relative to the InstNum.
582     if (UseRelativeIDs)
583       ValNo = InstNum - ValNo;
584     if (ValNo < InstNum) {
585       // If this is not a forward reference, just return the value we already
586       // have.
587       ResVal = getFnValueByID(ValNo, nullptr);
588       return ResVal == nullptr;
589     }
590     if (Slot == Record.size())
591       return true;
592 
593     unsigned TypeNo = (unsigned)Record[Slot++];
594     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
595     return ResVal == nullptr;
596   }
597 
598   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
599   /// past the number of slots used by the value in the record. Return true if
600   /// there is an error.
601   bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
602                 unsigned InstNum, Type *Ty, Value *&ResVal) {
603     if (getValue(Record, Slot, InstNum, Ty, ResVal))
604       return true;
605     // All values currently take a single record slot.
606     ++Slot;
607     return false;
608   }
609 
610   /// Like popValue, but does not increment the Slot number.
611   bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
612                 unsigned InstNum, Type *Ty, Value *&ResVal) {
613     ResVal = getValue(Record, Slot, InstNum, Ty);
614     return ResVal == nullptr;
615   }
616 
617   /// Version of getValue that returns ResVal directly, or 0 if there is an
618   /// error.
619   Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
620                   unsigned InstNum, Type *Ty) {
621     if (Slot == Record.size()) return nullptr;
622     unsigned ValNo = (unsigned)Record[Slot];
623     // Adjust the ValNo, if it was encoded relative to the InstNum.
624     if (UseRelativeIDs)
625       ValNo = InstNum - ValNo;
626     return getFnValueByID(ValNo, Ty);
627   }
628 
629   /// Like getValue, but decodes signed VBRs.
630   Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
631                         unsigned InstNum, Type *Ty) {
632     if (Slot == Record.size()) return nullptr;
633     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
634     // Adjust the ValNo, if it was encoded relative to the InstNum.
635     if (UseRelativeIDs)
636       ValNo = InstNum - ValNo;
637     return getFnValueByID(ValNo, Ty);
638   }
639 
640   /// Converts alignment exponent (i.e. power of two (or zero)) to the
641   /// corresponding alignment to use. If alignment is too large, returns
642   /// a corresponding error code.
643   Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
644   Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
645   Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
646 
647   Error parseComdatRecord(ArrayRef<uint64_t> Record);
648   Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
649   Error parseFunctionRecord(ArrayRef<uint64_t> Record);
650   Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
651                                         ArrayRef<uint64_t> Record);
652 
653   Error parseAttributeBlock();
654   Error parseAttributeGroupBlock();
655   Error parseTypeTable();
656   Error parseTypeTableBody();
657   Error parseOperandBundleTags();
658 
659   Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
660                                 unsigned NameIndex, Triple &TT);
661   void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
662                                ArrayRef<uint64_t> Record);
663   Error parseValueSymbolTable(uint64_t Offset = 0);
664   Error parseGlobalValueSymbolTable();
665   Error parseConstants();
666   Error rememberAndSkipFunctionBodies();
667   Error rememberAndSkipFunctionBody();
668   /// Save the positions of the Metadata blocks and skip parsing the blocks.
669   Error rememberAndSkipMetadata();
670   Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
671   Error parseFunctionBody(Function *F);
672   Error globalCleanup();
673   Error resolveGlobalAndIndirectSymbolInits();
674   Error parseUseLists();
675   Error findFunctionInStream(
676       Function *F,
677       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
678 };
679 
680 /// Class to manage reading and parsing function summary index bitcode
681 /// files/sections.
682 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
683   /// The module index built during parsing.
684   ModuleSummaryIndex &TheIndex;
685 
686   /// Indicates whether we have encountered a global value summary section
687   /// yet during parsing.
688   bool SeenGlobalValSummary = false;
689 
690   /// Indicates whether we have already parsed the VST, used for error checking.
691   bool SeenValueSymbolTable = false;
692 
693   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
694   /// Used to enable on-demand parsing of the VST.
695   uint64_t VSTOffset = 0;
696 
697   // Map to save ValueId to GUID association that was recorded in the
698   // ValueSymbolTable. It is used after the VST is parsed to convert
699   // call graph edges read from the function summary from referencing
700   // callees by their ValueId to using the GUID instead, which is how
701   // they are recorded in the summary index being built.
702   // We save a second GUID which is the same as the first one, but ignoring the
703   // linkage, i.e. for value other than local linkage they are identical.
704   DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
705       ValueIdToCallGraphGUIDMap;
706 
707   /// Map populated during module path string table parsing, from the
708   /// module ID to a string reference owned by the index's module
709   /// path string table, used to correlate with combined index
710   /// summary records.
711   DenseMap<uint64_t, StringRef> ModuleIdMap;
712 
713   /// Original source file name recorded in a bitcode record.
714   std::string SourceFileName;
715 
716 public:
717   ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
718                                   ModuleSummaryIndex &TheIndex);
719 
720   Error parseModule(StringRef ModulePath);
721 
722 private:
723   void setValueGUID(uint64_t ValueID, StringRef ValueName,
724                     GlobalValue::LinkageTypes Linkage,
725                     StringRef SourceFileName);
726   Error parseValueSymbolTable(
727       uint64_t Offset,
728       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
729   std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
730   std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
731                                                     bool IsOldProfileFormat,
732                                                     bool HasProfile);
733   Error parseEntireSummary(StringRef ModulePath);
734   Error parseModuleStringTable();
735 
736   std::pair<GlobalValue::GUID, GlobalValue::GUID>
737   getGUIDFromValueId(unsigned ValueId);
738 };
739 
740 } // end anonymous namespace
741 
742 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
743                                                     Error Err) {
744   if (Err) {
745     std::error_code EC;
746     handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
747       EC = EIB.convertToErrorCode();
748       Ctx.emitError(EIB.message());
749     });
750     return EC;
751   }
752   return std::error_code();
753 }
754 
755 BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
756                              StringRef ProducerIdentification,
757                              LLVMContext &Context)
758     : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
759       ValueList(Context) {
760   this->ProducerIdentification = ProducerIdentification;
761 }
762 
763 Error BitcodeReader::materializeForwardReferencedFunctions() {
764   if (WillMaterializeAllForwardRefs)
765     return Error::success();
766 
767   // Prevent recursion.
768   WillMaterializeAllForwardRefs = true;
769 
770   while (!BasicBlockFwdRefQueue.empty()) {
771     Function *F = BasicBlockFwdRefQueue.front();
772     BasicBlockFwdRefQueue.pop_front();
773     assert(F && "Expected valid function");
774     if (!BasicBlockFwdRefs.count(F))
775       // Already materialized.
776       continue;
777 
778     // Check for a function that isn't materializable to prevent an infinite
779     // loop.  When parsing a blockaddress stored in a global variable, there
780     // isn't a trivial way to check if a function will have a body without a
781     // linear search through FunctionsWithBodies, so just check it here.
782     if (!F->isMaterializable())
783       return error("Never resolved function from blockaddress");
784 
785     // Try to materialize F.
786     if (Error Err = materialize(F))
787       return Err;
788   }
789   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
790 
791   // Reset state.
792   WillMaterializeAllForwardRefs = false;
793   return Error::success();
794 }
795 
796 //===----------------------------------------------------------------------===//
797 //  Helper functions to implement forward reference resolution, etc.
798 //===----------------------------------------------------------------------===//
799 
800 static bool hasImplicitComdat(size_t Val) {
801   switch (Val) {
802   default:
803     return false;
804   case 1:  // Old WeakAnyLinkage
805   case 4:  // Old LinkOnceAnyLinkage
806   case 10: // Old WeakODRLinkage
807   case 11: // Old LinkOnceODRLinkage
808     return true;
809   }
810 }
811 
812 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
813   switch (Val) {
814   default: // Map unknown/new linkages to external
815   case 0:
816     return GlobalValue::ExternalLinkage;
817   case 2:
818     return GlobalValue::AppendingLinkage;
819   case 3:
820     return GlobalValue::InternalLinkage;
821   case 5:
822     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
823   case 6:
824     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
825   case 7:
826     return GlobalValue::ExternalWeakLinkage;
827   case 8:
828     return GlobalValue::CommonLinkage;
829   case 9:
830     return GlobalValue::PrivateLinkage;
831   case 12:
832     return GlobalValue::AvailableExternallyLinkage;
833   case 13:
834     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
835   case 14:
836     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
837   case 15:
838     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
839   case 1: // Old value with implicit comdat.
840   case 16:
841     return GlobalValue::WeakAnyLinkage;
842   case 10: // Old value with implicit comdat.
843   case 17:
844     return GlobalValue::WeakODRLinkage;
845   case 4: // Old value with implicit comdat.
846   case 18:
847     return GlobalValue::LinkOnceAnyLinkage;
848   case 11: // Old value with implicit comdat.
849   case 19:
850     return GlobalValue::LinkOnceODRLinkage;
851   }
852 }
853 
854 /// Decode the flags for GlobalValue in the summary.
855 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
856                                                             uint64_t Version) {
857   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
858   // like getDecodedLinkage() above. Any future change to the linkage enum and
859   // to getDecodedLinkage() will need to be taken into account here as above.
860   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
861   RawFlags = RawFlags >> 4;
862   bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
863   // The LiveRoot flag wasn't introduced until version 3. For dead stripping
864   // to work correctly on earlier versions, we must conservatively treat all
865   // values as live.
866   bool LiveRoot = (RawFlags & 0x2) || Version < 3;
867   return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, LiveRoot);
868 }
869 
870 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
871   switch (Val) {
872   default: // Map unknown visibilities to default.
873   case 0: return GlobalValue::DefaultVisibility;
874   case 1: return GlobalValue::HiddenVisibility;
875   case 2: return GlobalValue::ProtectedVisibility;
876   }
877 }
878 
879 static GlobalValue::DLLStorageClassTypes
880 getDecodedDLLStorageClass(unsigned Val) {
881   switch (Val) {
882   default: // Map unknown values to default.
883   case 0: return GlobalValue::DefaultStorageClass;
884   case 1: return GlobalValue::DLLImportStorageClass;
885   case 2: return GlobalValue::DLLExportStorageClass;
886   }
887 }
888 
889 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
890   switch (Val) {
891     case 0: return GlobalVariable::NotThreadLocal;
892     default: // Map unknown non-zero value to general dynamic.
893     case 1: return GlobalVariable::GeneralDynamicTLSModel;
894     case 2: return GlobalVariable::LocalDynamicTLSModel;
895     case 3: return GlobalVariable::InitialExecTLSModel;
896     case 4: return GlobalVariable::LocalExecTLSModel;
897   }
898 }
899 
900 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
901   switch (Val) {
902     default: // Map unknown to UnnamedAddr::None.
903     case 0: return GlobalVariable::UnnamedAddr::None;
904     case 1: return GlobalVariable::UnnamedAddr::Global;
905     case 2: return GlobalVariable::UnnamedAddr::Local;
906   }
907 }
908 
909 static int getDecodedCastOpcode(unsigned Val) {
910   switch (Val) {
911   default: return -1;
912   case bitc::CAST_TRUNC   : return Instruction::Trunc;
913   case bitc::CAST_ZEXT    : return Instruction::ZExt;
914   case bitc::CAST_SEXT    : return Instruction::SExt;
915   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
916   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
917   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
918   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
919   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
920   case bitc::CAST_FPEXT   : return Instruction::FPExt;
921   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
922   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
923   case bitc::CAST_BITCAST : return Instruction::BitCast;
924   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
925   }
926 }
927 
928 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
929   bool IsFP = Ty->isFPOrFPVectorTy();
930   // BinOps are only valid for int/fp or vector of int/fp types
931   if (!IsFP && !Ty->isIntOrIntVectorTy())
932     return -1;
933 
934   switch (Val) {
935   default:
936     return -1;
937   case bitc::BINOP_ADD:
938     return IsFP ? Instruction::FAdd : Instruction::Add;
939   case bitc::BINOP_SUB:
940     return IsFP ? Instruction::FSub : Instruction::Sub;
941   case bitc::BINOP_MUL:
942     return IsFP ? Instruction::FMul : Instruction::Mul;
943   case bitc::BINOP_UDIV:
944     return IsFP ? -1 : Instruction::UDiv;
945   case bitc::BINOP_SDIV:
946     return IsFP ? Instruction::FDiv : Instruction::SDiv;
947   case bitc::BINOP_UREM:
948     return IsFP ? -1 : Instruction::URem;
949   case bitc::BINOP_SREM:
950     return IsFP ? Instruction::FRem : Instruction::SRem;
951   case bitc::BINOP_SHL:
952     return IsFP ? -1 : Instruction::Shl;
953   case bitc::BINOP_LSHR:
954     return IsFP ? -1 : Instruction::LShr;
955   case bitc::BINOP_ASHR:
956     return IsFP ? -1 : Instruction::AShr;
957   case bitc::BINOP_AND:
958     return IsFP ? -1 : Instruction::And;
959   case bitc::BINOP_OR:
960     return IsFP ? -1 : Instruction::Or;
961   case bitc::BINOP_XOR:
962     return IsFP ? -1 : Instruction::Xor;
963   }
964 }
965 
966 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
967   switch (Val) {
968   default: return AtomicRMWInst::BAD_BINOP;
969   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
970   case bitc::RMW_ADD: return AtomicRMWInst::Add;
971   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
972   case bitc::RMW_AND: return AtomicRMWInst::And;
973   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
974   case bitc::RMW_OR: return AtomicRMWInst::Or;
975   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
976   case bitc::RMW_MAX: return AtomicRMWInst::Max;
977   case bitc::RMW_MIN: return AtomicRMWInst::Min;
978   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
979   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
980   }
981 }
982 
983 static AtomicOrdering getDecodedOrdering(unsigned Val) {
984   switch (Val) {
985   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
986   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
987   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
988   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
989   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
990   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
991   default: // Map unknown orderings to sequentially-consistent.
992   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
993   }
994 }
995 
996 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
997   switch (Val) {
998   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
999   default: // Map unknown scopes to cross-thread.
1000   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
1001   }
1002 }
1003 
1004 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1005   switch (Val) {
1006   default: // Map unknown selection kinds to any.
1007   case bitc::COMDAT_SELECTION_KIND_ANY:
1008     return Comdat::Any;
1009   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1010     return Comdat::ExactMatch;
1011   case bitc::COMDAT_SELECTION_KIND_LARGEST:
1012     return Comdat::Largest;
1013   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1014     return Comdat::NoDuplicates;
1015   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1016     return Comdat::SameSize;
1017   }
1018 }
1019 
1020 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1021   FastMathFlags FMF;
1022   if (0 != (Val & FastMathFlags::UnsafeAlgebra))
1023     FMF.setUnsafeAlgebra();
1024   if (0 != (Val & FastMathFlags::NoNaNs))
1025     FMF.setNoNaNs();
1026   if (0 != (Val & FastMathFlags::NoInfs))
1027     FMF.setNoInfs();
1028   if (0 != (Val & FastMathFlags::NoSignedZeros))
1029     FMF.setNoSignedZeros();
1030   if (0 != (Val & FastMathFlags::AllowReciprocal))
1031     FMF.setAllowReciprocal();
1032   if (0 != (Val & FastMathFlags::AllowContract))
1033     FMF.setAllowContract(true);
1034   return FMF;
1035 }
1036 
1037 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1038   switch (Val) {
1039   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1040   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1041   }
1042 }
1043 
1044 
1045 Type *BitcodeReader::getTypeByID(unsigned ID) {
1046   // The type table size is always specified correctly.
1047   if (ID >= TypeList.size())
1048     return nullptr;
1049 
1050   if (Type *Ty = TypeList[ID])
1051     return Ty;
1052 
1053   // If we have a forward reference, the only possible case is when it is to a
1054   // named struct.  Just create a placeholder for now.
1055   return TypeList[ID] = createIdentifiedStructType(Context);
1056 }
1057 
1058 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1059                                                       StringRef Name) {
1060   auto *Ret = StructType::create(Context, Name);
1061   IdentifiedStructTypes.push_back(Ret);
1062   return Ret;
1063 }
1064 
1065 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1066   auto *Ret = StructType::create(Context);
1067   IdentifiedStructTypes.push_back(Ret);
1068   return Ret;
1069 }
1070 
1071 //===----------------------------------------------------------------------===//
1072 //  Functions for parsing blocks from the bitcode file
1073 //===----------------------------------------------------------------------===//
1074 
1075 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1076   switch (Val) {
1077   case Attribute::EndAttrKinds:
1078     llvm_unreachable("Synthetic enumerators which should never get here");
1079 
1080   case Attribute::None:            return 0;
1081   case Attribute::ZExt:            return 1 << 0;
1082   case Attribute::SExt:            return 1 << 1;
1083   case Attribute::NoReturn:        return 1 << 2;
1084   case Attribute::InReg:           return 1 << 3;
1085   case Attribute::StructRet:       return 1 << 4;
1086   case Attribute::NoUnwind:        return 1 << 5;
1087   case Attribute::NoAlias:         return 1 << 6;
1088   case Attribute::ByVal:           return 1 << 7;
1089   case Attribute::Nest:            return 1 << 8;
1090   case Attribute::ReadNone:        return 1 << 9;
1091   case Attribute::ReadOnly:        return 1 << 10;
1092   case Attribute::NoInline:        return 1 << 11;
1093   case Attribute::AlwaysInline:    return 1 << 12;
1094   case Attribute::OptimizeForSize: return 1 << 13;
1095   case Attribute::StackProtect:    return 1 << 14;
1096   case Attribute::StackProtectReq: return 1 << 15;
1097   case Attribute::Alignment:       return 31 << 16;
1098   case Attribute::NoCapture:       return 1 << 21;
1099   case Attribute::NoRedZone:       return 1 << 22;
1100   case Attribute::NoImplicitFloat: return 1 << 23;
1101   case Attribute::Naked:           return 1 << 24;
1102   case Attribute::InlineHint:      return 1 << 25;
1103   case Attribute::StackAlignment:  return 7 << 26;
1104   case Attribute::ReturnsTwice:    return 1 << 29;
1105   case Attribute::UWTable:         return 1 << 30;
1106   case Attribute::NonLazyBind:     return 1U << 31;
1107   case Attribute::SanitizeAddress: return 1ULL << 32;
1108   case Attribute::MinSize:         return 1ULL << 33;
1109   case Attribute::NoDuplicate:     return 1ULL << 34;
1110   case Attribute::StackProtectStrong: return 1ULL << 35;
1111   case Attribute::SanitizeThread:  return 1ULL << 36;
1112   case Attribute::SanitizeMemory:  return 1ULL << 37;
1113   case Attribute::NoBuiltin:       return 1ULL << 38;
1114   case Attribute::Returned:        return 1ULL << 39;
1115   case Attribute::Cold:            return 1ULL << 40;
1116   case Attribute::Builtin:         return 1ULL << 41;
1117   case Attribute::OptimizeNone:    return 1ULL << 42;
1118   case Attribute::InAlloca:        return 1ULL << 43;
1119   case Attribute::NonNull:         return 1ULL << 44;
1120   case Attribute::JumpTable:       return 1ULL << 45;
1121   case Attribute::Convergent:      return 1ULL << 46;
1122   case Attribute::SafeStack:       return 1ULL << 47;
1123   case Attribute::NoRecurse:       return 1ULL << 48;
1124   case Attribute::InaccessibleMemOnly:         return 1ULL << 49;
1125   case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1126   case Attribute::SwiftSelf:       return 1ULL << 51;
1127   case Attribute::SwiftError:      return 1ULL << 52;
1128   case Attribute::WriteOnly:       return 1ULL << 53;
1129   case Attribute::Speculatable:    return 1ULL << 54;
1130   case Attribute::Dereferenceable:
1131     llvm_unreachable("dereferenceable attribute not supported in raw format");
1132     break;
1133   case Attribute::DereferenceableOrNull:
1134     llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1135                      "format");
1136     break;
1137   case Attribute::ArgMemOnly:
1138     llvm_unreachable("argmemonly attribute not supported in raw format");
1139     break;
1140   case Attribute::AllocSize:
1141     llvm_unreachable("allocsize not supported in raw format");
1142     break;
1143   }
1144   llvm_unreachable("Unsupported attribute type");
1145 }
1146 
1147 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1148   if (!Val) return;
1149 
1150   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1151        I = Attribute::AttrKind(I + 1)) {
1152     if (I == Attribute::Dereferenceable ||
1153         I == Attribute::DereferenceableOrNull ||
1154         I == Attribute::ArgMemOnly ||
1155         I == Attribute::AllocSize)
1156       continue;
1157     if (uint64_t A = (Val & getRawAttributeMask(I))) {
1158       if (I == Attribute::Alignment)
1159         B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1160       else if (I == Attribute::StackAlignment)
1161         B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1162       else
1163         B.addAttribute(I);
1164     }
1165   }
1166 }
1167 
1168 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1169 /// been decoded from the given integer. This function must stay in sync with
1170 /// 'encodeLLVMAttributesForBitcode'.
1171 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1172                                            uint64_t EncodedAttrs) {
1173   // FIXME: Remove in 4.0.
1174 
1175   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
1176   // the bits above 31 down by 11 bits.
1177   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1178   assert((!Alignment || isPowerOf2_32(Alignment)) &&
1179          "Alignment must be a power of two.");
1180 
1181   if (Alignment)
1182     B.addAlignmentAttr(Alignment);
1183   addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1184                           (EncodedAttrs & 0xffff));
1185 }
1186 
1187 Error BitcodeReader::parseAttributeBlock() {
1188   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1189     return error("Invalid record");
1190 
1191   if (!MAttributes.empty())
1192     return error("Invalid multiple blocks");
1193 
1194   SmallVector<uint64_t, 64> Record;
1195 
1196   SmallVector<AttributeList, 8> Attrs;
1197 
1198   // Read all the records.
1199   while (true) {
1200     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1201 
1202     switch (Entry.Kind) {
1203     case BitstreamEntry::SubBlock: // Handled for us already.
1204     case BitstreamEntry::Error:
1205       return error("Malformed block");
1206     case BitstreamEntry::EndBlock:
1207       return Error::success();
1208     case BitstreamEntry::Record:
1209       // The interesting case.
1210       break;
1211     }
1212 
1213     // Read a record.
1214     Record.clear();
1215     switch (Stream.readRecord(Entry.ID, Record)) {
1216     default:  // Default behavior: ignore.
1217       break;
1218     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1219       // FIXME: Remove in 4.0.
1220       if (Record.size() & 1)
1221         return error("Invalid record");
1222 
1223       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1224         AttrBuilder B;
1225         decodeLLVMAttributesForBitcode(B, Record[i+1]);
1226         Attrs.push_back(AttributeList::get(Context, Record[i], B));
1227       }
1228 
1229       MAttributes.push_back(AttributeList::get(Context, Attrs));
1230       Attrs.clear();
1231       break;
1232     }
1233     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1234       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1235         Attrs.push_back(MAttributeGroups[Record[i]]);
1236 
1237       MAttributes.push_back(AttributeList::get(Context, Attrs));
1238       Attrs.clear();
1239       break;
1240     }
1241     }
1242   }
1243 }
1244 
1245 // Returns Attribute::None on unrecognized codes.
1246 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1247   switch (Code) {
1248   default:
1249     return Attribute::None;
1250   case bitc::ATTR_KIND_ALIGNMENT:
1251     return Attribute::Alignment;
1252   case bitc::ATTR_KIND_ALWAYS_INLINE:
1253     return Attribute::AlwaysInline;
1254   case bitc::ATTR_KIND_ARGMEMONLY:
1255     return Attribute::ArgMemOnly;
1256   case bitc::ATTR_KIND_BUILTIN:
1257     return Attribute::Builtin;
1258   case bitc::ATTR_KIND_BY_VAL:
1259     return Attribute::ByVal;
1260   case bitc::ATTR_KIND_IN_ALLOCA:
1261     return Attribute::InAlloca;
1262   case bitc::ATTR_KIND_COLD:
1263     return Attribute::Cold;
1264   case bitc::ATTR_KIND_CONVERGENT:
1265     return Attribute::Convergent;
1266   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1267     return Attribute::InaccessibleMemOnly;
1268   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1269     return Attribute::InaccessibleMemOrArgMemOnly;
1270   case bitc::ATTR_KIND_INLINE_HINT:
1271     return Attribute::InlineHint;
1272   case bitc::ATTR_KIND_IN_REG:
1273     return Attribute::InReg;
1274   case bitc::ATTR_KIND_JUMP_TABLE:
1275     return Attribute::JumpTable;
1276   case bitc::ATTR_KIND_MIN_SIZE:
1277     return Attribute::MinSize;
1278   case bitc::ATTR_KIND_NAKED:
1279     return Attribute::Naked;
1280   case bitc::ATTR_KIND_NEST:
1281     return Attribute::Nest;
1282   case bitc::ATTR_KIND_NO_ALIAS:
1283     return Attribute::NoAlias;
1284   case bitc::ATTR_KIND_NO_BUILTIN:
1285     return Attribute::NoBuiltin;
1286   case bitc::ATTR_KIND_NO_CAPTURE:
1287     return Attribute::NoCapture;
1288   case bitc::ATTR_KIND_NO_DUPLICATE:
1289     return Attribute::NoDuplicate;
1290   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1291     return Attribute::NoImplicitFloat;
1292   case bitc::ATTR_KIND_NO_INLINE:
1293     return Attribute::NoInline;
1294   case bitc::ATTR_KIND_NO_RECURSE:
1295     return Attribute::NoRecurse;
1296   case bitc::ATTR_KIND_NON_LAZY_BIND:
1297     return Attribute::NonLazyBind;
1298   case bitc::ATTR_KIND_NON_NULL:
1299     return Attribute::NonNull;
1300   case bitc::ATTR_KIND_DEREFERENCEABLE:
1301     return Attribute::Dereferenceable;
1302   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1303     return Attribute::DereferenceableOrNull;
1304   case bitc::ATTR_KIND_ALLOC_SIZE:
1305     return Attribute::AllocSize;
1306   case bitc::ATTR_KIND_NO_RED_ZONE:
1307     return Attribute::NoRedZone;
1308   case bitc::ATTR_KIND_NO_RETURN:
1309     return Attribute::NoReturn;
1310   case bitc::ATTR_KIND_NO_UNWIND:
1311     return Attribute::NoUnwind;
1312   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1313     return Attribute::OptimizeForSize;
1314   case bitc::ATTR_KIND_OPTIMIZE_NONE:
1315     return Attribute::OptimizeNone;
1316   case bitc::ATTR_KIND_READ_NONE:
1317     return Attribute::ReadNone;
1318   case bitc::ATTR_KIND_READ_ONLY:
1319     return Attribute::ReadOnly;
1320   case bitc::ATTR_KIND_RETURNED:
1321     return Attribute::Returned;
1322   case bitc::ATTR_KIND_RETURNS_TWICE:
1323     return Attribute::ReturnsTwice;
1324   case bitc::ATTR_KIND_S_EXT:
1325     return Attribute::SExt;
1326   case bitc::ATTR_KIND_SPECULATABLE:
1327     return Attribute::Speculatable;
1328   case bitc::ATTR_KIND_STACK_ALIGNMENT:
1329     return Attribute::StackAlignment;
1330   case bitc::ATTR_KIND_STACK_PROTECT:
1331     return Attribute::StackProtect;
1332   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1333     return Attribute::StackProtectReq;
1334   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1335     return Attribute::StackProtectStrong;
1336   case bitc::ATTR_KIND_SAFESTACK:
1337     return Attribute::SafeStack;
1338   case bitc::ATTR_KIND_STRUCT_RET:
1339     return Attribute::StructRet;
1340   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1341     return Attribute::SanitizeAddress;
1342   case bitc::ATTR_KIND_SANITIZE_THREAD:
1343     return Attribute::SanitizeThread;
1344   case bitc::ATTR_KIND_SANITIZE_MEMORY:
1345     return Attribute::SanitizeMemory;
1346   case bitc::ATTR_KIND_SWIFT_ERROR:
1347     return Attribute::SwiftError;
1348   case bitc::ATTR_KIND_SWIFT_SELF:
1349     return Attribute::SwiftSelf;
1350   case bitc::ATTR_KIND_UW_TABLE:
1351     return Attribute::UWTable;
1352   case bitc::ATTR_KIND_WRITEONLY:
1353     return Attribute::WriteOnly;
1354   case bitc::ATTR_KIND_Z_EXT:
1355     return Attribute::ZExt;
1356   }
1357 }
1358 
1359 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1360                                          unsigned &Alignment) {
1361   // Note: Alignment in bitcode files is incremented by 1, so that zero
1362   // can be used for default alignment.
1363   if (Exponent > Value::MaxAlignmentExponent + 1)
1364     return error("Invalid alignment value");
1365   Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1366   return Error::success();
1367 }
1368 
1369 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
1370   *Kind = getAttrFromCode(Code);
1371   if (*Kind == Attribute::None)
1372     return error("Unknown attribute kind (" + Twine(Code) + ")");
1373   return Error::success();
1374 }
1375 
1376 Error BitcodeReader::parseAttributeGroupBlock() {
1377   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1378     return error("Invalid record");
1379 
1380   if (!MAttributeGroups.empty())
1381     return error("Invalid multiple blocks");
1382 
1383   SmallVector<uint64_t, 64> Record;
1384 
1385   // Read all the records.
1386   while (true) {
1387     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1388 
1389     switch (Entry.Kind) {
1390     case BitstreamEntry::SubBlock: // Handled for us already.
1391     case BitstreamEntry::Error:
1392       return error("Malformed block");
1393     case BitstreamEntry::EndBlock:
1394       return Error::success();
1395     case BitstreamEntry::Record:
1396       // The interesting case.
1397       break;
1398     }
1399 
1400     // Read a record.
1401     Record.clear();
1402     switch (Stream.readRecord(Entry.ID, Record)) {
1403     default:  // Default behavior: ignore.
1404       break;
1405     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1406       if (Record.size() < 3)
1407         return error("Invalid record");
1408 
1409       uint64_t GrpID = Record[0];
1410       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1411 
1412       AttrBuilder B;
1413       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1414         if (Record[i] == 0) {        // Enum attribute
1415           Attribute::AttrKind Kind;
1416           if (Error Err = parseAttrKind(Record[++i], &Kind))
1417             return Err;
1418 
1419           B.addAttribute(Kind);
1420         } else if (Record[i] == 1) { // Integer attribute
1421           Attribute::AttrKind Kind;
1422           if (Error Err = parseAttrKind(Record[++i], &Kind))
1423             return Err;
1424           if (Kind == Attribute::Alignment)
1425             B.addAlignmentAttr(Record[++i]);
1426           else if (Kind == Attribute::StackAlignment)
1427             B.addStackAlignmentAttr(Record[++i]);
1428           else if (Kind == Attribute::Dereferenceable)
1429             B.addDereferenceableAttr(Record[++i]);
1430           else if (Kind == Attribute::DereferenceableOrNull)
1431             B.addDereferenceableOrNullAttr(Record[++i]);
1432           else if (Kind == Attribute::AllocSize)
1433             B.addAllocSizeAttrFromRawRepr(Record[++i]);
1434         } else {                     // String attribute
1435           assert((Record[i] == 3 || Record[i] == 4) &&
1436                  "Invalid attribute group entry");
1437           bool HasValue = (Record[i++] == 4);
1438           SmallString<64> KindStr;
1439           SmallString<64> ValStr;
1440 
1441           while (Record[i] != 0 && i != e)
1442             KindStr += Record[i++];
1443           assert(Record[i] == 0 && "Kind string not null terminated");
1444 
1445           if (HasValue) {
1446             // Has a value associated with it.
1447             ++i; // Skip the '0' that terminates the "kind" string.
1448             while (Record[i] != 0 && i != e)
1449               ValStr += Record[i++];
1450             assert(Record[i] == 0 && "Value string not null terminated");
1451           }
1452 
1453           B.addAttribute(KindStr.str(), ValStr.str());
1454         }
1455       }
1456 
1457       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1458       break;
1459     }
1460     }
1461   }
1462 }
1463 
1464 Error BitcodeReader::parseTypeTable() {
1465   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1466     return error("Invalid record");
1467 
1468   return parseTypeTableBody();
1469 }
1470 
1471 Error BitcodeReader::parseTypeTableBody() {
1472   if (!TypeList.empty())
1473     return error("Invalid multiple blocks");
1474 
1475   SmallVector<uint64_t, 64> Record;
1476   unsigned NumRecords = 0;
1477 
1478   SmallString<64> TypeName;
1479 
1480   // Read all the records for this type table.
1481   while (true) {
1482     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1483 
1484     switch (Entry.Kind) {
1485     case BitstreamEntry::SubBlock: // Handled for us already.
1486     case BitstreamEntry::Error:
1487       return error("Malformed block");
1488     case BitstreamEntry::EndBlock:
1489       if (NumRecords != TypeList.size())
1490         return error("Malformed block");
1491       return Error::success();
1492     case BitstreamEntry::Record:
1493       // The interesting case.
1494       break;
1495     }
1496 
1497     // Read a record.
1498     Record.clear();
1499     Type *ResultTy = nullptr;
1500     switch (Stream.readRecord(Entry.ID, Record)) {
1501     default:
1502       return error("Invalid value");
1503     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1504       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1505       // type list.  This allows us to reserve space.
1506       if (Record.size() < 1)
1507         return error("Invalid record");
1508       TypeList.resize(Record[0]);
1509       continue;
1510     case bitc::TYPE_CODE_VOID:      // VOID
1511       ResultTy = Type::getVoidTy(Context);
1512       break;
1513     case bitc::TYPE_CODE_HALF:     // HALF
1514       ResultTy = Type::getHalfTy(Context);
1515       break;
1516     case bitc::TYPE_CODE_FLOAT:     // FLOAT
1517       ResultTy = Type::getFloatTy(Context);
1518       break;
1519     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1520       ResultTy = Type::getDoubleTy(Context);
1521       break;
1522     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1523       ResultTy = Type::getX86_FP80Ty(Context);
1524       break;
1525     case bitc::TYPE_CODE_FP128:     // FP128
1526       ResultTy = Type::getFP128Ty(Context);
1527       break;
1528     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1529       ResultTy = Type::getPPC_FP128Ty(Context);
1530       break;
1531     case bitc::TYPE_CODE_LABEL:     // LABEL
1532       ResultTy = Type::getLabelTy(Context);
1533       break;
1534     case bitc::TYPE_CODE_METADATA:  // METADATA
1535       ResultTy = Type::getMetadataTy(Context);
1536       break;
1537     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
1538       ResultTy = Type::getX86_MMXTy(Context);
1539       break;
1540     case bitc::TYPE_CODE_TOKEN:     // TOKEN
1541       ResultTy = Type::getTokenTy(Context);
1542       break;
1543     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1544       if (Record.size() < 1)
1545         return error("Invalid record");
1546 
1547       uint64_t NumBits = Record[0];
1548       if (NumBits < IntegerType::MIN_INT_BITS ||
1549           NumBits > IntegerType::MAX_INT_BITS)
1550         return error("Bitwidth for integer type out of range");
1551       ResultTy = IntegerType::get(Context, NumBits);
1552       break;
1553     }
1554     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1555                                     //          [pointee type, address space]
1556       if (Record.size() < 1)
1557         return error("Invalid record");
1558       unsigned AddressSpace = 0;
1559       if (Record.size() == 2)
1560         AddressSpace = Record[1];
1561       ResultTy = getTypeByID(Record[0]);
1562       if (!ResultTy ||
1563           !PointerType::isValidElementType(ResultTy))
1564         return error("Invalid type");
1565       ResultTy = PointerType::get(ResultTy, AddressSpace);
1566       break;
1567     }
1568     case bitc::TYPE_CODE_FUNCTION_OLD: {
1569       // FIXME: attrid is dead, remove it in LLVM 4.0
1570       // FUNCTION: [vararg, attrid, retty, paramty x N]
1571       if (Record.size() < 3)
1572         return error("Invalid record");
1573       SmallVector<Type*, 8> ArgTys;
1574       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1575         if (Type *T = getTypeByID(Record[i]))
1576           ArgTys.push_back(T);
1577         else
1578           break;
1579       }
1580 
1581       ResultTy = getTypeByID(Record[2]);
1582       if (!ResultTy || ArgTys.size() < Record.size()-3)
1583         return error("Invalid type");
1584 
1585       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1586       break;
1587     }
1588     case bitc::TYPE_CODE_FUNCTION: {
1589       // FUNCTION: [vararg, retty, paramty x N]
1590       if (Record.size() < 2)
1591         return error("Invalid record");
1592       SmallVector<Type*, 8> ArgTys;
1593       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1594         if (Type *T = getTypeByID(Record[i])) {
1595           if (!FunctionType::isValidArgumentType(T))
1596             return error("Invalid function argument type");
1597           ArgTys.push_back(T);
1598         }
1599         else
1600           break;
1601       }
1602 
1603       ResultTy = getTypeByID(Record[1]);
1604       if (!ResultTy || ArgTys.size() < Record.size()-2)
1605         return error("Invalid type");
1606 
1607       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1608       break;
1609     }
1610     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1611       if (Record.size() < 1)
1612         return error("Invalid record");
1613       SmallVector<Type*, 8> EltTys;
1614       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1615         if (Type *T = getTypeByID(Record[i]))
1616           EltTys.push_back(T);
1617         else
1618           break;
1619       }
1620       if (EltTys.size() != Record.size()-1)
1621         return error("Invalid type");
1622       ResultTy = StructType::get(Context, EltTys, Record[0]);
1623       break;
1624     }
1625     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1626       if (convertToString(Record, 0, TypeName))
1627         return error("Invalid record");
1628       continue;
1629 
1630     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1631       if (Record.size() < 1)
1632         return error("Invalid record");
1633 
1634       if (NumRecords >= TypeList.size())
1635         return error("Invalid TYPE table");
1636 
1637       // Check to see if this was forward referenced, if so fill in the temp.
1638       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1639       if (Res) {
1640         Res->setName(TypeName);
1641         TypeList[NumRecords] = nullptr;
1642       } else  // Otherwise, create a new struct.
1643         Res = createIdentifiedStructType(Context, TypeName);
1644       TypeName.clear();
1645 
1646       SmallVector<Type*, 8> EltTys;
1647       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1648         if (Type *T = getTypeByID(Record[i]))
1649           EltTys.push_back(T);
1650         else
1651           break;
1652       }
1653       if (EltTys.size() != Record.size()-1)
1654         return error("Invalid record");
1655       Res->setBody(EltTys, Record[0]);
1656       ResultTy = Res;
1657       break;
1658     }
1659     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1660       if (Record.size() != 1)
1661         return error("Invalid record");
1662 
1663       if (NumRecords >= TypeList.size())
1664         return error("Invalid TYPE table");
1665 
1666       // Check to see if this was forward referenced, if so fill in the temp.
1667       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1668       if (Res) {
1669         Res->setName(TypeName);
1670         TypeList[NumRecords] = nullptr;
1671       } else  // Otherwise, create a new struct with no body.
1672         Res = createIdentifiedStructType(Context, TypeName);
1673       TypeName.clear();
1674       ResultTy = Res;
1675       break;
1676     }
1677     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1678       if (Record.size() < 2)
1679         return error("Invalid record");
1680       ResultTy = getTypeByID(Record[1]);
1681       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1682         return error("Invalid type");
1683       ResultTy = ArrayType::get(ResultTy, Record[0]);
1684       break;
1685     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
1686       if (Record.size() < 2)
1687         return error("Invalid record");
1688       if (Record[0] == 0)
1689         return error("Invalid vector length");
1690       ResultTy = getTypeByID(Record[1]);
1691       if (!ResultTy || !StructType::isValidElementType(ResultTy))
1692         return error("Invalid type");
1693       ResultTy = VectorType::get(ResultTy, Record[0]);
1694       break;
1695     }
1696 
1697     if (NumRecords >= TypeList.size())
1698       return error("Invalid TYPE table");
1699     if (TypeList[NumRecords])
1700       return error(
1701           "Invalid TYPE table: Only named structs can be forward referenced");
1702     assert(ResultTy && "Didn't read a type?");
1703     TypeList[NumRecords++] = ResultTy;
1704   }
1705 }
1706 
1707 Error BitcodeReader::parseOperandBundleTags() {
1708   if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1709     return error("Invalid record");
1710 
1711   if (!BundleTags.empty())
1712     return error("Invalid multiple blocks");
1713 
1714   SmallVector<uint64_t, 64> Record;
1715 
1716   while (true) {
1717     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
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       return Error::success();
1725     case BitstreamEntry::Record:
1726       // The interesting case.
1727       break;
1728     }
1729 
1730     // Tags are implicitly mapped to integers by their order.
1731 
1732     if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1733       return error("Invalid record");
1734 
1735     // OPERAND_BUNDLE_TAG: [strchr x N]
1736     BundleTags.emplace_back();
1737     if (convertToString(Record, 0, BundleTags.back()))
1738       return error("Invalid record");
1739     Record.clear();
1740   }
1741 }
1742 
1743 /// Associate a value with its name from the given index in the provided record.
1744 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1745                                              unsigned NameIndex, Triple &TT) {
1746   SmallString<128> ValueName;
1747   if (convertToString(Record, NameIndex, ValueName))
1748     return error("Invalid record");
1749   unsigned ValueID = Record[0];
1750   if (ValueID >= ValueList.size() || !ValueList[ValueID])
1751     return error("Invalid record");
1752   Value *V = ValueList[ValueID];
1753 
1754   StringRef NameStr(ValueName.data(), ValueName.size());
1755   if (NameStr.find_first_of(0) != StringRef::npos)
1756     return error("Invalid value name");
1757   V->setName(NameStr);
1758   auto *GO = dyn_cast<GlobalObject>(V);
1759   if (GO) {
1760     if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1761       if (TT.isOSBinFormatMachO())
1762         GO->setComdat(nullptr);
1763       else
1764         GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1765     }
1766   }
1767   return V;
1768 }
1769 
1770 /// Helper to note and return the current location, and jump to the given
1771 /// offset.
1772 static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1773                                        BitstreamCursor &Stream) {
1774   // Save the current parsing location so we can jump back at the end
1775   // of the VST read.
1776   uint64_t CurrentBit = Stream.GetCurrentBitNo();
1777   Stream.JumpToBit(Offset * 32);
1778 #ifndef NDEBUG
1779   // Do some checking if we are in debug mode.
1780   BitstreamEntry Entry = Stream.advance();
1781   assert(Entry.Kind == BitstreamEntry::SubBlock);
1782   assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1783 #else
1784   // In NDEBUG mode ignore the output so we don't get an unused variable
1785   // warning.
1786   Stream.advance();
1787 #endif
1788   return CurrentBit;
1789 }
1790 
1791 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1792                                             Function *F,
1793                                             ArrayRef<uint64_t> Record) {
1794   // Note that we subtract 1 here because the offset is relative to one word
1795   // before the start of the identification or module block, which was
1796   // historically always the start of the regular bitcode header.
1797   uint64_t FuncWordOffset = Record[1] - 1;
1798   uint64_t FuncBitOffset = FuncWordOffset * 32;
1799   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1800   // Set the LastFunctionBlockBit to point to the last function block.
1801   // Later when parsing is resumed after function materialization,
1802   // we can simply skip that last function block.
1803   if (FuncBitOffset > LastFunctionBlockBit)
1804     LastFunctionBlockBit = FuncBitOffset;
1805 }
1806 
1807 /// Read a new-style GlobalValue symbol table.
1808 Error BitcodeReader::parseGlobalValueSymbolTable() {
1809   unsigned FuncBitcodeOffsetDelta =
1810       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1811 
1812   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1813     return error("Invalid record");
1814 
1815   SmallVector<uint64_t, 64> Record;
1816   while (true) {
1817     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1818 
1819     switch (Entry.Kind) {
1820     case BitstreamEntry::SubBlock:
1821     case BitstreamEntry::Error:
1822       return error("Malformed block");
1823     case BitstreamEntry::EndBlock:
1824       return Error::success();
1825     case BitstreamEntry::Record:
1826       break;
1827     }
1828 
1829     Record.clear();
1830     switch (Stream.readRecord(Entry.ID, Record)) {
1831     case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1832       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1833                               cast<Function>(ValueList[Record[0]]), Record);
1834       break;
1835     }
1836   }
1837 }
1838 
1839 /// Parse the value symbol table at either the current parsing location or
1840 /// at the given bit offset if provided.
1841 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1842   uint64_t CurrentBit;
1843   // Pass in the Offset to distinguish between calling for the module-level
1844   // VST (where we want to jump to the VST offset) and the function-level
1845   // VST (where we don't).
1846   if (Offset > 0) {
1847     CurrentBit = jumpToValueSymbolTable(Offset, Stream);
1848     // If this module uses a string table, read this as a module-level VST.
1849     if (UseStrtab) {
1850       if (Error Err = parseGlobalValueSymbolTable())
1851         return Err;
1852       Stream.JumpToBit(CurrentBit);
1853       return Error::success();
1854     }
1855     // Otherwise, the VST will be in a similar format to a function-level VST,
1856     // and will contain symbol names.
1857   }
1858 
1859   // Compute the delta between the bitcode indices in the VST (the word offset
1860   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1861   // expected by the lazy reader. The reader's EnterSubBlock expects to have
1862   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1863   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1864   // just before entering the VST subblock because: 1) the EnterSubBlock
1865   // changes the AbbrevID width; 2) the VST block is nested within the same
1866   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1867   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1868   // jump to the FUNCTION_BLOCK using this offset later, we don't want
1869   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1870   unsigned FuncBitcodeOffsetDelta =
1871       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1872 
1873   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1874     return error("Invalid record");
1875 
1876   SmallVector<uint64_t, 64> Record;
1877 
1878   Triple TT(TheModule->getTargetTriple());
1879 
1880   // Read all the records for this value table.
1881   SmallString<128> ValueName;
1882 
1883   while (true) {
1884     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1885 
1886     switch (Entry.Kind) {
1887     case BitstreamEntry::SubBlock: // Handled for us already.
1888     case BitstreamEntry::Error:
1889       return error("Malformed block");
1890     case BitstreamEntry::EndBlock:
1891       if (Offset > 0)
1892         Stream.JumpToBit(CurrentBit);
1893       return Error::success();
1894     case BitstreamEntry::Record:
1895       // The interesting case.
1896       break;
1897     }
1898 
1899     // Read a record.
1900     Record.clear();
1901     switch (Stream.readRecord(Entry.ID, Record)) {
1902     default:  // Default behavior: unknown type.
1903       break;
1904     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
1905       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1906       if (Error Err = ValOrErr.takeError())
1907         return Err;
1908       ValOrErr.get();
1909       break;
1910     }
1911     case bitc::VST_CODE_FNENTRY: {
1912       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
1913       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1914       if (Error Err = ValOrErr.takeError())
1915         return Err;
1916       Value *V = ValOrErr.get();
1917 
1918       // Ignore function offsets emitted for aliases of functions in older
1919       // versions of LLVM.
1920       if (auto *F = dyn_cast<Function>(V))
1921         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
1922       break;
1923     }
1924     case bitc::VST_CODE_BBENTRY: {
1925       if (convertToString(Record, 1, ValueName))
1926         return error("Invalid record");
1927       BasicBlock *BB = getBasicBlock(Record[0]);
1928       if (!BB)
1929         return error("Invalid record");
1930 
1931       BB->setName(StringRef(ValueName.data(), ValueName.size()));
1932       ValueName.clear();
1933       break;
1934     }
1935     }
1936   }
1937 }
1938 
1939 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
1940 /// encoding.
1941 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1942   if ((V & 1) == 0)
1943     return V >> 1;
1944   if (V != 1)
1945     return -(V >> 1);
1946   // There is no such thing as -0 with integers.  "-0" really means MININT.
1947   return 1ULL << 63;
1948 }
1949 
1950 /// Resolve all of the initializers for global values and aliases that we can.
1951 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
1952   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1953   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
1954       IndirectSymbolInitWorklist;
1955   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1956   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1957   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
1958 
1959   GlobalInitWorklist.swap(GlobalInits);
1960   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
1961   FunctionPrefixWorklist.swap(FunctionPrefixes);
1962   FunctionPrologueWorklist.swap(FunctionPrologues);
1963   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
1964 
1965   while (!GlobalInitWorklist.empty()) {
1966     unsigned ValID = GlobalInitWorklist.back().second;
1967     if (ValID >= ValueList.size()) {
1968       // Not ready to resolve this yet, it requires something later in the file.
1969       GlobalInits.push_back(GlobalInitWorklist.back());
1970     } else {
1971       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1972         GlobalInitWorklist.back().first->setInitializer(C);
1973       else
1974         return error("Expected a constant");
1975     }
1976     GlobalInitWorklist.pop_back();
1977   }
1978 
1979   while (!IndirectSymbolInitWorklist.empty()) {
1980     unsigned ValID = IndirectSymbolInitWorklist.back().second;
1981     if (ValID >= ValueList.size()) {
1982       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
1983     } else {
1984       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
1985       if (!C)
1986         return error("Expected a constant");
1987       GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
1988       if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
1989         return error("Alias and aliasee types don't match");
1990       GIS->setIndirectSymbol(C);
1991     }
1992     IndirectSymbolInitWorklist.pop_back();
1993   }
1994 
1995   while (!FunctionPrefixWorklist.empty()) {
1996     unsigned ValID = FunctionPrefixWorklist.back().second;
1997     if (ValID >= ValueList.size()) {
1998       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1999     } else {
2000       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2001         FunctionPrefixWorklist.back().first->setPrefixData(C);
2002       else
2003         return error("Expected a constant");
2004     }
2005     FunctionPrefixWorklist.pop_back();
2006   }
2007 
2008   while (!FunctionPrologueWorklist.empty()) {
2009     unsigned ValID = FunctionPrologueWorklist.back().second;
2010     if (ValID >= ValueList.size()) {
2011       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2012     } else {
2013       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2014         FunctionPrologueWorklist.back().first->setPrologueData(C);
2015       else
2016         return error("Expected a constant");
2017     }
2018     FunctionPrologueWorklist.pop_back();
2019   }
2020 
2021   while (!FunctionPersonalityFnWorklist.empty()) {
2022     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2023     if (ValID >= ValueList.size()) {
2024       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2025     } else {
2026       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2027         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2028       else
2029         return error("Expected a constant");
2030     }
2031     FunctionPersonalityFnWorklist.pop_back();
2032   }
2033 
2034   return Error::success();
2035 }
2036 
2037 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2038   SmallVector<uint64_t, 8> Words(Vals.size());
2039   transform(Vals, Words.begin(),
2040                  BitcodeReader::decodeSignRotatedValue);
2041 
2042   return APInt(TypeBits, Words);
2043 }
2044 
2045 Error BitcodeReader::parseConstants() {
2046   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2047     return error("Invalid record");
2048 
2049   SmallVector<uint64_t, 64> Record;
2050 
2051   // Read all the records for this value table.
2052   Type *CurTy = Type::getInt32Ty(Context);
2053   unsigned NextCstNo = ValueList.size();
2054 
2055   while (true) {
2056     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2057 
2058     switch (Entry.Kind) {
2059     case BitstreamEntry::SubBlock: // Handled for us already.
2060     case BitstreamEntry::Error:
2061       return error("Malformed block");
2062     case BitstreamEntry::EndBlock:
2063       if (NextCstNo != ValueList.size())
2064         return error("Invalid constant reference");
2065 
2066       // Once all the constants have been read, go through and resolve forward
2067       // references.
2068       ValueList.resolveConstantForwardRefs();
2069       return Error::success();
2070     case BitstreamEntry::Record:
2071       // The interesting case.
2072       break;
2073     }
2074 
2075     // Read a record.
2076     Record.clear();
2077     Type *VoidType = Type::getVoidTy(Context);
2078     Value *V = nullptr;
2079     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2080     switch (BitCode) {
2081     default:  // Default behavior: unknown constant
2082     case bitc::CST_CODE_UNDEF:     // UNDEF
2083       V = UndefValue::get(CurTy);
2084       break;
2085     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2086       if (Record.empty())
2087         return error("Invalid record");
2088       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2089         return error("Invalid record");
2090       if (TypeList[Record[0]] == VoidType)
2091         return error("Invalid constant type");
2092       CurTy = TypeList[Record[0]];
2093       continue;  // Skip the ValueList manipulation.
2094     case bitc::CST_CODE_NULL:      // NULL
2095       V = Constant::getNullValue(CurTy);
2096       break;
2097     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2098       if (!CurTy->isIntegerTy() || Record.empty())
2099         return error("Invalid record");
2100       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2101       break;
2102     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2103       if (!CurTy->isIntegerTy() || Record.empty())
2104         return error("Invalid record");
2105 
2106       APInt VInt =
2107           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2108       V = ConstantInt::get(Context, VInt);
2109 
2110       break;
2111     }
2112     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2113       if (Record.empty())
2114         return error("Invalid record");
2115       if (CurTy->isHalfTy())
2116         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2117                                              APInt(16, (uint16_t)Record[0])));
2118       else if (CurTy->isFloatTy())
2119         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2120                                              APInt(32, (uint32_t)Record[0])));
2121       else if (CurTy->isDoubleTy())
2122         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2123                                              APInt(64, Record[0])));
2124       else if (CurTy->isX86_FP80Ty()) {
2125         // Bits are not stored the same way as a normal i80 APInt, compensate.
2126         uint64_t Rearrange[2];
2127         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2128         Rearrange[1] = Record[0] >> 48;
2129         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2130                                              APInt(80, Rearrange)));
2131       } else if (CurTy->isFP128Ty())
2132         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2133                                              APInt(128, Record)));
2134       else if (CurTy->isPPC_FP128Ty())
2135         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2136                                              APInt(128, Record)));
2137       else
2138         V = UndefValue::get(CurTy);
2139       break;
2140     }
2141 
2142     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2143       if (Record.empty())
2144         return error("Invalid record");
2145 
2146       unsigned Size = Record.size();
2147       SmallVector<Constant*, 16> Elts;
2148 
2149       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2150         for (unsigned i = 0; i != Size; ++i)
2151           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2152                                                      STy->getElementType(i)));
2153         V = ConstantStruct::get(STy, Elts);
2154       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2155         Type *EltTy = ATy->getElementType();
2156         for (unsigned i = 0; i != Size; ++i)
2157           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2158         V = ConstantArray::get(ATy, Elts);
2159       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2160         Type *EltTy = VTy->getElementType();
2161         for (unsigned i = 0; i != Size; ++i)
2162           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2163         V = ConstantVector::get(Elts);
2164       } else {
2165         V = UndefValue::get(CurTy);
2166       }
2167       break;
2168     }
2169     case bitc::CST_CODE_STRING:    // STRING: [values]
2170     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2171       if (Record.empty())
2172         return error("Invalid record");
2173 
2174       SmallString<16> Elts(Record.begin(), Record.end());
2175       V = ConstantDataArray::getString(Context, Elts,
2176                                        BitCode == bitc::CST_CODE_CSTRING);
2177       break;
2178     }
2179     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2180       if (Record.empty())
2181         return error("Invalid record");
2182 
2183       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2184       if (EltTy->isIntegerTy(8)) {
2185         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2186         if (isa<VectorType>(CurTy))
2187           V = ConstantDataVector::get(Context, Elts);
2188         else
2189           V = ConstantDataArray::get(Context, Elts);
2190       } else if (EltTy->isIntegerTy(16)) {
2191         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2192         if (isa<VectorType>(CurTy))
2193           V = ConstantDataVector::get(Context, Elts);
2194         else
2195           V = ConstantDataArray::get(Context, Elts);
2196       } else if (EltTy->isIntegerTy(32)) {
2197         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2198         if (isa<VectorType>(CurTy))
2199           V = ConstantDataVector::get(Context, Elts);
2200         else
2201           V = ConstantDataArray::get(Context, Elts);
2202       } else if (EltTy->isIntegerTy(64)) {
2203         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2204         if (isa<VectorType>(CurTy))
2205           V = ConstantDataVector::get(Context, Elts);
2206         else
2207           V = ConstantDataArray::get(Context, Elts);
2208       } else if (EltTy->isHalfTy()) {
2209         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2210         if (isa<VectorType>(CurTy))
2211           V = ConstantDataVector::getFP(Context, Elts);
2212         else
2213           V = ConstantDataArray::getFP(Context, Elts);
2214       } else if (EltTy->isFloatTy()) {
2215         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2216         if (isa<VectorType>(CurTy))
2217           V = ConstantDataVector::getFP(Context, Elts);
2218         else
2219           V = ConstantDataArray::getFP(Context, Elts);
2220       } else if (EltTy->isDoubleTy()) {
2221         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2222         if (isa<VectorType>(CurTy))
2223           V = ConstantDataVector::getFP(Context, Elts);
2224         else
2225           V = ConstantDataArray::getFP(Context, Elts);
2226       } else {
2227         return error("Invalid type for value");
2228       }
2229       break;
2230     }
2231     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2232       if (Record.size() < 3)
2233         return error("Invalid record");
2234       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2235       if (Opc < 0) {
2236         V = UndefValue::get(CurTy);  // Unknown binop.
2237       } else {
2238         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2239         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2240         unsigned Flags = 0;
2241         if (Record.size() >= 4) {
2242           if (Opc == Instruction::Add ||
2243               Opc == Instruction::Sub ||
2244               Opc == Instruction::Mul ||
2245               Opc == Instruction::Shl) {
2246             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2247               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2248             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2249               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2250           } else if (Opc == Instruction::SDiv ||
2251                      Opc == Instruction::UDiv ||
2252                      Opc == Instruction::LShr ||
2253                      Opc == Instruction::AShr) {
2254             if (Record[3] & (1 << bitc::PEO_EXACT))
2255               Flags |= SDivOperator::IsExact;
2256           }
2257         }
2258         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2259       }
2260       break;
2261     }
2262     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2263       if (Record.size() < 3)
2264         return error("Invalid record");
2265       int Opc = getDecodedCastOpcode(Record[0]);
2266       if (Opc < 0) {
2267         V = UndefValue::get(CurTy);  // Unknown cast.
2268       } else {
2269         Type *OpTy = getTypeByID(Record[1]);
2270         if (!OpTy)
2271           return error("Invalid record");
2272         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2273         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2274         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2275       }
2276       break;
2277     }
2278     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2279     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2280     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2281                                                      // operands]
2282       unsigned OpNum = 0;
2283       Type *PointeeType = nullptr;
2284       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2285           Record.size() % 2)
2286         PointeeType = getTypeByID(Record[OpNum++]);
2287 
2288       bool InBounds = false;
2289       Optional<unsigned> InRangeIndex;
2290       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2291         uint64_t Op = Record[OpNum++];
2292         InBounds = Op & 1;
2293         InRangeIndex = Op >> 1;
2294       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2295         InBounds = true;
2296 
2297       SmallVector<Constant*, 16> Elts;
2298       while (OpNum != Record.size()) {
2299         Type *ElTy = getTypeByID(Record[OpNum++]);
2300         if (!ElTy)
2301           return error("Invalid record");
2302         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2303       }
2304 
2305       if (PointeeType &&
2306           PointeeType !=
2307               cast<PointerType>(Elts[0]->getType()->getScalarType())
2308                   ->getElementType())
2309         return error("Explicit gep operator type does not match pointee type "
2310                      "of pointer operand");
2311 
2312       if (Elts.size() < 1)
2313         return error("Invalid gep with no operands");
2314 
2315       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2316       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2317                                          InBounds, InRangeIndex);
2318       break;
2319     }
2320     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2321       if (Record.size() < 3)
2322         return error("Invalid record");
2323 
2324       Type *SelectorTy = Type::getInt1Ty(Context);
2325 
2326       // The selector might be an i1 or an <n x i1>
2327       // Get the type from the ValueList before getting a forward ref.
2328       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2329         if (Value *V = ValueList[Record[0]])
2330           if (SelectorTy != V->getType())
2331             SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2332 
2333       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2334                                                               SelectorTy),
2335                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2336                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2337       break;
2338     }
2339     case bitc::CST_CODE_CE_EXTRACTELT
2340         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2341       if (Record.size() < 3)
2342         return error("Invalid record");
2343       VectorType *OpTy =
2344         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2345       if (!OpTy)
2346         return error("Invalid record");
2347       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2348       Constant *Op1 = nullptr;
2349       if (Record.size() == 4) {
2350         Type *IdxTy = getTypeByID(Record[2]);
2351         if (!IdxTy)
2352           return error("Invalid record");
2353         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2354       } else // TODO: Remove with llvm 4.0
2355         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2356       if (!Op1)
2357         return error("Invalid record");
2358       V = ConstantExpr::getExtractElement(Op0, Op1);
2359       break;
2360     }
2361     case bitc::CST_CODE_CE_INSERTELT
2362         : { // CE_INSERTELT: [opval, opval, opty, opval]
2363       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2364       if (Record.size() < 3 || !OpTy)
2365         return error("Invalid record");
2366       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2367       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2368                                                   OpTy->getElementType());
2369       Constant *Op2 = nullptr;
2370       if (Record.size() == 4) {
2371         Type *IdxTy = getTypeByID(Record[2]);
2372         if (!IdxTy)
2373           return error("Invalid record");
2374         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2375       } else // TODO: Remove with llvm 4.0
2376         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2377       if (!Op2)
2378         return error("Invalid record");
2379       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2380       break;
2381     }
2382     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2383       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2384       if (Record.size() < 3 || !OpTy)
2385         return error("Invalid record");
2386       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2387       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2388       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2389                                                  OpTy->getNumElements());
2390       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2391       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2392       break;
2393     }
2394     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2395       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2396       VectorType *OpTy =
2397         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2398       if (Record.size() < 4 || !RTy || !OpTy)
2399         return error("Invalid record");
2400       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2401       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2402       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2403                                                  RTy->getNumElements());
2404       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2405       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2406       break;
2407     }
2408     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2409       if (Record.size() < 4)
2410         return error("Invalid record");
2411       Type *OpTy = getTypeByID(Record[0]);
2412       if (!OpTy)
2413         return error("Invalid record");
2414       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2415       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2416 
2417       if (OpTy->isFPOrFPVectorTy())
2418         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2419       else
2420         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2421       break;
2422     }
2423     // This maintains backward compatibility, pre-asm dialect keywords.
2424     // FIXME: Remove with the 4.0 release.
2425     case bitc::CST_CODE_INLINEASM_OLD: {
2426       if (Record.size() < 2)
2427         return error("Invalid record");
2428       std::string AsmStr, ConstrStr;
2429       bool HasSideEffects = Record[0] & 1;
2430       bool IsAlignStack = Record[0] >> 1;
2431       unsigned AsmStrSize = Record[1];
2432       if (2+AsmStrSize >= Record.size())
2433         return error("Invalid record");
2434       unsigned ConstStrSize = Record[2+AsmStrSize];
2435       if (3+AsmStrSize+ConstStrSize > Record.size())
2436         return error("Invalid record");
2437 
2438       for (unsigned i = 0; i != AsmStrSize; ++i)
2439         AsmStr += (char)Record[2+i];
2440       for (unsigned i = 0; i != ConstStrSize; ++i)
2441         ConstrStr += (char)Record[3+AsmStrSize+i];
2442       PointerType *PTy = cast<PointerType>(CurTy);
2443       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2444                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2445       break;
2446     }
2447     // This version adds support for the asm dialect keywords (e.g.,
2448     // inteldialect).
2449     case bitc::CST_CODE_INLINEASM: {
2450       if (Record.size() < 2)
2451         return error("Invalid record");
2452       std::string AsmStr, ConstrStr;
2453       bool HasSideEffects = Record[0] & 1;
2454       bool IsAlignStack = (Record[0] >> 1) & 1;
2455       unsigned AsmDialect = Record[0] >> 2;
2456       unsigned AsmStrSize = Record[1];
2457       if (2+AsmStrSize >= Record.size())
2458         return error("Invalid record");
2459       unsigned ConstStrSize = Record[2+AsmStrSize];
2460       if (3+AsmStrSize+ConstStrSize > Record.size())
2461         return error("Invalid record");
2462 
2463       for (unsigned i = 0; i != AsmStrSize; ++i)
2464         AsmStr += (char)Record[2+i];
2465       for (unsigned i = 0; i != ConstStrSize; ++i)
2466         ConstrStr += (char)Record[3+AsmStrSize+i];
2467       PointerType *PTy = cast<PointerType>(CurTy);
2468       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2469                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2470                          InlineAsm::AsmDialect(AsmDialect));
2471       break;
2472     }
2473     case bitc::CST_CODE_BLOCKADDRESS:{
2474       if (Record.size() < 3)
2475         return error("Invalid record");
2476       Type *FnTy = getTypeByID(Record[0]);
2477       if (!FnTy)
2478         return error("Invalid record");
2479       Function *Fn =
2480         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2481       if (!Fn)
2482         return error("Invalid record");
2483 
2484       // If the function is already parsed we can insert the block address right
2485       // away.
2486       BasicBlock *BB;
2487       unsigned BBID = Record[2];
2488       if (!BBID)
2489         // Invalid reference to entry block.
2490         return error("Invalid ID");
2491       if (!Fn->empty()) {
2492         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2493         for (size_t I = 0, E = BBID; I != E; ++I) {
2494           if (BBI == BBE)
2495             return error("Invalid ID");
2496           ++BBI;
2497         }
2498         BB = &*BBI;
2499       } else {
2500         // Otherwise insert a placeholder and remember it so it can be inserted
2501         // when the function is parsed.
2502         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2503         if (FwdBBs.empty())
2504           BasicBlockFwdRefQueue.push_back(Fn);
2505         if (FwdBBs.size() < BBID + 1)
2506           FwdBBs.resize(BBID + 1);
2507         if (!FwdBBs[BBID])
2508           FwdBBs[BBID] = BasicBlock::Create(Context);
2509         BB = FwdBBs[BBID];
2510       }
2511       V = BlockAddress::get(Fn, BB);
2512       break;
2513     }
2514     }
2515 
2516     ValueList.assignValue(V, NextCstNo);
2517     ++NextCstNo;
2518   }
2519 }
2520 
2521 Error BitcodeReader::parseUseLists() {
2522   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2523     return error("Invalid record");
2524 
2525   // Read all the records.
2526   SmallVector<uint64_t, 64> Record;
2527 
2528   while (true) {
2529     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2530 
2531     switch (Entry.Kind) {
2532     case BitstreamEntry::SubBlock: // Handled for us already.
2533     case BitstreamEntry::Error:
2534       return error("Malformed block");
2535     case BitstreamEntry::EndBlock:
2536       return Error::success();
2537     case BitstreamEntry::Record:
2538       // The interesting case.
2539       break;
2540     }
2541 
2542     // Read a use list record.
2543     Record.clear();
2544     bool IsBB = false;
2545     switch (Stream.readRecord(Entry.ID, Record)) {
2546     default:  // Default behavior: unknown type.
2547       break;
2548     case bitc::USELIST_CODE_BB:
2549       IsBB = true;
2550       LLVM_FALLTHROUGH;
2551     case bitc::USELIST_CODE_DEFAULT: {
2552       unsigned RecordLength = Record.size();
2553       if (RecordLength < 3)
2554         // Records should have at least an ID and two indexes.
2555         return error("Invalid record");
2556       unsigned ID = Record.back();
2557       Record.pop_back();
2558 
2559       Value *V;
2560       if (IsBB) {
2561         assert(ID < FunctionBBs.size() && "Basic block not found");
2562         V = FunctionBBs[ID];
2563       } else
2564         V = ValueList[ID];
2565       unsigned NumUses = 0;
2566       SmallDenseMap<const Use *, unsigned, 16> Order;
2567       for (const Use &U : V->materialized_uses()) {
2568         if (++NumUses > Record.size())
2569           break;
2570         Order[&U] = Record[NumUses - 1];
2571       }
2572       if (Order.size() != Record.size() || NumUses > Record.size())
2573         // Mismatches can happen if the functions are being materialized lazily
2574         // (out-of-order), or a value has been upgraded.
2575         break;
2576 
2577       V->sortUseList([&](const Use &L, const Use &R) {
2578         return Order.lookup(&L) < Order.lookup(&R);
2579       });
2580       break;
2581     }
2582     }
2583   }
2584 }
2585 
2586 /// When we see the block for metadata, remember where it is and then skip it.
2587 /// This lets us lazily deserialize the metadata.
2588 Error BitcodeReader::rememberAndSkipMetadata() {
2589   // Save the current stream state.
2590   uint64_t CurBit = Stream.GetCurrentBitNo();
2591   DeferredMetadataInfo.push_back(CurBit);
2592 
2593   // Skip over the block for now.
2594   if (Stream.SkipBlock())
2595     return error("Invalid record");
2596   return Error::success();
2597 }
2598 
2599 Error BitcodeReader::materializeMetadata() {
2600   for (uint64_t BitPos : DeferredMetadataInfo) {
2601     // Move the bit stream to the saved position.
2602     Stream.JumpToBit(BitPos);
2603     if (Error Err = MDLoader->parseModuleMetadata())
2604       return Err;
2605   }
2606   DeferredMetadataInfo.clear();
2607   return Error::success();
2608 }
2609 
2610 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2611 
2612 /// When we see the block for a function body, remember where it is and then
2613 /// skip it.  This lets us lazily deserialize the functions.
2614 Error BitcodeReader::rememberAndSkipFunctionBody() {
2615   // Get the function we are talking about.
2616   if (FunctionsWithBodies.empty())
2617     return error("Insufficient function protos");
2618 
2619   Function *Fn = FunctionsWithBodies.back();
2620   FunctionsWithBodies.pop_back();
2621 
2622   // Save the current stream state.
2623   uint64_t CurBit = Stream.GetCurrentBitNo();
2624   assert(
2625       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2626       "Mismatch between VST and scanned function offsets");
2627   DeferredFunctionInfo[Fn] = CurBit;
2628 
2629   // Skip over the function block for now.
2630   if (Stream.SkipBlock())
2631     return error("Invalid record");
2632   return Error::success();
2633 }
2634 
2635 Error BitcodeReader::globalCleanup() {
2636   // Patch the initializers for globals and aliases up.
2637   if (Error Err = resolveGlobalAndIndirectSymbolInits())
2638     return Err;
2639   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2640     return error("Malformed global initializer set");
2641 
2642   // Look for intrinsic functions which need to be upgraded at some point
2643   for (Function &F : *TheModule) {
2644     MDLoader->upgradeDebugIntrinsics(F);
2645     Function *NewFn;
2646     if (UpgradeIntrinsicFunction(&F, NewFn))
2647       UpgradedIntrinsics[&F] = NewFn;
2648     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2649       // Some types could be renamed during loading if several modules are
2650       // loaded in the same LLVMContext (LTO scenario). In this case we should
2651       // remangle intrinsics names as well.
2652       RemangledIntrinsics[&F] = Remangled.getValue();
2653   }
2654 
2655   // Look for global variables which need to be renamed.
2656   for (GlobalVariable &GV : TheModule->globals())
2657     UpgradeGlobalVariable(&GV);
2658 
2659   // Force deallocation of memory for these vectors to favor the client that
2660   // want lazy deserialization.
2661   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2662   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
2663       IndirectSymbolInits);
2664   return Error::success();
2665 }
2666 
2667 /// Support for lazy parsing of function bodies. This is required if we
2668 /// either have an old bitcode file without a VST forward declaration record,
2669 /// or if we have an anonymous function being materialized, since anonymous
2670 /// functions do not have a name and are therefore not in the VST.
2671 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2672   Stream.JumpToBit(NextUnreadBit);
2673 
2674   if (Stream.AtEndOfStream())
2675     return error("Could not find function in stream");
2676 
2677   if (!SeenFirstFunctionBody)
2678     return error("Trying to materialize functions before seeing function blocks");
2679 
2680   // An old bitcode file with the symbol table at the end would have
2681   // finished the parse greedily.
2682   assert(SeenValueSymbolTable);
2683 
2684   SmallVector<uint64_t, 64> Record;
2685 
2686   while (true) {
2687     BitstreamEntry Entry = Stream.advance();
2688     switch (Entry.Kind) {
2689     default:
2690       return error("Expect SubBlock");
2691     case BitstreamEntry::SubBlock:
2692       switch (Entry.ID) {
2693       default:
2694         return error("Expect function block");
2695       case bitc::FUNCTION_BLOCK_ID:
2696         if (Error Err = rememberAndSkipFunctionBody())
2697           return Err;
2698         NextUnreadBit = Stream.GetCurrentBitNo();
2699         return Error::success();
2700       }
2701     }
2702   }
2703 }
2704 
2705 bool BitcodeReaderBase::readBlockInfo() {
2706   Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2707   if (!NewBlockInfo)
2708     return true;
2709   BlockInfo = std::move(*NewBlockInfo);
2710   return false;
2711 }
2712 
2713 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
2714   // v1: [selection_kind, name]
2715   // v2: [strtab_offset, strtab_size, selection_kind]
2716   StringRef Name;
2717   std::tie(Name, Record) = readNameFromStrtab(Record);
2718 
2719   if (Record.size() < 1)
2720     return error("Invalid record");
2721   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2722   std::string OldFormatName;
2723   if (!UseStrtab) {
2724     if (Record.size() < 2)
2725       return error("Invalid record");
2726     unsigned ComdatNameSize = Record[1];
2727     OldFormatName.reserve(ComdatNameSize);
2728     for (unsigned i = 0; i != ComdatNameSize; ++i)
2729       OldFormatName += (char)Record[2 + i];
2730     Name = OldFormatName;
2731   }
2732   Comdat *C = TheModule->getOrInsertComdat(Name);
2733   C->setSelectionKind(SK);
2734   ComdatList.push_back(C);
2735   return Error::success();
2736 }
2737 
2738 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
2739   // v1: [pointer type, isconst, initid, linkage, alignment, section,
2740   // visibility, threadlocal, unnamed_addr, externally_initialized,
2741   // dllstorageclass, comdat] (name in VST)
2742   // v2: [strtab_offset, strtab_size, v1]
2743   StringRef Name;
2744   std::tie(Name, Record) = readNameFromStrtab(Record);
2745 
2746   if (Record.size() < 6)
2747     return error("Invalid record");
2748   Type *Ty = getTypeByID(Record[0]);
2749   if (!Ty)
2750     return error("Invalid record");
2751   bool isConstant = Record[1] & 1;
2752   bool explicitType = Record[1] & 2;
2753   unsigned AddressSpace;
2754   if (explicitType) {
2755     AddressSpace = Record[1] >> 2;
2756   } else {
2757     if (!Ty->isPointerTy())
2758       return error("Invalid type for value");
2759     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2760     Ty = cast<PointerType>(Ty)->getElementType();
2761   }
2762 
2763   uint64_t RawLinkage = Record[3];
2764   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2765   unsigned Alignment;
2766   if (Error Err = parseAlignmentValue(Record[4], Alignment))
2767     return Err;
2768   std::string Section;
2769   if (Record[5]) {
2770     if (Record[5] - 1 >= SectionTable.size())
2771       return error("Invalid ID");
2772     Section = SectionTable[Record[5] - 1];
2773   }
2774   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2775   // Local linkage must have default visibility.
2776   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2777     // FIXME: Change to an error if non-default in 4.0.
2778     Visibility = getDecodedVisibility(Record[6]);
2779 
2780   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2781   if (Record.size() > 7)
2782     TLM = getDecodedThreadLocalMode(Record[7]);
2783 
2784   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2785   if (Record.size() > 8)
2786     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2787 
2788   bool ExternallyInitialized = false;
2789   if (Record.size() > 9)
2790     ExternallyInitialized = Record[9];
2791 
2792   GlobalVariable *NewGV =
2793       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
2794                          nullptr, TLM, AddressSpace, ExternallyInitialized);
2795   NewGV->setAlignment(Alignment);
2796   if (!Section.empty())
2797     NewGV->setSection(Section);
2798   NewGV->setVisibility(Visibility);
2799   NewGV->setUnnamedAddr(UnnamedAddr);
2800 
2801   if (Record.size() > 10)
2802     NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2803   else
2804     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2805 
2806   ValueList.push_back(NewGV);
2807 
2808   // Remember which value to use for the global initializer.
2809   if (unsigned InitID = Record[2])
2810     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2811 
2812   if (Record.size() > 11) {
2813     if (unsigned ComdatID = Record[11]) {
2814       if (ComdatID > ComdatList.size())
2815         return error("Invalid global variable comdat ID");
2816       NewGV->setComdat(ComdatList[ComdatID - 1]);
2817     }
2818   } else if (hasImplicitComdat(RawLinkage)) {
2819     NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2820   }
2821   return Error::success();
2822 }
2823 
2824 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
2825   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
2826   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
2827   // prefixdata] (name in VST)
2828   // v2: [strtab_offset, strtab_size, v1]
2829   StringRef Name;
2830   std::tie(Name, Record) = readNameFromStrtab(Record);
2831 
2832   if (Record.size() < 8)
2833     return error("Invalid record");
2834   Type *Ty = getTypeByID(Record[0]);
2835   if (!Ty)
2836     return error("Invalid record");
2837   if (auto *PTy = dyn_cast<PointerType>(Ty))
2838     Ty = PTy->getElementType();
2839   auto *FTy = dyn_cast<FunctionType>(Ty);
2840   if (!FTy)
2841     return error("Invalid type for value");
2842   auto CC = static_cast<CallingConv::ID>(Record[1]);
2843   if (CC & ~CallingConv::MaxID)
2844     return error("Invalid calling convention ID");
2845 
2846   Function *Func =
2847       Function::Create(FTy, GlobalValue::ExternalLinkage, Name, TheModule);
2848 
2849   Func->setCallingConv(CC);
2850   bool isProto = Record[2];
2851   uint64_t RawLinkage = Record[3];
2852   Func->setLinkage(getDecodedLinkage(RawLinkage));
2853   Func->setAttributes(getAttributes(Record[4]));
2854 
2855   unsigned Alignment;
2856   if (Error Err = parseAlignmentValue(Record[5], Alignment))
2857     return Err;
2858   Func->setAlignment(Alignment);
2859   if (Record[6]) {
2860     if (Record[6] - 1 >= SectionTable.size())
2861       return error("Invalid ID");
2862     Func->setSection(SectionTable[Record[6] - 1]);
2863   }
2864   // Local linkage must have default visibility.
2865   if (!Func->hasLocalLinkage())
2866     // FIXME: Change to an error if non-default in 4.0.
2867     Func->setVisibility(getDecodedVisibility(Record[7]));
2868   if (Record.size() > 8 && Record[8]) {
2869     if (Record[8] - 1 >= GCTable.size())
2870       return error("Invalid ID");
2871     Func->setGC(GCTable[Record[8] - 1]);
2872   }
2873   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
2874   if (Record.size() > 9)
2875     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
2876   Func->setUnnamedAddr(UnnamedAddr);
2877   if (Record.size() > 10 && Record[10] != 0)
2878     FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
2879 
2880   if (Record.size() > 11)
2881     Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
2882   else
2883     upgradeDLLImportExportLinkage(Func, RawLinkage);
2884 
2885   if (Record.size() > 12) {
2886     if (unsigned ComdatID = Record[12]) {
2887       if (ComdatID > ComdatList.size())
2888         return error("Invalid function comdat ID");
2889       Func->setComdat(ComdatList[ComdatID - 1]);
2890     }
2891   } else if (hasImplicitComdat(RawLinkage)) {
2892     Func->setComdat(reinterpret_cast<Comdat *>(1));
2893   }
2894 
2895   if (Record.size() > 13 && Record[13] != 0)
2896     FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
2897 
2898   if (Record.size() > 14 && Record[14] != 0)
2899     FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2900 
2901   ValueList.push_back(Func);
2902 
2903   // If this is a function with a body, remember the prototype we are
2904   // creating now, so that we can match up the body with them later.
2905   if (!isProto) {
2906     Func->setIsMaterializable(true);
2907     FunctionsWithBodies.push_back(Func);
2908     DeferredFunctionInfo[Func] = 0;
2909   }
2910   return Error::success();
2911 }
2912 
2913 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
2914     unsigned BitCode, ArrayRef<uint64_t> Record) {
2915   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
2916   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
2917   // dllstorageclass] (name in VST)
2918   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
2919   // visibility, dllstorageclass] (name in VST)
2920   // v2: [strtab_offset, strtab_size, v1]
2921   StringRef Name;
2922   std::tie(Name, Record) = readNameFromStrtab(Record);
2923 
2924   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
2925   if (Record.size() < (3 + (unsigned)NewRecord))
2926     return error("Invalid record");
2927   unsigned OpNum = 0;
2928   Type *Ty = getTypeByID(Record[OpNum++]);
2929   if (!Ty)
2930     return error("Invalid record");
2931 
2932   unsigned AddrSpace;
2933   if (!NewRecord) {
2934     auto *PTy = dyn_cast<PointerType>(Ty);
2935     if (!PTy)
2936       return error("Invalid type for value");
2937     Ty = PTy->getElementType();
2938     AddrSpace = PTy->getAddressSpace();
2939   } else {
2940     AddrSpace = Record[OpNum++];
2941   }
2942 
2943   auto Val = Record[OpNum++];
2944   auto Linkage = Record[OpNum++];
2945   GlobalIndirectSymbol *NewGA;
2946   if (BitCode == bitc::MODULE_CODE_ALIAS ||
2947       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
2948     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
2949                                 TheModule);
2950   else
2951     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
2952                                 nullptr, TheModule);
2953   // Old bitcode files didn't have visibility field.
2954   // Local linkage must have default visibility.
2955   if (OpNum != Record.size()) {
2956     auto VisInd = OpNum++;
2957     if (!NewGA->hasLocalLinkage())
2958       // FIXME: Change to an error if non-default in 4.0.
2959       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
2960   }
2961   if (OpNum != Record.size())
2962     NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
2963   else
2964     upgradeDLLImportExportLinkage(NewGA, Linkage);
2965   if (OpNum != Record.size())
2966     NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
2967   if (OpNum != Record.size())
2968     NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
2969   ValueList.push_back(NewGA);
2970   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
2971   return Error::success();
2972 }
2973 
2974 Error BitcodeReader::parseModule(uint64_t ResumeBit,
2975                                  bool ShouldLazyLoadMetadata) {
2976   if (ResumeBit)
2977     Stream.JumpToBit(ResumeBit);
2978   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2979     return error("Invalid record");
2980 
2981   SmallVector<uint64_t, 64> Record;
2982 
2983   // Read all the records for this module.
2984   while (true) {
2985     BitstreamEntry Entry = Stream.advance();
2986 
2987     switch (Entry.Kind) {
2988     case BitstreamEntry::Error:
2989       return error("Malformed block");
2990     case BitstreamEntry::EndBlock:
2991       return globalCleanup();
2992 
2993     case BitstreamEntry::SubBlock:
2994       switch (Entry.ID) {
2995       default:  // Skip unknown content.
2996         if (Stream.SkipBlock())
2997           return error("Invalid record");
2998         break;
2999       case bitc::BLOCKINFO_BLOCK_ID:
3000         if (readBlockInfo())
3001           return error("Malformed block");
3002         break;
3003       case bitc::PARAMATTR_BLOCK_ID:
3004         if (Error Err = parseAttributeBlock())
3005           return Err;
3006         break;
3007       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3008         if (Error Err = parseAttributeGroupBlock())
3009           return Err;
3010         break;
3011       case bitc::TYPE_BLOCK_ID_NEW:
3012         if (Error Err = parseTypeTable())
3013           return Err;
3014         break;
3015       case bitc::VALUE_SYMTAB_BLOCK_ID:
3016         if (!SeenValueSymbolTable) {
3017           // Either this is an old form VST without function index and an
3018           // associated VST forward declaration record (which would have caused
3019           // the VST to be jumped to and parsed before it was encountered
3020           // normally in the stream), or there were no function blocks to
3021           // trigger an earlier parsing of the VST.
3022           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3023           if (Error Err = parseValueSymbolTable())
3024             return Err;
3025           SeenValueSymbolTable = true;
3026         } else {
3027           // We must have had a VST forward declaration record, which caused
3028           // the parser to jump to and parse the VST earlier.
3029           assert(VSTOffset > 0);
3030           if (Stream.SkipBlock())
3031             return error("Invalid record");
3032         }
3033         break;
3034       case bitc::CONSTANTS_BLOCK_ID:
3035         if (Error Err = parseConstants())
3036           return Err;
3037         if (Error Err = resolveGlobalAndIndirectSymbolInits())
3038           return Err;
3039         break;
3040       case bitc::METADATA_BLOCK_ID:
3041         if (ShouldLazyLoadMetadata) {
3042           if (Error Err = rememberAndSkipMetadata())
3043             return Err;
3044           break;
3045         }
3046         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3047         if (Error Err = MDLoader->parseModuleMetadata())
3048           return Err;
3049         break;
3050       case bitc::METADATA_KIND_BLOCK_ID:
3051         if (Error Err = MDLoader->parseMetadataKinds())
3052           return Err;
3053         break;
3054       case bitc::FUNCTION_BLOCK_ID:
3055         // If this is the first function body we've seen, reverse the
3056         // FunctionsWithBodies list.
3057         if (!SeenFirstFunctionBody) {
3058           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3059           if (Error Err = globalCleanup())
3060             return Err;
3061           SeenFirstFunctionBody = true;
3062         }
3063 
3064         if (VSTOffset > 0) {
3065           // If we have a VST forward declaration record, make sure we
3066           // parse the VST now if we haven't already. It is needed to
3067           // set up the DeferredFunctionInfo vector for lazy reading.
3068           if (!SeenValueSymbolTable) {
3069             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3070               return Err;
3071             SeenValueSymbolTable = true;
3072             // Fall through so that we record the NextUnreadBit below.
3073             // This is necessary in case we have an anonymous function that
3074             // is later materialized. Since it will not have a VST entry we
3075             // need to fall back to the lazy parse to find its offset.
3076           } else {
3077             // If we have a VST forward declaration record, but have already
3078             // parsed the VST (just above, when the first function body was
3079             // encountered here), then we are resuming the parse after
3080             // materializing functions. The ResumeBit points to the
3081             // start of the last function block recorded in the
3082             // DeferredFunctionInfo map. Skip it.
3083             if (Stream.SkipBlock())
3084               return error("Invalid record");
3085             continue;
3086           }
3087         }
3088 
3089         // Support older bitcode files that did not have the function
3090         // index in the VST, nor a VST forward declaration record, as
3091         // well as anonymous functions that do not have VST entries.
3092         // Build the DeferredFunctionInfo vector on the fly.
3093         if (Error Err = rememberAndSkipFunctionBody())
3094           return Err;
3095 
3096         // Suspend parsing when we reach the function bodies. Subsequent
3097         // materialization calls will resume it when necessary. If the bitcode
3098         // file is old, the symbol table will be at the end instead and will not
3099         // have been seen yet. In this case, just finish the parse now.
3100         if (SeenValueSymbolTable) {
3101           NextUnreadBit = Stream.GetCurrentBitNo();
3102           // After the VST has been parsed, we need to make sure intrinsic name
3103           // are auto-upgraded.
3104           return globalCleanup();
3105         }
3106         break;
3107       case bitc::USELIST_BLOCK_ID:
3108         if (Error Err = parseUseLists())
3109           return Err;
3110         break;
3111       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3112         if (Error Err = parseOperandBundleTags())
3113           return Err;
3114         break;
3115       }
3116       continue;
3117 
3118     case BitstreamEntry::Record:
3119       // The interesting case.
3120       break;
3121     }
3122 
3123     // Read a record.
3124     auto BitCode = Stream.readRecord(Entry.ID, Record);
3125     switch (BitCode) {
3126     default: break;  // Default behavior, ignore unknown content.
3127     case bitc::MODULE_CODE_VERSION: {
3128       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3129       if (!VersionOrErr)
3130         return VersionOrErr.takeError();
3131       UseRelativeIDs = *VersionOrErr >= 1;
3132       break;
3133     }
3134     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3135       std::string S;
3136       if (convertToString(Record, 0, S))
3137         return error("Invalid record");
3138       TheModule->setTargetTriple(S);
3139       break;
3140     }
3141     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3142       std::string S;
3143       if (convertToString(Record, 0, S))
3144         return error("Invalid record");
3145       TheModule->setDataLayout(S);
3146       break;
3147     }
3148     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3149       std::string S;
3150       if (convertToString(Record, 0, S))
3151         return error("Invalid record");
3152       TheModule->setModuleInlineAsm(S);
3153       break;
3154     }
3155     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3156       // FIXME: Remove in 4.0.
3157       std::string S;
3158       if (convertToString(Record, 0, S))
3159         return error("Invalid record");
3160       // Ignore value.
3161       break;
3162     }
3163     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3164       std::string S;
3165       if (convertToString(Record, 0, S))
3166         return error("Invalid record");
3167       SectionTable.push_back(S);
3168       break;
3169     }
3170     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3171       std::string S;
3172       if (convertToString(Record, 0, S))
3173         return error("Invalid record");
3174       GCTable.push_back(S);
3175       break;
3176     }
3177     case bitc::MODULE_CODE_COMDAT: {
3178       if (Error Err = parseComdatRecord(Record))
3179         return Err;
3180       break;
3181     }
3182     case bitc::MODULE_CODE_GLOBALVAR: {
3183       if (Error Err = parseGlobalVarRecord(Record))
3184         return Err;
3185       break;
3186     }
3187     case bitc::MODULE_CODE_FUNCTION: {
3188       if (Error Err = parseFunctionRecord(Record))
3189         return Err;
3190       break;
3191     }
3192     case bitc::MODULE_CODE_IFUNC:
3193     case bitc::MODULE_CODE_ALIAS:
3194     case bitc::MODULE_CODE_ALIAS_OLD: {
3195       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3196         return Err;
3197       break;
3198     }
3199     /// MODULE_CODE_VSTOFFSET: [offset]
3200     case bitc::MODULE_CODE_VSTOFFSET:
3201       if (Record.size() < 1)
3202         return error("Invalid record");
3203       // Note that we subtract 1 here because the offset is relative to one word
3204       // before the start of the identification or module block, which was
3205       // historically always the start of the regular bitcode header.
3206       VSTOffset = Record[0] - 1;
3207       break;
3208     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3209     case bitc::MODULE_CODE_SOURCE_FILENAME:
3210       SmallString<128> ValueName;
3211       if (convertToString(Record, 0, ValueName))
3212         return error("Invalid record");
3213       TheModule->setSourceFileName(ValueName);
3214       break;
3215     }
3216     Record.clear();
3217   }
3218 }
3219 
3220 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3221                                       bool IsImporting) {
3222   TheModule = M;
3223   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3224                             [&](unsigned ID) { return getTypeByID(ID); });
3225   return parseModule(0, ShouldLazyLoadMetadata);
3226 }
3227 
3228 
3229 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3230   if (!isa<PointerType>(PtrType))
3231     return error("Load/Store operand is not a pointer type");
3232   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3233 
3234   if (ValType && ValType != ElemType)
3235     return error("Explicit load/store type does not match pointee "
3236                  "type of pointer operand");
3237   if (!PointerType::isLoadableOrStorableType(ElemType))
3238     return error("Cannot load/store from pointer");
3239   return Error::success();
3240 }
3241 
3242 /// Lazily parse the specified function body block.
3243 Error BitcodeReader::parseFunctionBody(Function *F) {
3244   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3245     return error("Invalid record");
3246 
3247   // Unexpected unresolved metadata when parsing function.
3248   if (MDLoader->hasFwdRefs())
3249     return error("Invalid function metadata: incoming forward references");
3250 
3251   InstructionList.clear();
3252   unsigned ModuleValueListSize = ValueList.size();
3253   unsigned ModuleMDLoaderSize = MDLoader->size();
3254 
3255   // Add all the function arguments to the value table.
3256   for (Argument &I : F->args())
3257     ValueList.push_back(&I);
3258 
3259   unsigned NextValueNo = ValueList.size();
3260   BasicBlock *CurBB = nullptr;
3261   unsigned CurBBNo = 0;
3262 
3263   DebugLoc LastLoc;
3264   auto getLastInstruction = [&]() -> Instruction * {
3265     if (CurBB && !CurBB->empty())
3266       return &CurBB->back();
3267     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3268              !FunctionBBs[CurBBNo - 1]->empty())
3269       return &FunctionBBs[CurBBNo - 1]->back();
3270     return nullptr;
3271   };
3272 
3273   std::vector<OperandBundleDef> OperandBundles;
3274 
3275   // Read all the records.
3276   SmallVector<uint64_t, 64> Record;
3277 
3278   while (true) {
3279     BitstreamEntry Entry = Stream.advance();
3280 
3281     switch (Entry.Kind) {
3282     case BitstreamEntry::Error:
3283       return error("Malformed block");
3284     case BitstreamEntry::EndBlock:
3285       goto OutOfRecordLoop;
3286 
3287     case BitstreamEntry::SubBlock:
3288       switch (Entry.ID) {
3289       default:  // Skip unknown content.
3290         if (Stream.SkipBlock())
3291           return error("Invalid record");
3292         break;
3293       case bitc::CONSTANTS_BLOCK_ID:
3294         if (Error Err = parseConstants())
3295           return Err;
3296         NextValueNo = ValueList.size();
3297         break;
3298       case bitc::VALUE_SYMTAB_BLOCK_ID:
3299         if (Error Err = parseValueSymbolTable())
3300           return Err;
3301         break;
3302       case bitc::METADATA_ATTACHMENT_ID:
3303         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3304           return Err;
3305         break;
3306       case bitc::METADATA_BLOCK_ID:
3307         assert(DeferredMetadataInfo.empty() &&
3308                "Must read all module-level metadata before function-level");
3309         if (Error Err = MDLoader->parseFunctionMetadata())
3310           return Err;
3311         break;
3312       case bitc::USELIST_BLOCK_ID:
3313         if (Error Err = parseUseLists())
3314           return Err;
3315         break;
3316       }
3317       continue;
3318 
3319     case BitstreamEntry::Record:
3320       // The interesting case.
3321       break;
3322     }
3323 
3324     // Read a record.
3325     Record.clear();
3326     Instruction *I = nullptr;
3327     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3328     switch (BitCode) {
3329     default: // Default behavior: reject
3330       return error("Invalid value");
3331     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3332       if (Record.size() < 1 || Record[0] == 0)
3333         return error("Invalid record");
3334       // Create all the basic blocks for the function.
3335       FunctionBBs.resize(Record[0]);
3336 
3337       // See if anything took the address of blocks in this function.
3338       auto BBFRI = BasicBlockFwdRefs.find(F);
3339       if (BBFRI == BasicBlockFwdRefs.end()) {
3340         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3341           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3342       } else {
3343         auto &BBRefs = BBFRI->second;
3344         // Check for invalid basic block references.
3345         if (BBRefs.size() > FunctionBBs.size())
3346           return error("Invalid ID");
3347         assert(!BBRefs.empty() && "Unexpected empty array");
3348         assert(!BBRefs.front() && "Invalid reference to entry block");
3349         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3350              ++I)
3351           if (I < RE && BBRefs[I]) {
3352             BBRefs[I]->insertInto(F);
3353             FunctionBBs[I] = BBRefs[I];
3354           } else {
3355             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3356           }
3357 
3358         // Erase from the table.
3359         BasicBlockFwdRefs.erase(BBFRI);
3360       }
3361 
3362       CurBB = FunctionBBs[0];
3363       continue;
3364     }
3365 
3366     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
3367       // This record indicates that the last instruction is at the same
3368       // location as the previous instruction with a location.
3369       I = getLastInstruction();
3370 
3371       if (!I)
3372         return error("Invalid record");
3373       I->setDebugLoc(LastLoc);
3374       I = nullptr;
3375       continue;
3376 
3377     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
3378       I = getLastInstruction();
3379       if (!I || Record.size() < 4)
3380         return error("Invalid record");
3381 
3382       unsigned Line = Record[0], Col = Record[1];
3383       unsigned ScopeID = Record[2], IAID = Record[3];
3384 
3385       MDNode *Scope = nullptr, *IA = nullptr;
3386       if (ScopeID) {
3387         Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
3388         if (!Scope)
3389           return error("Invalid record");
3390       }
3391       if (IAID) {
3392         IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
3393         if (!IA)
3394           return error("Invalid record");
3395       }
3396       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3397       I->setDebugLoc(LastLoc);
3398       I = nullptr;
3399       continue;
3400     }
3401 
3402     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
3403       unsigned OpNum = 0;
3404       Value *LHS, *RHS;
3405       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3406           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3407           OpNum+1 > Record.size())
3408         return error("Invalid record");
3409 
3410       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3411       if (Opc == -1)
3412         return error("Invalid record");
3413       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3414       InstructionList.push_back(I);
3415       if (OpNum < Record.size()) {
3416         if (Opc == Instruction::Add ||
3417             Opc == Instruction::Sub ||
3418             Opc == Instruction::Mul ||
3419             Opc == Instruction::Shl) {
3420           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3421             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3422           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3423             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3424         } else if (Opc == Instruction::SDiv ||
3425                    Opc == Instruction::UDiv ||
3426                    Opc == Instruction::LShr ||
3427                    Opc == Instruction::AShr) {
3428           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3429             cast<BinaryOperator>(I)->setIsExact(true);
3430         } else if (isa<FPMathOperator>(I)) {
3431           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3432           if (FMF.any())
3433             I->setFastMathFlags(FMF);
3434         }
3435 
3436       }
3437       break;
3438     }
3439     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
3440       unsigned OpNum = 0;
3441       Value *Op;
3442       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3443           OpNum+2 != Record.size())
3444         return error("Invalid record");
3445 
3446       Type *ResTy = getTypeByID(Record[OpNum]);
3447       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3448       if (Opc == -1 || !ResTy)
3449         return error("Invalid record");
3450       Instruction *Temp = nullptr;
3451       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3452         if (Temp) {
3453           InstructionList.push_back(Temp);
3454           CurBB->getInstList().push_back(Temp);
3455         }
3456       } else {
3457         auto CastOp = (Instruction::CastOps)Opc;
3458         if (!CastInst::castIsValid(CastOp, Op, ResTy))
3459           return error("Invalid cast");
3460         I = CastInst::Create(CastOp, Op, ResTy);
3461       }
3462       InstructionList.push_back(I);
3463       break;
3464     }
3465     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3466     case bitc::FUNC_CODE_INST_GEP_OLD:
3467     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3468       unsigned OpNum = 0;
3469 
3470       Type *Ty;
3471       bool InBounds;
3472 
3473       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3474         InBounds = Record[OpNum++];
3475         Ty = getTypeByID(Record[OpNum++]);
3476       } else {
3477         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3478         Ty = nullptr;
3479       }
3480 
3481       Value *BasePtr;
3482       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3483         return error("Invalid record");
3484 
3485       if (!Ty)
3486         Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
3487                  ->getElementType();
3488       else if (Ty !=
3489                cast<PointerType>(BasePtr->getType()->getScalarType())
3490                    ->getElementType())
3491         return error(
3492             "Explicit gep type does not match pointee type of pointer operand");
3493 
3494       SmallVector<Value*, 16> GEPIdx;
3495       while (OpNum != Record.size()) {
3496         Value *Op;
3497         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3498           return error("Invalid record");
3499         GEPIdx.push_back(Op);
3500       }
3501 
3502       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3503 
3504       InstructionList.push_back(I);
3505       if (InBounds)
3506         cast<GetElementPtrInst>(I)->setIsInBounds(true);
3507       break;
3508     }
3509 
3510     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3511                                        // EXTRACTVAL: [opty, opval, n x indices]
3512       unsigned OpNum = 0;
3513       Value *Agg;
3514       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3515         return error("Invalid record");
3516 
3517       unsigned RecSize = Record.size();
3518       if (OpNum == RecSize)
3519         return error("EXTRACTVAL: Invalid instruction with 0 indices");
3520 
3521       SmallVector<unsigned, 4> EXTRACTVALIdx;
3522       Type *CurTy = Agg->getType();
3523       for (; OpNum != RecSize; ++OpNum) {
3524         bool IsArray = CurTy->isArrayTy();
3525         bool IsStruct = CurTy->isStructTy();
3526         uint64_t Index = Record[OpNum];
3527 
3528         if (!IsStruct && !IsArray)
3529           return error("EXTRACTVAL: Invalid type");
3530         if ((unsigned)Index != Index)
3531           return error("Invalid value");
3532         if (IsStruct && Index >= CurTy->subtypes().size())
3533           return error("EXTRACTVAL: Invalid struct index");
3534         if (IsArray && Index >= CurTy->getArrayNumElements())
3535           return error("EXTRACTVAL: Invalid array index");
3536         EXTRACTVALIdx.push_back((unsigned)Index);
3537 
3538         if (IsStruct)
3539           CurTy = CurTy->subtypes()[Index];
3540         else
3541           CurTy = CurTy->subtypes()[0];
3542       }
3543 
3544       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3545       InstructionList.push_back(I);
3546       break;
3547     }
3548 
3549     case bitc::FUNC_CODE_INST_INSERTVAL: {
3550                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
3551       unsigned OpNum = 0;
3552       Value *Agg;
3553       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3554         return error("Invalid record");
3555       Value *Val;
3556       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3557         return error("Invalid record");
3558 
3559       unsigned RecSize = Record.size();
3560       if (OpNum == RecSize)
3561         return error("INSERTVAL: Invalid instruction with 0 indices");
3562 
3563       SmallVector<unsigned, 4> INSERTVALIdx;
3564       Type *CurTy = Agg->getType();
3565       for (; OpNum != RecSize; ++OpNum) {
3566         bool IsArray = CurTy->isArrayTy();
3567         bool IsStruct = CurTy->isStructTy();
3568         uint64_t Index = Record[OpNum];
3569 
3570         if (!IsStruct && !IsArray)
3571           return error("INSERTVAL: Invalid type");
3572         if ((unsigned)Index != Index)
3573           return error("Invalid value");
3574         if (IsStruct && Index >= CurTy->subtypes().size())
3575           return error("INSERTVAL: Invalid struct index");
3576         if (IsArray && Index >= CurTy->getArrayNumElements())
3577           return error("INSERTVAL: Invalid array index");
3578 
3579         INSERTVALIdx.push_back((unsigned)Index);
3580         if (IsStruct)
3581           CurTy = CurTy->subtypes()[Index];
3582         else
3583           CurTy = CurTy->subtypes()[0];
3584       }
3585 
3586       if (CurTy != Val->getType())
3587         return error("Inserted value type doesn't match aggregate type");
3588 
3589       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3590       InstructionList.push_back(I);
3591       break;
3592     }
3593 
3594     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3595       // obsolete form of select
3596       // handles select i1 ... in old bitcode
3597       unsigned OpNum = 0;
3598       Value *TrueVal, *FalseVal, *Cond;
3599       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3600           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3601           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3602         return error("Invalid record");
3603 
3604       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3605       InstructionList.push_back(I);
3606       break;
3607     }
3608 
3609     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3610       // new form of select
3611       // handles select i1 or select [N x i1]
3612       unsigned OpNum = 0;
3613       Value *TrueVal, *FalseVal, *Cond;
3614       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3615           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3616           getValueTypePair(Record, OpNum, NextValueNo, Cond))
3617         return error("Invalid record");
3618 
3619       // select condition can be either i1 or [N x i1]
3620       if (VectorType* vector_type =
3621           dyn_cast<VectorType>(Cond->getType())) {
3622         // expect <n x i1>
3623         if (vector_type->getElementType() != Type::getInt1Ty(Context))
3624           return error("Invalid type for value");
3625       } else {
3626         // expect i1
3627         if (Cond->getType() != Type::getInt1Ty(Context))
3628           return error("Invalid type for value");
3629       }
3630 
3631       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3632       InstructionList.push_back(I);
3633       break;
3634     }
3635 
3636     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3637       unsigned OpNum = 0;
3638       Value *Vec, *Idx;
3639       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3640           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3641         return error("Invalid record");
3642       if (!Vec->getType()->isVectorTy())
3643         return error("Invalid type for value");
3644       I = ExtractElementInst::Create(Vec, Idx);
3645       InstructionList.push_back(I);
3646       break;
3647     }
3648 
3649     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3650       unsigned OpNum = 0;
3651       Value *Vec, *Elt, *Idx;
3652       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3653         return error("Invalid record");
3654       if (!Vec->getType()->isVectorTy())
3655         return error("Invalid type for value");
3656       if (popValue(Record, OpNum, NextValueNo,
3657                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3658           getValueTypePair(Record, OpNum, NextValueNo, Idx))
3659         return error("Invalid record");
3660       I = InsertElementInst::Create(Vec, Elt, Idx);
3661       InstructionList.push_back(I);
3662       break;
3663     }
3664 
3665     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3666       unsigned OpNum = 0;
3667       Value *Vec1, *Vec2, *Mask;
3668       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3669           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3670         return error("Invalid record");
3671 
3672       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3673         return error("Invalid record");
3674       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3675         return error("Invalid type for value");
3676       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3677       InstructionList.push_back(I);
3678       break;
3679     }
3680 
3681     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
3682       // Old form of ICmp/FCmp returning bool
3683       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3684       // both legal on vectors but had different behaviour.
3685     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3686       // FCmp/ICmp returning bool or vector of bool
3687 
3688       unsigned OpNum = 0;
3689       Value *LHS, *RHS;
3690       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3691           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3692         return error("Invalid record");
3693 
3694       unsigned PredVal = Record[OpNum];
3695       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3696       FastMathFlags FMF;
3697       if (IsFP && Record.size() > OpNum+1)
3698         FMF = getDecodedFastMathFlags(Record[++OpNum]);
3699 
3700       if (OpNum+1 != Record.size())
3701         return error("Invalid record");
3702 
3703       if (LHS->getType()->isFPOrFPVectorTy())
3704         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3705       else
3706         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3707 
3708       if (FMF.any())
3709         I->setFastMathFlags(FMF);
3710       InstructionList.push_back(I);
3711       break;
3712     }
3713 
3714     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3715       {
3716         unsigned Size = Record.size();
3717         if (Size == 0) {
3718           I = ReturnInst::Create(Context);
3719           InstructionList.push_back(I);
3720           break;
3721         }
3722 
3723         unsigned OpNum = 0;
3724         Value *Op = nullptr;
3725         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3726           return error("Invalid record");
3727         if (OpNum != Record.size())
3728           return error("Invalid record");
3729 
3730         I = ReturnInst::Create(Context, Op);
3731         InstructionList.push_back(I);
3732         break;
3733       }
3734     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3735       if (Record.size() != 1 && Record.size() != 3)
3736         return error("Invalid record");
3737       BasicBlock *TrueDest = getBasicBlock(Record[0]);
3738       if (!TrueDest)
3739         return error("Invalid record");
3740 
3741       if (Record.size() == 1) {
3742         I = BranchInst::Create(TrueDest);
3743         InstructionList.push_back(I);
3744       }
3745       else {
3746         BasicBlock *FalseDest = getBasicBlock(Record[1]);
3747         Value *Cond = getValue(Record, 2, NextValueNo,
3748                                Type::getInt1Ty(Context));
3749         if (!FalseDest || !Cond)
3750           return error("Invalid record");
3751         I = BranchInst::Create(TrueDest, FalseDest, Cond);
3752         InstructionList.push_back(I);
3753       }
3754       break;
3755     }
3756     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
3757       if (Record.size() != 1 && Record.size() != 2)
3758         return error("Invalid record");
3759       unsigned Idx = 0;
3760       Value *CleanupPad =
3761           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3762       if (!CleanupPad)
3763         return error("Invalid record");
3764       BasicBlock *UnwindDest = nullptr;
3765       if (Record.size() == 2) {
3766         UnwindDest = getBasicBlock(Record[Idx++]);
3767         if (!UnwindDest)
3768           return error("Invalid record");
3769       }
3770 
3771       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
3772       InstructionList.push_back(I);
3773       break;
3774     }
3775     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3776       if (Record.size() != 2)
3777         return error("Invalid record");
3778       unsigned Idx = 0;
3779       Value *CatchPad =
3780           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3781       if (!CatchPad)
3782         return error("Invalid record");
3783       BasicBlock *BB = getBasicBlock(Record[Idx++]);
3784       if (!BB)
3785         return error("Invalid record");
3786 
3787       I = CatchReturnInst::Create(CatchPad, BB);
3788       InstructionList.push_back(I);
3789       break;
3790     }
3791     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3792       // We must have, at minimum, the outer scope and the number of arguments.
3793       if (Record.size() < 2)
3794         return error("Invalid record");
3795 
3796       unsigned Idx = 0;
3797 
3798       Value *ParentPad =
3799           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3800 
3801       unsigned NumHandlers = Record[Idx++];
3802 
3803       SmallVector<BasicBlock *, 2> Handlers;
3804       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3805         BasicBlock *BB = getBasicBlock(Record[Idx++]);
3806         if (!BB)
3807           return error("Invalid record");
3808         Handlers.push_back(BB);
3809       }
3810 
3811       BasicBlock *UnwindDest = nullptr;
3812       if (Idx + 1 == Record.size()) {
3813         UnwindDest = getBasicBlock(Record[Idx++]);
3814         if (!UnwindDest)
3815           return error("Invalid record");
3816       }
3817 
3818       if (Record.size() != Idx)
3819         return error("Invalid record");
3820 
3821       auto *CatchSwitch =
3822           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3823       for (BasicBlock *Handler : Handlers)
3824         CatchSwitch->addHandler(Handler);
3825       I = CatchSwitch;
3826       InstructionList.push_back(I);
3827       break;
3828     }
3829     case bitc::FUNC_CODE_INST_CATCHPAD:
3830     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
3831       // We must have, at minimum, the outer scope and the number of arguments.
3832       if (Record.size() < 2)
3833         return error("Invalid record");
3834 
3835       unsigned Idx = 0;
3836 
3837       Value *ParentPad =
3838           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3839 
3840       unsigned NumArgOperands = Record[Idx++];
3841 
3842       SmallVector<Value *, 2> Args;
3843       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3844         Value *Val;
3845         if (getValueTypePair(Record, Idx, NextValueNo, Val))
3846           return error("Invalid record");
3847         Args.push_back(Val);
3848       }
3849 
3850       if (Record.size() != Idx)
3851         return error("Invalid record");
3852 
3853       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
3854         I = CleanupPadInst::Create(ParentPad, Args);
3855       else
3856         I = CatchPadInst::Create(ParentPad, Args);
3857       InstructionList.push_back(I);
3858       break;
3859     }
3860     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3861       // Check magic
3862       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3863         // "New" SwitchInst format with case ranges. The changes to write this
3864         // format were reverted but we still recognize bitcode that uses it.
3865         // Hopefully someday we will have support for case ranges and can use
3866         // this format again.
3867 
3868         Type *OpTy = getTypeByID(Record[1]);
3869         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3870 
3871         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3872         BasicBlock *Default = getBasicBlock(Record[3]);
3873         if (!OpTy || !Cond || !Default)
3874           return error("Invalid record");
3875 
3876         unsigned NumCases = Record[4];
3877 
3878         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3879         InstructionList.push_back(SI);
3880 
3881         unsigned CurIdx = 5;
3882         for (unsigned i = 0; i != NumCases; ++i) {
3883           SmallVector<ConstantInt*, 1> CaseVals;
3884           unsigned NumItems = Record[CurIdx++];
3885           for (unsigned ci = 0; ci != NumItems; ++ci) {
3886             bool isSingleNumber = Record[CurIdx++];
3887 
3888             APInt Low;
3889             unsigned ActiveWords = 1;
3890             if (ValueBitWidth > 64)
3891               ActiveWords = Record[CurIdx++];
3892             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3893                                 ValueBitWidth);
3894             CurIdx += ActiveWords;
3895 
3896             if (!isSingleNumber) {
3897               ActiveWords = 1;
3898               if (ValueBitWidth > 64)
3899                 ActiveWords = Record[CurIdx++];
3900               APInt High = readWideAPInt(
3901                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3902               CurIdx += ActiveWords;
3903 
3904               // FIXME: It is not clear whether values in the range should be
3905               // compared as signed or unsigned values. The partially
3906               // implemented changes that used this format in the past used
3907               // unsigned comparisons.
3908               for ( ; Low.ule(High); ++Low)
3909                 CaseVals.push_back(ConstantInt::get(Context, Low));
3910             } else
3911               CaseVals.push_back(ConstantInt::get(Context, Low));
3912           }
3913           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3914           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3915                  cve = CaseVals.end(); cvi != cve; ++cvi)
3916             SI->addCase(*cvi, DestBB);
3917         }
3918         I = SI;
3919         break;
3920       }
3921 
3922       // Old SwitchInst format without case ranges.
3923 
3924       if (Record.size() < 3 || (Record.size() & 1) == 0)
3925         return error("Invalid record");
3926       Type *OpTy = getTypeByID(Record[0]);
3927       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3928       BasicBlock *Default = getBasicBlock(Record[2]);
3929       if (!OpTy || !Cond || !Default)
3930         return error("Invalid record");
3931       unsigned NumCases = (Record.size()-3)/2;
3932       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3933       InstructionList.push_back(SI);
3934       for (unsigned i = 0, e = NumCases; i != e; ++i) {
3935         ConstantInt *CaseVal =
3936           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3937         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3938         if (!CaseVal || !DestBB) {
3939           delete SI;
3940           return error("Invalid record");
3941         }
3942         SI->addCase(CaseVal, DestBB);
3943       }
3944       I = SI;
3945       break;
3946     }
3947     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3948       if (Record.size() < 2)
3949         return error("Invalid record");
3950       Type *OpTy = getTypeByID(Record[0]);
3951       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3952       if (!OpTy || !Address)
3953         return error("Invalid record");
3954       unsigned NumDests = Record.size()-2;
3955       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3956       InstructionList.push_back(IBI);
3957       for (unsigned i = 0, e = NumDests; i != e; ++i) {
3958         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3959           IBI->addDestination(DestBB);
3960         } else {
3961           delete IBI;
3962           return error("Invalid record");
3963         }
3964       }
3965       I = IBI;
3966       break;
3967     }
3968 
3969     case bitc::FUNC_CODE_INST_INVOKE: {
3970       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3971       if (Record.size() < 4)
3972         return error("Invalid record");
3973       unsigned OpNum = 0;
3974       AttributeList PAL = getAttributes(Record[OpNum++]);
3975       unsigned CCInfo = Record[OpNum++];
3976       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3977       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3978 
3979       FunctionType *FTy = nullptr;
3980       if (CCInfo >> 13 & 1 &&
3981           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3982         return error("Explicit invoke type is not a function type");
3983 
3984       Value *Callee;
3985       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3986         return error("Invalid record");
3987 
3988       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3989       if (!CalleeTy)
3990         return error("Callee is not a pointer");
3991       if (!FTy) {
3992         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3993         if (!FTy)
3994           return error("Callee is not of pointer to function type");
3995       } else if (CalleeTy->getElementType() != FTy)
3996         return error("Explicit invoke type does not match pointee type of "
3997                      "callee operand");
3998       if (Record.size() < FTy->getNumParams() + OpNum)
3999         return error("Insufficient operands to call");
4000 
4001       SmallVector<Value*, 16> Ops;
4002       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4003         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4004                                FTy->getParamType(i)));
4005         if (!Ops.back())
4006           return error("Invalid record");
4007       }
4008 
4009       if (!FTy->isVarArg()) {
4010         if (Record.size() != OpNum)
4011           return error("Invalid record");
4012       } else {
4013         // Read type/value pairs for varargs params.
4014         while (OpNum != Record.size()) {
4015           Value *Op;
4016           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4017             return error("Invalid record");
4018           Ops.push_back(Op);
4019         }
4020       }
4021 
4022       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4023       OperandBundles.clear();
4024       InstructionList.push_back(I);
4025       cast<InvokeInst>(I)->setCallingConv(
4026           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4027       cast<InvokeInst>(I)->setAttributes(PAL);
4028       break;
4029     }
4030     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4031       unsigned Idx = 0;
4032       Value *Val = nullptr;
4033       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4034         return error("Invalid record");
4035       I = ResumeInst::Create(Val);
4036       InstructionList.push_back(I);
4037       break;
4038     }
4039     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4040       I = new UnreachableInst(Context);
4041       InstructionList.push_back(I);
4042       break;
4043     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4044       if (Record.size() < 1 || ((Record.size()-1)&1))
4045         return error("Invalid record");
4046       Type *Ty = getTypeByID(Record[0]);
4047       if (!Ty)
4048         return error("Invalid record");
4049 
4050       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4051       InstructionList.push_back(PN);
4052 
4053       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4054         Value *V;
4055         // With the new function encoding, it is possible that operands have
4056         // negative IDs (for forward references).  Use a signed VBR
4057         // representation to keep the encoding small.
4058         if (UseRelativeIDs)
4059           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4060         else
4061           V = getValue(Record, 1+i, NextValueNo, Ty);
4062         BasicBlock *BB = getBasicBlock(Record[2+i]);
4063         if (!V || !BB)
4064           return error("Invalid record");
4065         PN->addIncoming(V, BB);
4066       }
4067       I = PN;
4068       break;
4069     }
4070 
4071     case bitc::FUNC_CODE_INST_LANDINGPAD:
4072     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4073       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4074       unsigned Idx = 0;
4075       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4076         if (Record.size() < 3)
4077           return error("Invalid record");
4078       } else {
4079         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4080         if (Record.size() < 4)
4081           return error("Invalid record");
4082       }
4083       Type *Ty = getTypeByID(Record[Idx++]);
4084       if (!Ty)
4085         return error("Invalid record");
4086       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4087         Value *PersFn = nullptr;
4088         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4089           return error("Invalid record");
4090 
4091         if (!F->hasPersonalityFn())
4092           F->setPersonalityFn(cast<Constant>(PersFn));
4093         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4094           return error("Personality function mismatch");
4095       }
4096 
4097       bool IsCleanup = !!Record[Idx++];
4098       unsigned NumClauses = Record[Idx++];
4099       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4100       LP->setCleanup(IsCleanup);
4101       for (unsigned J = 0; J != NumClauses; ++J) {
4102         LandingPadInst::ClauseType CT =
4103           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4104         Value *Val;
4105 
4106         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4107           delete LP;
4108           return error("Invalid record");
4109         }
4110 
4111         assert((CT != LandingPadInst::Catch ||
4112                 !isa<ArrayType>(Val->getType())) &&
4113                "Catch clause has a invalid type!");
4114         assert((CT != LandingPadInst::Filter ||
4115                 isa<ArrayType>(Val->getType())) &&
4116                "Filter clause has invalid type!");
4117         LP->addClause(cast<Constant>(Val));
4118       }
4119 
4120       I = LP;
4121       InstructionList.push_back(I);
4122       break;
4123     }
4124 
4125     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4126       if (Record.size() != 4)
4127         return error("Invalid record");
4128       uint64_t AlignRecord = Record[3];
4129       const uint64_t InAllocaMask = uint64_t(1) << 5;
4130       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4131       const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4132       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4133                                 SwiftErrorMask;
4134       bool InAlloca = AlignRecord & InAllocaMask;
4135       bool SwiftError = AlignRecord & SwiftErrorMask;
4136       Type *Ty = getTypeByID(Record[0]);
4137       if ((AlignRecord & ExplicitTypeMask) == 0) {
4138         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4139         if (!PTy)
4140           return error("Old-style alloca with a non-pointer type");
4141         Ty = PTy->getElementType();
4142       }
4143       Type *OpTy = getTypeByID(Record[1]);
4144       Value *Size = getFnValueByID(Record[2], OpTy);
4145       unsigned Align;
4146       if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4147         return Err;
4148       }
4149       if (!Ty || !Size)
4150         return error("Invalid record");
4151 
4152       // FIXME: Make this an optional field.
4153       const DataLayout &DL = TheModule->getDataLayout();
4154       unsigned AS = DL.getAllocaAddrSpace();
4155 
4156       AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
4157       AI->setUsedWithInAlloca(InAlloca);
4158       AI->setSwiftError(SwiftError);
4159       I = AI;
4160       InstructionList.push_back(I);
4161       break;
4162     }
4163     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4164       unsigned OpNum = 0;
4165       Value *Op;
4166       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4167           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4168         return error("Invalid record");
4169 
4170       Type *Ty = nullptr;
4171       if (OpNum + 3 == Record.size())
4172         Ty = getTypeByID(Record[OpNum++]);
4173       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4174         return Err;
4175       if (!Ty)
4176         Ty = cast<PointerType>(Op->getType())->getElementType();
4177 
4178       unsigned Align;
4179       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4180         return Err;
4181       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4182 
4183       InstructionList.push_back(I);
4184       break;
4185     }
4186     case bitc::FUNC_CODE_INST_LOADATOMIC: {
4187        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4188       unsigned OpNum = 0;
4189       Value *Op;
4190       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4191           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4192         return error("Invalid record");
4193 
4194       Type *Ty = nullptr;
4195       if (OpNum + 5 == Record.size())
4196         Ty = getTypeByID(Record[OpNum++]);
4197       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4198         return Err;
4199       if (!Ty)
4200         Ty = cast<PointerType>(Op->getType())->getElementType();
4201 
4202       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4203       if (Ordering == AtomicOrdering::NotAtomic ||
4204           Ordering == AtomicOrdering::Release ||
4205           Ordering == AtomicOrdering::AcquireRelease)
4206         return error("Invalid record");
4207       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4208         return error("Invalid record");
4209       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4210 
4211       unsigned Align;
4212       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4213         return Err;
4214       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4215 
4216       InstructionList.push_back(I);
4217       break;
4218     }
4219     case bitc::FUNC_CODE_INST_STORE:
4220     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4221       unsigned OpNum = 0;
4222       Value *Val, *Ptr;
4223       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4224           (BitCode == bitc::FUNC_CODE_INST_STORE
4225                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4226                : popValue(Record, OpNum, NextValueNo,
4227                           cast<PointerType>(Ptr->getType())->getElementType(),
4228                           Val)) ||
4229           OpNum + 2 != Record.size())
4230         return error("Invalid record");
4231 
4232       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4233         return Err;
4234       unsigned Align;
4235       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4236         return Err;
4237       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4238       InstructionList.push_back(I);
4239       break;
4240     }
4241     case bitc::FUNC_CODE_INST_STOREATOMIC:
4242     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4243       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4244       unsigned OpNum = 0;
4245       Value *Val, *Ptr;
4246       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4247           !isa<PointerType>(Ptr->getType()) ||
4248           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4249                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4250                : popValue(Record, OpNum, NextValueNo,
4251                           cast<PointerType>(Ptr->getType())->getElementType(),
4252                           Val)) ||
4253           OpNum + 4 != Record.size())
4254         return error("Invalid record");
4255 
4256       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4257         return Err;
4258       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4259       if (Ordering == AtomicOrdering::NotAtomic ||
4260           Ordering == AtomicOrdering::Acquire ||
4261           Ordering == AtomicOrdering::AcquireRelease)
4262         return error("Invalid record");
4263       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4264       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4265         return error("Invalid record");
4266 
4267       unsigned Align;
4268       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4269         return Err;
4270       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4271       InstructionList.push_back(I);
4272       break;
4273     }
4274     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4275     case bitc::FUNC_CODE_INST_CMPXCHG: {
4276       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4277       //          failureordering?, isweak?]
4278       unsigned OpNum = 0;
4279       Value *Ptr, *Cmp, *New;
4280       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4281           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4282                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4283                : popValue(Record, OpNum, NextValueNo,
4284                           cast<PointerType>(Ptr->getType())->getElementType(),
4285                           Cmp)) ||
4286           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4287           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4288         return error("Invalid record");
4289       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4290       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4291           SuccessOrdering == AtomicOrdering::Unordered)
4292         return error("Invalid record");
4293       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4294 
4295       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4296         return Err;
4297       AtomicOrdering FailureOrdering;
4298       if (Record.size() < 7)
4299         FailureOrdering =
4300             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4301       else
4302         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4303 
4304       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4305                                 SynchScope);
4306       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4307 
4308       if (Record.size() < 8) {
4309         // Before weak cmpxchgs existed, the instruction simply returned the
4310         // value loaded from memory, so bitcode files from that era will be
4311         // expecting the first component of a modern cmpxchg.
4312         CurBB->getInstList().push_back(I);
4313         I = ExtractValueInst::Create(I, 0);
4314       } else {
4315         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4316       }
4317 
4318       InstructionList.push_back(I);
4319       break;
4320     }
4321     case bitc::FUNC_CODE_INST_ATOMICRMW: {
4322       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4323       unsigned OpNum = 0;
4324       Value *Ptr, *Val;
4325       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4326           !isa<PointerType>(Ptr->getType()) ||
4327           popValue(Record, OpNum, NextValueNo,
4328                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4329           OpNum+4 != Record.size())
4330         return error("Invalid record");
4331       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4332       if (Operation < AtomicRMWInst::FIRST_BINOP ||
4333           Operation > AtomicRMWInst::LAST_BINOP)
4334         return error("Invalid record");
4335       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4336       if (Ordering == AtomicOrdering::NotAtomic ||
4337           Ordering == AtomicOrdering::Unordered)
4338         return error("Invalid record");
4339       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4340       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4341       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4342       InstructionList.push_back(I);
4343       break;
4344     }
4345     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4346       if (2 != Record.size())
4347         return error("Invalid record");
4348       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4349       if (Ordering == AtomicOrdering::NotAtomic ||
4350           Ordering == AtomicOrdering::Unordered ||
4351           Ordering == AtomicOrdering::Monotonic)
4352         return error("Invalid record");
4353       SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4354       I = new FenceInst(Context, Ordering, SynchScope);
4355       InstructionList.push_back(I);
4356       break;
4357     }
4358     case bitc::FUNC_CODE_INST_CALL: {
4359       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4360       if (Record.size() < 3)
4361         return error("Invalid record");
4362 
4363       unsigned OpNum = 0;
4364       AttributeList PAL = getAttributes(Record[OpNum++]);
4365       unsigned CCInfo = Record[OpNum++];
4366 
4367       FastMathFlags FMF;
4368       if ((CCInfo >> bitc::CALL_FMF) & 1) {
4369         FMF = getDecodedFastMathFlags(Record[OpNum++]);
4370         if (!FMF.any())
4371           return error("Fast math flags indicator set for call with no FMF");
4372       }
4373 
4374       FunctionType *FTy = nullptr;
4375       if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4376           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4377         return error("Explicit call type is not a function type");
4378 
4379       Value *Callee;
4380       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4381         return error("Invalid record");
4382 
4383       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4384       if (!OpTy)
4385         return error("Callee is not a pointer type");
4386       if (!FTy) {
4387         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4388         if (!FTy)
4389           return error("Callee is not of pointer to function type");
4390       } else if (OpTy->getElementType() != FTy)
4391         return error("Explicit call type does not match pointee type of "
4392                      "callee operand");
4393       if (Record.size() < FTy->getNumParams() + OpNum)
4394         return error("Insufficient operands to call");
4395 
4396       SmallVector<Value*, 16> Args;
4397       // Read the fixed params.
4398       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4399         if (FTy->getParamType(i)->isLabelTy())
4400           Args.push_back(getBasicBlock(Record[OpNum]));
4401         else
4402           Args.push_back(getValue(Record, OpNum, NextValueNo,
4403                                   FTy->getParamType(i)));
4404         if (!Args.back())
4405           return error("Invalid record");
4406       }
4407 
4408       // Read type/value pairs for varargs params.
4409       if (!FTy->isVarArg()) {
4410         if (OpNum != Record.size())
4411           return error("Invalid record");
4412       } else {
4413         while (OpNum != Record.size()) {
4414           Value *Op;
4415           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4416             return error("Invalid record");
4417           Args.push_back(Op);
4418         }
4419       }
4420 
4421       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4422       OperandBundles.clear();
4423       InstructionList.push_back(I);
4424       cast<CallInst>(I)->setCallingConv(
4425           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4426       CallInst::TailCallKind TCK = CallInst::TCK_None;
4427       if (CCInfo & 1 << bitc::CALL_TAIL)
4428         TCK = CallInst::TCK_Tail;
4429       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
4430         TCK = CallInst::TCK_MustTail;
4431       if (CCInfo & (1 << bitc::CALL_NOTAIL))
4432         TCK = CallInst::TCK_NoTail;
4433       cast<CallInst>(I)->setTailCallKind(TCK);
4434       cast<CallInst>(I)->setAttributes(PAL);
4435       if (FMF.any()) {
4436         if (!isa<FPMathOperator>(I))
4437           return error("Fast-math-flags specified for call without "
4438                        "floating-point scalar or vector return type");
4439         I->setFastMathFlags(FMF);
4440       }
4441       break;
4442     }
4443     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4444       if (Record.size() < 3)
4445         return error("Invalid record");
4446       Type *OpTy = getTypeByID(Record[0]);
4447       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4448       Type *ResTy = getTypeByID(Record[2]);
4449       if (!OpTy || !Op || !ResTy)
4450         return error("Invalid record");
4451       I = new VAArgInst(Op, ResTy);
4452       InstructionList.push_back(I);
4453       break;
4454     }
4455 
4456     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
4457       // A call or an invoke can be optionally prefixed with some variable
4458       // number of operand bundle blocks.  These blocks are read into
4459       // OperandBundles and consumed at the next call or invoke instruction.
4460 
4461       if (Record.size() < 1 || Record[0] >= BundleTags.size())
4462         return error("Invalid record");
4463 
4464       std::vector<Value *> Inputs;
4465 
4466       unsigned OpNum = 1;
4467       while (OpNum != Record.size()) {
4468         Value *Op;
4469         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4470           return error("Invalid record");
4471         Inputs.push_back(Op);
4472       }
4473 
4474       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4475       continue;
4476     }
4477     }
4478 
4479     // Add instruction to end of current BB.  If there is no current BB, reject
4480     // this file.
4481     if (!CurBB) {
4482       delete I;
4483       return error("Invalid instruction with no BB");
4484     }
4485     if (!OperandBundles.empty()) {
4486       delete I;
4487       return error("Operand bundles found with no consumer");
4488     }
4489     CurBB->getInstList().push_back(I);
4490 
4491     // If this was a terminator instruction, move to the next block.
4492     if (isa<TerminatorInst>(I)) {
4493       ++CurBBNo;
4494       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4495     }
4496 
4497     // Non-void values get registered in the value table for future use.
4498     if (I && !I->getType()->isVoidTy())
4499       ValueList.assignValue(I, NextValueNo++);
4500   }
4501 
4502 OutOfRecordLoop:
4503 
4504   if (!OperandBundles.empty())
4505     return error("Operand bundles found with no consumer");
4506 
4507   // Check the function list for unresolved values.
4508   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4509     if (!A->getParent()) {
4510       // We found at least one unresolved value.  Nuke them all to avoid leaks.
4511       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4512         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4513           A->replaceAllUsesWith(UndefValue::get(A->getType()));
4514           delete A;
4515         }
4516       }
4517       return error("Never resolved value found in function");
4518     }
4519   }
4520 
4521   // Unexpected unresolved metadata about to be dropped.
4522   if (MDLoader->hasFwdRefs())
4523     return error("Invalid function metadata: outgoing forward refs");
4524 
4525   // Trim the value list down to the size it was before we parsed this function.
4526   ValueList.shrinkTo(ModuleValueListSize);
4527   MDLoader->shrinkTo(ModuleMDLoaderSize);
4528   std::vector<BasicBlock*>().swap(FunctionBBs);
4529   return Error::success();
4530 }
4531 
4532 /// Find the function body in the bitcode stream
4533 Error BitcodeReader::findFunctionInStream(
4534     Function *F,
4535     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4536   while (DeferredFunctionInfoIterator->second == 0) {
4537     // This is the fallback handling for the old format bitcode that
4538     // didn't contain the function index in the VST, or when we have
4539     // an anonymous function which would not have a VST entry.
4540     // Assert that we have one of those two cases.
4541     assert(VSTOffset == 0 || !F->hasName());
4542     // Parse the next body in the stream and set its position in the
4543     // DeferredFunctionInfo map.
4544     if (Error Err = rememberAndSkipFunctionBodies())
4545       return Err;
4546   }
4547   return Error::success();
4548 }
4549 
4550 //===----------------------------------------------------------------------===//
4551 // GVMaterializer implementation
4552 //===----------------------------------------------------------------------===//
4553 
4554 Error BitcodeReader::materialize(GlobalValue *GV) {
4555   Function *F = dyn_cast<Function>(GV);
4556   // If it's not a function or is already material, ignore the request.
4557   if (!F || !F->isMaterializable())
4558     return Error::success();
4559 
4560   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4561   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4562   // If its position is recorded as 0, its body is somewhere in the stream
4563   // but we haven't seen it yet.
4564   if (DFII->second == 0)
4565     if (Error Err = findFunctionInStream(F, DFII))
4566       return Err;
4567 
4568   // Materialize metadata before parsing any function bodies.
4569   if (Error Err = materializeMetadata())
4570     return Err;
4571 
4572   // Move the bit stream to the saved position of the deferred function body.
4573   Stream.JumpToBit(DFII->second);
4574 
4575   if (Error Err = parseFunctionBody(F))
4576     return Err;
4577   F->setIsMaterializable(false);
4578 
4579   if (StripDebugInfo)
4580     stripDebugInfo(*F);
4581 
4582   // Upgrade any old intrinsic calls in the function.
4583   for (auto &I : UpgradedIntrinsics) {
4584     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4585          UI != UE;) {
4586       User *U = *UI;
4587       ++UI;
4588       if (CallInst *CI = dyn_cast<CallInst>(U))
4589         UpgradeIntrinsicCall(CI, I.second);
4590     }
4591   }
4592 
4593   // Update calls to the remangled intrinsics
4594   for (auto &I : RemangledIntrinsics)
4595     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4596          UI != UE;)
4597       // Don't expect any other users than call sites
4598       CallSite(*UI++).setCalledFunction(I.second);
4599 
4600   // Finish fn->subprogram upgrade for materialized functions.
4601   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
4602     F->setSubprogram(SP);
4603 
4604   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4605   if (!MDLoader->isStrippingTBAA()) {
4606     for (auto &I : instructions(F)) {
4607       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4608       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4609         continue;
4610       MDLoader->setStripTBAA(true);
4611       stripTBAA(F->getParent());
4612     }
4613   }
4614 
4615   // Bring in any functions that this function forward-referenced via
4616   // blockaddresses.
4617   return materializeForwardReferencedFunctions();
4618 }
4619 
4620 Error BitcodeReader::materializeModule() {
4621   if (Error Err = materializeMetadata())
4622     return Err;
4623 
4624   // Promise to materialize all forward references.
4625   WillMaterializeAllForwardRefs = true;
4626 
4627   // Iterate over the module, deserializing any functions that are still on
4628   // disk.
4629   for (Function &F : *TheModule) {
4630     if (Error Err = materialize(&F))
4631       return Err;
4632   }
4633   // At this point, if there are any function bodies, parse the rest of
4634   // the bits in the module past the last function block we have recorded
4635   // through either lazy scanning or the VST.
4636   if (LastFunctionBlockBit || NextUnreadBit)
4637     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4638                                     ? LastFunctionBlockBit
4639                                     : NextUnreadBit))
4640       return Err;
4641 
4642   // Check that all block address forward references got resolved (as we
4643   // promised above).
4644   if (!BasicBlockFwdRefs.empty())
4645     return error("Never resolved function from blockaddress");
4646 
4647   // Upgrade any intrinsic calls that slipped through (should not happen!) and
4648   // delete the old functions to clean up. We can't do this unless the entire
4649   // module is materialized because there could always be another function body
4650   // with calls to the old function.
4651   for (auto &I : UpgradedIntrinsics) {
4652     for (auto *U : I.first->users()) {
4653       if (CallInst *CI = dyn_cast<CallInst>(U))
4654         UpgradeIntrinsicCall(CI, I.second);
4655     }
4656     if (!I.first->use_empty())
4657       I.first->replaceAllUsesWith(I.second);
4658     I.first->eraseFromParent();
4659   }
4660   UpgradedIntrinsics.clear();
4661   // Do the same for remangled intrinsics
4662   for (auto &I : RemangledIntrinsics) {
4663     I.first->replaceAllUsesWith(I.second);
4664     I.first->eraseFromParent();
4665   }
4666   RemangledIntrinsics.clear();
4667 
4668   UpgradeDebugInfo(*TheModule);
4669 
4670   UpgradeModuleFlags(*TheModule);
4671   return Error::success();
4672 }
4673 
4674 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4675   return IdentifiedStructTypes;
4676 }
4677 
4678 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4679     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex)
4680     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex) {}
4681 
4682 std::pair<GlobalValue::GUID, GlobalValue::GUID>
4683 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
4684   auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
4685   assert(VGI != ValueIdToCallGraphGUIDMap.end());
4686   return VGI->second;
4687 }
4688 
4689 void ModuleSummaryIndexBitcodeReader::setValueGUID(
4690     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
4691     StringRef SourceFileName) {
4692   std::string GlobalId =
4693       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4694   auto ValueGUID = GlobalValue::getGUID(GlobalId);
4695   auto OriginalNameID = ValueGUID;
4696   if (GlobalValue::isLocalLinkage(Linkage))
4697     OriginalNameID = GlobalValue::getGUID(ValueName);
4698   if (PrintSummaryGUIDs)
4699     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4700            << ValueName << "\n";
4701   ValueIdToCallGraphGUIDMap[ValueID] =
4702       std::make_pair(ValueGUID, OriginalNameID);
4703 }
4704 
4705 // Specialized value symbol table parser used when reading module index
4706 // blocks where we don't actually create global values. The parsed information
4707 // is saved in the bitcode reader for use when later parsing summaries.
4708 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
4709     uint64_t Offset,
4710     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
4711   // With a strtab the VST is not required to parse the summary.
4712   if (UseStrtab)
4713     return Error::success();
4714 
4715   assert(Offset > 0 && "Expected non-zero VST offset");
4716   uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4717 
4718   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
4719     return error("Invalid record");
4720 
4721   SmallVector<uint64_t, 64> Record;
4722 
4723   // Read all the records for this value table.
4724   SmallString<128> ValueName;
4725 
4726   while (true) {
4727     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4728 
4729     switch (Entry.Kind) {
4730     case BitstreamEntry::SubBlock: // Handled for us already.
4731     case BitstreamEntry::Error:
4732       return error("Malformed block");
4733     case BitstreamEntry::EndBlock:
4734       // Done parsing VST, jump back to wherever we came from.
4735       Stream.JumpToBit(CurrentBit);
4736       return Error::success();
4737     case BitstreamEntry::Record:
4738       // The interesting case.
4739       break;
4740     }
4741 
4742     // Read a record.
4743     Record.clear();
4744     switch (Stream.readRecord(Entry.ID, Record)) {
4745     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4746       break;
4747     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4748       if (convertToString(Record, 1, ValueName))
4749         return error("Invalid record");
4750       unsigned ValueID = Record[0];
4751       assert(!SourceFileName.empty());
4752       auto VLI = ValueIdToLinkageMap.find(ValueID);
4753       assert(VLI != ValueIdToLinkageMap.end() &&
4754              "No linkage found for VST entry?");
4755       auto Linkage = VLI->second;
4756       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4757       ValueName.clear();
4758       break;
4759     }
4760     case bitc::VST_CODE_FNENTRY: {
4761       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
4762       if (convertToString(Record, 2, ValueName))
4763         return error("Invalid record");
4764       unsigned ValueID = Record[0];
4765       assert(!SourceFileName.empty());
4766       auto VLI = ValueIdToLinkageMap.find(ValueID);
4767       assert(VLI != ValueIdToLinkageMap.end() &&
4768              "No linkage found for VST entry?");
4769       auto Linkage = VLI->second;
4770       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
4771       ValueName.clear();
4772       break;
4773     }
4774     case bitc::VST_CODE_COMBINED_ENTRY: {
4775       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4776       unsigned ValueID = Record[0];
4777       GlobalValue::GUID RefGUID = Record[1];
4778       // The "original name", which is the second value of the pair will be
4779       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
4780       ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
4781       break;
4782     }
4783     }
4784   }
4785 }
4786 
4787 // Parse just the blocks needed for building the index out of the module.
4788 // At the end of this routine the module Index is populated with a map
4789 // from global value id to GlobalValueSummary objects.
4790 Error ModuleSummaryIndexBitcodeReader::parseModule(StringRef ModulePath) {
4791   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4792     return error("Invalid record");
4793 
4794   SmallVector<uint64_t, 64> Record;
4795   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
4796   unsigned ValueId = 0;
4797 
4798   // Read the index for this module.
4799   while (true) {
4800     BitstreamEntry Entry = Stream.advance();
4801 
4802     switch (Entry.Kind) {
4803     case BitstreamEntry::Error:
4804       return error("Malformed block");
4805     case BitstreamEntry::EndBlock:
4806       return Error::success();
4807 
4808     case BitstreamEntry::SubBlock:
4809       switch (Entry.ID) {
4810       default: // Skip unknown content.
4811         if (Stream.SkipBlock())
4812           return error("Invalid record");
4813         break;
4814       case bitc::BLOCKINFO_BLOCK_ID:
4815         // Need to parse these to get abbrev ids (e.g. for VST)
4816         if (readBlockInfo())
4817           return error("Malformed block");
4818         break;
4819       case bitc::VALUE_SYMTAB_BLOCK_ID:
4820         // Should have been parsed earlier via VSTOffset, unless there
4821         // is no summary section.
4822         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4823                 !SeenGlobalValSummary) &&
4824                "Expected early VST parse via VSTOffset record");
4825         if (Stream.SkipBlock())
4826           return error("Invalid record");
4827         break;
4828       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
4829         assert(!SeenValueSymbolTable &&
4830                "Already read VST when parsing summary block?");
4831         // We might not have a VST if there were no values in the
4832         // summary. An empty summary block generated when we are
4833         // performing ThinLTO compiles so we don't later invoke
4834         // the regular LTO process on them.
4835         if (VSTOffset > 0) {
4836           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4837             return Err;
4838           SeenValueSymbolTable = true;
4839         }
4840         SeenGlobalValSummary = true;
4841         if (Error Err = parseEntireSummary(ModulePath))
4842           return Err;
4843         break;
4844       case bitc::MODULE_STRTAB_BLOCK_ID:
4845         if (Error Err = parseModuleStringTable())
4846           return Err;
4847         break;
4848       }
4849       continue;
4850 
4851     case BitstreamEntry::Record: {
4852         Record.clear();
4853         auto BitCode = Stream.readRecord(Entry.ID, Record);
4854         switch (BitCode) {
4855         default:
4856           break; // Default behavior, ignore unknown content.
4857         case bitc::MODULE_CODE_VERSION: {
4858           if (Error Err = parseVersionRecord(Record).takeError())
4859             return Err;
4860           break;
4861         }
4862         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4863         case bitc::MODULE_CODE_SOURCE_FILENAME: {
4864           SmallString<128> ValueName;
4865           if (convertToString(Record, 0, ValueName))
4866             return error("Invalid record");
4867           SourceFileName = ValueName.c_str();
4868           break;
4869         }
4870         /// MODULE_CODE_HASH: [5*i32]
4871         case bitc::MODULE_CODE_HASH: {
4872           if (Record.size() != 5)
4873             return error("Invalid hash length " + Twine(Record.size()).str());
4874           if (TheIndex.modulePaths().empty())
4875             // We always seed the index with the module.
4876             TheIndex.addModulePath(ModulePath, 0);
4877           if (TheIndex.modulePaths().size() != 1)
4878             return error("Don't expect multiple modules defined?");
4879           auto &Hash = TheIndex.modulePaths().begin()->second.second;
4880           int Pos = 0;
4881           for (auto &Val : Record) {
4882             assert(!(Val >> 32) && "Unexpected high bits set");
4883             Hash[Pos++] = Val;
4884           }
4885           break;
4886         }
4887         /// MODULE_CODE_VSTOFFSET: [offset]
4888         case bitc::MODULE_CODE_VSTOFFSET:
4889           if (Record.size() < 1)
4890             return error("Invalid record");
4891           // Note that we subtract 1 here because the offset is relative to one
4892           // word before the start of the identification or module block, which
4893           // was historically always the start of the regular bitcode header.
4894           VSTOffset = Record[0] - 1;
4895           break;
4896         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
4897         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
4898         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
4899         // v2: [strtab offset, strtab size, v1]
4900         case bitc::MODULE_CODE_GLOBALVAR:
4901         case bitc::MODULE_CODE_FUNCTION:
4902         case bitc::MODULE_CODE_ALIAS: {
4903           StringRef Name;
4904           ArrayRef<uint64_t> GVRecord;
4905           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
4906           if (GVRecord.size() <= 3)
4907             return error("Invalid record");
4908           uint64_t RawLinkage = GVRecord[3];
4909           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
4910           if (!UseStrtab) {
4911             ValueIdToLinkageMap[ValueId++] = Linkage;
4912             break;
4913           }
4914 
4915           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
4916           break;
4917         }
4918         }
4919       }
4920       continue;
4921     }
4922   }
4923 }
4924 
4925 std::vector<ValueInfo>
4926 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
4927   std::vector<ValueInfo> Ret;
4928   Ret.reserve(Record.size());
4929   for (uint64_t RefValueId : Record)
4930     Ret.push_back(getGUIDFromValueId(RefValueId).first);
4931   return Ret;
4932 }
4933 
4934 std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
4935     ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
4936   std::vector<FunctionSummary::EdgeTy> Ret;
4937   Ret.reserve(Record.size());
4938   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
4939     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
4940     GlobalValue::GUID CalleeGUID = getGUIDFromValueId(Record[I]).first;
4941     if (IsOldProfileFormat) {
4942       I += 1; // Skip old callsitecount field
4943       if (HasProfile)
4944         I += 1; // Skip old profilecount field
4945     } else if (HasProfile)
4946       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
4947     Ret.push_back(FunctionSummary::EdgeTy{CalleeGUID, CalleeInfo{Hotness}});
4948   }
4949   return Ret;
4950 }
4951 
4952 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
4953 // objects in the index.
4954 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
4955     StringRef ModulePath) {
4956   if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
4957     return error("Invalid record");
4958   SmallVector<uint64_t, 64> Record;
4959 
4960   // Parse version
4961   {
4962     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4963     if (Entry.Kind != BitstreamEntry::Record)
4964       return error("Invalid Summary Block: record for version expected");
4965     if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
4966       return error("Invalid Summary Block: version expected");
4967   }
4968   const uint64_t Version = Record[0];
4969   const bool IsOldProfileFormat = Version == 1;
4970   if (Version < 1 || Version > 3)
4971     return error("Invalid summary version " + Twine(Version) +
4972                  ", 1, 2 or 3 expected");
4973   Record.clear();
4974 
4975   // Keep around the last seen summary to be used when we see an optional
4976   // "OriginalName" attachement.
4977   GlobalValueSummary *LastSeenSummary = nullptr;
4978   GlobalValue::GUID LastSeenGUID = 0;
4979 
4980   // We can expect to see any number of type ID information records before
4981   // each function summary records; these variables store the information
4982   // collected so far so that it can be used to create the summary object.
4983   std::vector<GlobalValue::GUID> PendingTypeTests;
4984   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
4985       PendingTypeCheckedLoadVCalls;
4986   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
4987       PendingTypeCheckedLoadConstVCalls;
4988 
4989   while (true) {
4990     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4991 
4992     switch (Entry.Kind) {
4993     case BitstreamEntry::SubBlock: // Handled for us already.
4994     case BitstreamEntry::Error:
4995       return error("Malformed block");
4996     case BitstreamEntry::EndBlock:
4997       return Error::success();
4998     case BitstreamEntry::Record:
4999       // The interesting case.
5000       break;
5001     }
5002 
5003     // Read a record. The record format depends on whether this
5004     // is a per-module index or a combined index file. In the per-module
5005     // case the records contain the associated value's ID for correlation
5006     // with VST entries. In the combined index the correlation is done
5007     // via the bitcode offset of the summary records (which were saved
5008     // in the combined index VST entries). The records also contain
5009     // information used for ThinLTO renaming and importing.
5010     Record.clear();
5011     auto BitCode = Stream.readRecord(Entry.ID, Record);
5012     switch (BitCode) {
5013     default: // Default behavior: ignore.
5014       break;
5015     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
5016       uint64_t ValueID = Record[0];
5017       GlobalValue::GUID RefGUID = Record[1];
5018       ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
5019       break;
5020     }
5021     // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
5022     //                n x (valueid)]
5023     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
5024     //                        numrefs x valueid,
5025     //                        n x (valueid, hotness)]
5026     case bitc::FS_PERMODULE:
5027     case bitc::FS_PERMODULE_PROFILE: {
5028       unsigned ValueID = Record[0];
5029       uint64_t RawFlags = Record[1];
5030       unsigned InstCount = Record[2];
5031       unsigned NumRefs = Record[3];
5032       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5033       // The module path string ref set in the summary must be owned by the
5034       // index's module string table. Since we don't have a module path
5035       // string table section in the per-module index, we create a single
5036       // module path string table entry with an empty (0) ID to take
5037       // ownership.
5038       static int RefListStartIndex = 4;
5039       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5040       assert(Record.size() >= RefListStartIndex + NumRefs &&
5041              "Record size inconsistent with number of references");
5042       std::vector<ValueInfo> Refs = makeRefList(
5043           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5044       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
5045       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5046           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5047           IsOldProfileFormat, HasProfile);
5048       auto FS = llvm::make_unique<FunctionSummary>(
5049           Flags, InstCount, std::move(Refs), std::move(Calls),
5050           std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls),
5051           std::move(PendingTypeCheckedLoadVCalls),
5052           std::move(PendingTypeTestAssumeConstVCalls),
5053           std::move(PendingTypeCheckedLoadConstVCalls));
5054       PendingTypeTests.clear();
5055       PendingTypeTestAssumeVCalls.clear();
5056       PendingTypeCheckedLoadVCalls.clear();
5057       PendingTypeTestAssumeConstVCalls.clear();
5058       PendingTypeCheckedLoadConstVCalls.clear();
5059       auto GUID = getGUIDFromValueId(ValueID);
5060       FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
5061       FS->setOriginalName(GUID.second);
5062       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
5063       break;
5064     }
5065     // FS_ALIAS: [valueid, flags, valueid]
5066     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
5067     // they expect all aliasee summaries to be available.
5068     case bitc::FS_ALIAS: {
5069       unsigned ValueID = Record[0];
5070       uint64_t RawFlags = Record[1];
5071       unsigned AliaseeID = Record[2];
5072       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5073       auto AS =
5074           llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
5075       // The module path string ref set in the summary must be owned by the
5076       // index's module string table. Since we don't have a module path
5077       // string table section in the per-module index, we create a single
5078       // module path string table entry with an empty (0) ID to take
5079       // ownership.
5080       AS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
5081 
5082       GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
5083       auto *AliaseeSummary = TheIndex.getGlobalValueSummary(AliaseeGUID);
5084       if (!AliaseeSummary)
5085         return error("Alias expects aliasee summary to be parsed");
5086       AS->setAliasee(AliaseeSummary);
5087 
5088       auto GUID = getGUIDFromValueId(ValueID);
5089       AS->setOriginalName(GUID.second);
5090       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
5091       break;
5092     }
5093     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
5094     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5095       unsigned ValueID = Record[0];
5096       uint64_t RawFlags = Record[1];
5097       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5098       std::vector<ValueInfo> Refs =
5099           makeRefList(ArrayRef<uint64_t>(Record).slice(2));
5100       auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5101       FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
5102       auto GUID = getGUIDFromValueId(ValueID);
5103       FS->setOriginalName(GUID.second);
5104       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
5105       break;
5106     }
5107     // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
5108     //               numrefs x valueid, n x (valueid)]
5109     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
5110     //                       numrefs x valueid, n x (valueid, hotness)]
5111     case bitc::FS_COMBINED:
5112     case bitc::FS_COMBINED_PROFILE: {
5113       unsigned ValueID = Record[0];
5114       uint64_t ModuleId = Record[1];
5115       uint64_t RawFlags = Record[2];
5116       unsigned InstCount = Record[3];
5117       unsigned NumRefs = Record[4];
5118       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5119       static int RefListStartIndex = 5;
5120       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5121       assert(Record.size() >= RefListStartIndex + NumRefs &&
5122              "Record size inconsistent with number of references");
5123       std::vector<ValueInfo> Refs = makeRefList(
5124           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
5125       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5126       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5127           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5128           IsOldProfileFormat, HasProfile);
5129       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
5130       auto FS = llvm::make_unique<FunctionSummary>(
5131           Flags, InstCount, std::move(Refs), std::move(Edges),
5132           std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls),
5133           std::move(PendingTypeCheckedLoadVCalls),
5134           std::move(PendingTypeTestAssumeConstVCalls),
5135           std::move(PendingTypeCheckedLoadConstVCalls));
5136       PendingTypeTests.clear();
5137       PendingTypeTestAssumeVCalls.clear();
5138       PendingTypeCheckedLoadVCalls.clear();
5139       PendingTypeTestAssumeConstVCalls.clear();
5140       PendingTypeCheckedLoadConstVCalls.clear();
5141       LastSeenSummary = FS.get();
5142       LastSeenGUID = GUID;
5143       FS->setModulePath(ModuleIdMap[ModuleId]);
5144       TheIndex.addGlobalValueSummary(GUID, std::move(FS));
5145       break;
5146     }
5147     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
5148     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5149     // they expect all aliasee summaries to be available.
5150     case bitc::FS_COMBINED_ALIAS: {
5151       unsigned ValueID = Record[0];
5152       uint64_t ModuleId = Record[1];
5153       uint64_t RawFlags = Record[2];
5154       unsigned AliaseeValueId = Record[3];
5155       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5156       auto AS = llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
5157       LastSeenSummary = AS.get();
5158       AS->setModulePath(ModuleIdMap[ModuleId]);
5159 
5160       auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
5161       auto AliaseeInModule =
5162           TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
5163       if (!AliaseeInModule)
5164         return error("Alias expects aliasee summary to be parsed");
5165       AS->setAliasee(AliaseeInModule);
5166 
5167       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
5168       LastSeenGUID = GUID;
5169       TheIndex.addGlobalValueSummary(GUID, std::move(AS));
5170       break;
5171     }
5172     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
5173     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
5174       unsigned ValueID = Record[0];
5175       uint64_t ModuleId = Record[1];
5176       uint64_t RawFlags = Record[2];
5177       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5178       std::vector<ValueInfo> Refs =
5179           makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5180       auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5181       LastSeenSummary = FS.get();
5182       FS->setModulePath(ModuleIdMap[ModuleId]);
5183       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
5184       LastSeenGUID = GUID;
5185       TheIndex.addGlobalValueSummary(GUID, std::move(FS));
5186       break;
5187     }
5188     // FS_COMBINED_ORIGINAL_NAME: [original_name]
5189     case bitc::FS_COMBINED_ORIGINAL_NAME: {
5190       uint64_t OriginalName = Record[0];
5191       if (!LastSeenSummary)
5192         return error("Name attachment that does not follow a combined record");
5193       LastSeenSummary->setOriginalName(OriginalName);
5194       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
5195       // Reset the LastSeenSummary
5196       LastSeenSummary = nullptr;
5197       LastSeenGUID = 0;
5198       break;
5199     }
5200     case bitc::FS_TYPE_TESTS: {
5201       assert(PendingTypeTests.empty());
5202       PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5203                               Record.end());
5204       break;
5205     }
5206     case bitc::FS_TYPE_TEST_ASSUME_VCALLS: {
5207       assert(PendingTypeTestAssumeVCalls.empty());
5208       for (unsigned I = 0; I != Record.size(); I += 2)
5209         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
5210       break;
5211     }
5212     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: {
5213       assert(PendingTypeCheckedLoadVCalls.empty());
5214       for (unsigned I = 0; I != Record.size(); I += 2)
5215         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
5216       break;
5217     }
5218     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: {
5219       PendingTypeTestAssumeConstVCalls.push_back(
5220           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5221       break;
5222     }
5223     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: {
5224       PendingTypeCheckedLoadConstVCalls.push_back(
5225           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
5226       break;
5227     }
5228     }
5229   }
5230   llvm_unreachable("Exit infinite loop");
5231 }
5232 
5233 // Parse the  module string table block into the Index.
5234 // This populates the ModulePathStringTable map in the index.
5235 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5236   if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5237     return error("Invalid record");
5238 
5239   SmallVector<uint64_t, 64> Record;
5240 
5241   SmallString<128> ModulePath;
5242   ModulePathStringTableTy::iterator LastSeenModulePath;
5243 
5244   while (true) {
5245     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5246 
5247     switch (Entry.Kind) {
5248     case BitstreamEntry::SubBlock: // Handled for us already.
5249     case BitstreamEntry::Error:
5250       return error("Malformed block");
5251     case BitstreamEntry::EndBlock:
5252       return Error::success();
5253     case BitstreamEntry::Record:
5254       // The interesting case.
5255       break;
5256     }
5257 
5258     Record.clear();
5259     switch (Stream.readRecord(Entry.ID, Record)) {
5260     default: // Default behavior: ignore.
5261       break;
5262     case bitc::MST_CODE_ENTRY: {
5263       // MST_ENTRY: [modid, namechar x N]
5264       uint64_t ModuleId = Record[0];
5265 
5266       if (convertToString(Record, 1, ModulePath))
5267         return error("Invalid record");
5268 
5269       LastSeenModulePath = TheIndex.addModulePath(ModulePath, ModuleId);
5270       ModuleIdMap[ModuleId] = LastSeenModulePath->first();
5271 
5272       ModulePath.clear();
5273       break;
5274     }
5275     /// MST_CODE_HASH: [5*i32]
5276     case bitc::MST_CODE_HASH: {
5277       if (Record.size() != 5)
5278         return error("Invalid hash length " + Twine(Record.size()).str());
5279       if (LastSeenModulePath == TheIndex.modulePaths().end())
5280         return error("Invalid hash that does not follow a module path");
5281       int Pos = 0;
5282       for (auto &Val : Record) {
5283         assert(!(Val >> 32) && "Unexpected high bits set");
5284         LastSeenModulePath->second.second[Pos++] = Val;
5285       }
5286       // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
5287       LastSeenModulePath = TheIndex.modulePaths().end();
5288       break;
5289     }
5290     }
5291   }
5292   llvm_unreachable("Exit infinite loop");
5293 }
5294 
5295 namespace {
5296 
5297 // FIXME: This class is only here to support the transition to llvm::Error. It
5298 // will be removed once this transition is complete. Clients should prefer to
5299 // deal with the Error value directly, rather than converting to error_code.
5300 class BitcodeErrorCategoryType : public std::error_category {
5301   const char *name() const noexcept override {
5302     return "llvm.bitcode";
5303   }
5304   std::string message(int IE) const override {
5305     BitcodeError E = static_cast<BitcodeError>(IE);
5306     switch (E) {
5307     case BitcodeError::CorruptedBitcode:
5308       return "Corrupted bitcode";
5309     }
5310     llvm_unreachable("Unknown error type!");
5311   }
5312 };
5313 
5314 } // end anonymous namespace
5315 
5316 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5317 
5318 const std::error_category &llvm::BitcodeErrorCategory() {
5319   return *ErrorCategory;
5320 }
5321 
5322 static Expected<StringRef> readStrtab(BitstreamCursor &Stream) {
5323   if (Stream.EnterSubBlock(bitc::STRTAB_BLOCK_ID))
5324     return error("Invalid record");
5325 
5326   StringRef Strtab;
5327   while (1) {
5328     BitstreamEntry Entry = Stream.advance();
5329     switch (Entry.Kind) {
5330     case BitstreamEntry::EndBlock:
5331       return Strtab;
5332 
5333     case BitstreamEntry::Error:
5334       return error("Malformed block");
5335 
5336     case BitstreamEntry::SubBlock:
5337       if (Stream.SkipBlock())
5338         return error("Malformed block");
5339       break;
5340 
5341     case BitstreamEntry::Record:
5342       StringRef Blob;
5343       SmallVector<uint64_t, 1> Record;
5344       if (Stream.readRecord(Entry.ID, Record, &Blob) == bitc::STRTAB_BLOB)
5345         Strtab = Blob;
5346       break;
5347     }
5348   }
5349 }
5350 
5351 //===----------------------------------------------------------------------===//
5352 // External interface
5353 //===----------------------------------------------------------------------===//
5354 
5355 Expected<std::vector<BitcodeModule>>
5356 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
5357   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5358   if (!StreamOrErr)
5359     return StreamOrErr.takeError();
5360   BitstreamCursor &Stream = *StreamOrErr;
5361 
5362   std::vector<BitcodeModule> Modules;
5363   while (true) {
5364     uint64_t BCBegin = Stream.getCurrentByteNo();
5365 
5366     // We may be consuming bitcode from a client that leaves garbage at the end
5367     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5368     // the end that there cannot possibly be another module, stop looking.
5369     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
5370       return Modules;
5371 
5372     BitstreamEntry Entry = Stream.advance();
5373     switch (Entry.Kind) {
5374     case BitstreamEntry::EndBlock:
5375     case BitstreamEntry::Error:
5376       return error("Malformed block");
5377 
5378     case BitstreamEntry::SubBlock: {
5379       uint64_t IdentificationBit = -1ull;
5380       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5381         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5382         if (Stream.SkipBlock())
5383           return error("Malformed block");
5384 
5385         Entry = Stream.advance();
5386         if (Entry.Kind != BitstreamEntry::SubBlock ||
5387             Entry.ID != bitc::MODULE_BLOCK_ID)
5388           return error("Malformed block");
5389       }
5390 
5391       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5392         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5393         if (Stream.SkipBlock())
5394           return error("Malformed block");
5395 
5396         Modules.push_back({Stream.getBitcodeBytes().slice(
5397                                BCBegin, Stream.getCurrentByteNo() - BCBegin),
5398                            Buffer.getBufferIdentifier(), IdentificationBit,
5399                            ModuleBit});
5400         continue;
5401       }
5402 
5403       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
5404         Expected<StringRef> Strtab = readStrtab(Stream);
5405         if (!Strtab)
5406           return Strtab.takeError();
5407         // This string table is used by every preceding bitcode module that does
5408         // not have its own string table. A bitcode file may have multiple
5409         // string tables if it was created by binary concatenation, for example
5410         // with "llvm-cat -b".
5411         for (auto I = Modules.rbegin(), E = Modules.rend(); I != E; ++I) {
5412           if (!I->Strtab.empty())
5413             break;
5414           I->Strtab = *Strtab;
5415         }
5416         continue;
5417       }
5418 
5419       if (Stream.SkipBlock())
5420         return error("Malformed block");
5421       continue;
5422     }
5423     case BitstreamEntry::Record:
5424       Stream.skipRecord(Entry.ID);
5425       continue;
5426     }
5427   }
5428 }
5429 
5430 /// \brief Get a lazy one-at-time loading module from bitcode.
5431 ///
5432 /// This isn't always used in a lazy context.  In particular, it's also used by
5433 /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
5434 /// in forward-referenced functions from block address references.
5435 ///
5436 /// \param[in] MaterializeAll Set to \c true if we should materialize
5437 /// everything.
5438 Expected<std::unique_ptr<Module>>
5439 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
5440                              bool ShouldLazyLoadMetadata, bool IsImporting) {
5441   BitstreamCursor Stream(Buffer);
5442 
5443   std::string ProducerIdentification;
5444   if (IdentificationBit != -1ull) {
5445     Stream.JumpToBit(IdentificationBit);
5446     Expected<std::string> ProducerIdentificationOrErr =
5447         readIdentificationBlock(Stream);
5448     if (!ProducerIdentificationOrErr)
5449       return ProducerIdentificationOrErr.takeError();
5450 
5451     ProducerIdentification = *ProducerIdentificationOrErr;
5452   }
5453 
5454   Stream.JumpToBit(ModuleBit);
5455   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
5456                               Context);
5457 
5458   std::unique_ptr<Module> M =
5459       llvm::make_unique<Module>(ModuleIdentifier, Context);
5460   M->setMaterializer(R);
5461 
5462   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5463   if (Error Err =
5464           R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5465     return std::move(Err);
5466 
5467   if (MaterializeAll) {
5468     // Read in the entire module, and destroy the BitcodeReader.
5469     if (Error Err = M->materializeAll())
5470       return std::move(Err);
5471   } else {
5472     // Resolve forward references from blockaddresses.
5473     if (Error Err = R->materializeForwardReferencedFunctions())
5474       return std::move(Err);
5475   }
5476   return std::move(M);
5477 }
5478 
5479 Expected<std::unique_ptr<Module>>
5480 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5481                              bool IsImporting) {
5482   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
5483 }
5484 
5485 // Parse the specified bitcode buffer, returning the function info index.
5486 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5487   BitstreamCursor Stream(Buffer);
5488   Stream.JumpToBit(ModuleBit);
5489 
5490   auto Index = llvm::make_unique<ModuleSummaryIndex>();
5491   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index);
5492 
5493   if (Error Err = R.parseModule(ModuleIdentifier))
5494     return std::move(Err);
5495 
5496   return std::move(Index);
5497 }
5498 
5499 // Check if the given bitcode buffer contains a global value summary block.
5500 Expected<bool> BitcodeModule::hasSummary() {
5501   BitstreamCursor Stream(Buffer);
5502   Stream.JumpToBit(ModuleBit);
5503 
5504   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5505     return error("Invalid record");
5506 
5507   while (true) {
5508     BitstreamEntry Entry = Stream.advance();
5509 
5510     switch (Entry.Kind) {
5511     case BitstreamEntry::Error:
5512       return error("Malformed block");
5513     case BitstreamEntry::EndBlock:
5514       return false;
5515 
5516     case BitstreamEntry::SubBlock:
5517       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
5518         return true;
5519 
5520       // Ignore other sub-blocks.
5521       if (Stream.SkipBlock())
5522         return error("Malformed block");
5523       continue;
5524 
5525     case BitstreamEntry::Record:
5526       Stream.skipRecord(Entry.ID);
5527       continue;
5528     }
5529   }
5530 }
5531 
5532 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
5533   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
5534   if (!MsOrErr)
5535     return MsOrErr.takeError();
5536 
5537   if (MsOrErr->size() != 1)
5538     return error("Expected a single module");
5539 
5540   return (*MsOrErr)[0];
5541 }
5542 
5543 Expected<std::unique_ptr<Module>>
5544 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
5545                            bool ShouldLazyLoadMetadata, bool IsImporting) {
5546   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5547   if (!BM)
5548     return BM.takeError();
5549 
5550   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
5551 }
5552 
5553 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
5554     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5555     bool ShouldLazyLoadMetadata, bool IsImporting) {
5556   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5557                                      IsImporting);
5558   if (MOrErr)
5559     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5560   return MOrErr;
5561 }
5562 
5563 Expected<std::unique_ptr<Module>>
5564 BitcodeModule::parseModule(LLVMContext &Context) {
5565   return getModuleImpl(Context, true, false, false);
5566   // TODO: Restore the use-lists to the in-memory state when the bitcode was
5567   // written.  We must defer until the Module has been fully materialized.
5568 }
5569 
5570 Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5571                                                          LLVMContext &Context) {
5572   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5573   if (!BM)
5574     return BM.takeError();
5575 
5576   return BM->parseModule(Context);
5577 }
5578 
5579 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
5580   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5581   if (!StreamOrErr)
5582     return StreamOrErr.takeError();
5583 
5584   return readTriple(*StreamOrErr);
5585 }
5586 
5587 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
5588   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5589   if (!StreamOrErr)
5590     return StreamOrErr.takeError();
5591 
5592   return hasObjCCategory(*StreamOrErr);
5593 }
5594 
5595 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
5596   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5597   if (!StreamOrErr)
5598     return StreamOrErr.takeError();
5599 
5600   return readIdentificationCode(*StreamOrErr);
5601 }
5602 
5603 Expected<std::unique_ptr<ModuleSummaryIndex>>
5604 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
5605   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5606   if (!BM)
5607     return BM.takeError();
5608 
5609   return BM->getSummary();
5610 }
5611 
5612 Expected<bool> llvm::hasGlobalValueSummary(MemoryBufferRef Buffer) {
5613   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5614   if (!BM)
5615     return BM.takeError();
5616 
5617   return BM->hasSummary();
5618 }
5619 
5620 Expected<std::unique_ptr<ModuleSummaryIndex>>
5621 llvm::getModuleSummaryIndexForFile(StringRef Path) {
5622   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5623       MemoryBuffer::getFileOrSTDIN(Path);
5624   if (!FileOrErr)
5625     return errorCodeToError(FileOrErr.getError());
5626   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
5627     return nullptr;
5628   return getModuleSummaryIndex(**FileOrErr);
5629 }
5630