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