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