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