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