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