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