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