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