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