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