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