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