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