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