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