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