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