LLVM  9.0.0svn
BitcodeReader.cpp
Go to the documentation of this file.
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 
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"
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"
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"
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"
58 #include "llvm/IR/Operator.h"
59 #include "llvm/IR/Type.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/IR/Verifier.h"
63 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/Compiler.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/Error.h"
69 #include "llvm/Support/ErrorOr.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 
88 using namespace llvm;
89 
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 
95 namespace {
96 
97 enum {
98  SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
99 };
100 
101 } // end anonymous namespace
102 
103 static Error error(const Twine &Message) {
104  return make_error<StringError>(
106 }
107 
108 /// Helper to read the header common to all bitcode files.
110  // Sniff for the signature.
111  if (!Stream.canSkipToPos(4) ||
112  Stream.Read(8) != 'B' ||
113  Stream.Read(8) != 'C' ||
114  Stream.Read(4) != 0x0 ||
115  Stream.Read(4) != 0xC ||
116  Stream.Read(4) != 0xE ||
117  Stream.Read(4) != 0xD)
118  return false;
119  return true;
120 }
121 
123  const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
124  const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
125 
126  if (Buffer.getBufferSize() & 3)
127  return error("Invalid bitcode signature");
128 
129  // If we have a wrapper header, parse it and ignore the non-bc file contents.
130  // The magic number is 0x0B17C0DE stored in little endian.
131  if (isBitcodeWrapper(BufPtr, BufEnd))
132  if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
133  return error("Invalid bitcode wrapper header");
134 
135  BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
136  if (!hasValidBitcodeHeader(Stream))
137  return error("Invalid bitcode signature");
138 
139  return std::move(Stream);
140 }
141 
142 /// Convert a string from a record into an std::string, return true on failure.
143 template <typename StrTy>
144 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
145  StrTy &Result) {
146  if (Idx > Record.size())
147  return true;
148 
149  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
150  Result += (char)Record[i];
151  return false;
152 }
153 
154 // Strip all the TBAA attachment for the module.
155 static void stripTBAA(Module *M) {
156  for (auto &F : *M) {
157  if (F.isMaterializable())
158  continue;
159  for (auto &I : instructions(F))
160  I.setMetadata(LLVMContext::MD_tbaa, nullptr);
161  }
162 }
163 
164 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
165 /// "epoch" encoded in the bitcode, and return the producer name if any.
168  return error("Invalid record");
169 
170  // Read all the records.
172 
173  std::string ProducerIdentification;
174 
175  while (true) {
176  BitstreamEntry Entry = Stream.advance();
177 
178  switch (Entry.Kind) {
179  default:
181  return error("Malformed block");
183  return ProducerIdentification;
185  // The interesting case.
186  break;
187  }
188 
189  // Read a record.
190  Record.clear();
191  unsigned BitCode = Stream.readRecord(Entry.ID, Record);
192  switch (BitCode) {
193  default: // Default behavior: reject
194  return error("Invalid value");
195  case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
196  convertToString(Record, 0, ProducerIdentification);
197  break;
198  case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
199  unsigned epoch = (unsigned)Record[0];
200  if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
201  return error(
202  Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
203  "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
204  }
205  }
206  }
207  }
208 }
209 
211  // We expect a number of well-defined blocks, though we don't necessarily
212  // need to understand them all.
213  while (true) {
214  if (Stream.AtEndOfStream())
215  return "";
216 
217  BitstreamEntry Entry = Stream.advance();
218  switch (Entry.Kind) {
221  return error("Malformed block");
222 
224  if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
225  return readIdentificationBlock(Stream);
226 
227  // Ignore other sub-blocks.
228  if (Stream.SkipBlock())
229  return error("Malformed block");
230  continue;
232  Stream.skipRecord(Entry.ID);
233  continue;
234  }
235  }
236 }
237 
240  return error("Invalid record");
241 
243  // Read all the records for this module.
244 
245  while (true) {
246  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
247 
248  switch (Entry.Kind) {
249  case BitstreamEntry::SubBlock: // Handled for us already.
251  return error("Malformed block");
253  return false;
255  // The interesting case.
256  break;
257  }
258 
259  // Read a record.
260  switch (Stream.readRecord(Entry.ID, Record)) {
261  default:
262  break; // Default behavior, ignore unknown content.
263  case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
264  std::string S;
265  if (convertToString(Record, 0, S))
266  return error("Invalid record");
267  // Check for the i386 and other (x86_64, ARM) conventions
268  if (S.find("__DATA,__objc_catlist") != std::string::npos ||
269  S.find("__OBJC,__category") != std::string::npos)
270  return true;
271  break;
272  }
273  }
274  Record.clear();
275  }
276  llvm_unreachable("Exit infinite loop");
277 }
278 
280  // We expect a number of well-defined blocks, though we don't necessarily
281  // need to understand them all.
282  while (true) {
283  BitstreamEntry Entry = Stream.advance();
284 
285  switch (Entry.Kind) {
287  return error("Malformed block");
289  return false;
290 
292  if (Entry.ID == bitc::MODULE_BLOCK_ID)
293  return hasObjCCategoryInModule(Stream);
294 
295  // Ignore other sub-blocks.
296  if (Stream.SkipBlock())
297  return error("Malformed block");
298  continue;
299 
301  Stream.skipRecord(Entry.ID);
302  continue;
303  }
304  }
305 }
306 
309  return error("Invalid record");
310 
312 
313  std::string Triple;
314 
315  // Read all the records for this module.
316  while (true) {
317  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
318 
319  switch (Entry.Kind) {
320  case BitstreamEntry::SubBlock: // Handled for us already.
322  return error("Malformed block");
324  return Triple;
326  // The interesting case.
327  break;
328  }
329 
330  // Read a record.
331  switch (Stream.readRecord(Entry.ID, Record)) {
332  default: break; // Default behavior, ignore unknown content.
333  case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
334  std::string S;
335  if (convertToString(Record, 0, S))
336  return error("Invalid record");
337  Triple = S;
338  break;
339  }
340  }
341  Record.clear();
342  }
343  llvm_unreachable("Exit infinite loop");
344 }
345 
347  // We expect a number of well-defined blocks, though we don't necessarily
348  // need to understand them all.
349  while (true) {
350  BitstreamEntry Entry = Stream.advance();
351 
352  switch (Entry.Kind) {
354  return error("Malformed block");
356  return "";
357 
359  if (Entry.ID == bitc::MODULE_BLOCK_ID)
360  return readModuleTriple(Stream);
361 
362  // Ignore other sub-blocks.
363  if (Stream.SkipBlock())
364  return error("Malformed block");
365  continue;
366 
368  Stream.skipRecord(Entry.ID);
369  continue;
370  }
371  }
372 }
373 
374 namespace {
375 
376 class BitcodeReaderBase {
377 protected:
378  BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
379  : Stream(std::move(Stream)), Strtab(Strtab) {
380  this->Stream.setBlockInfo(&BlockInfo);
381  }
382 
383  BitstreamBlockInfo BlockInfo;
384  BitstreamCursor Stream;
385  StringRef Strtab;
386 
387  /// In version 2 of the bitcode we store names of global values and comdats in
388  /// a string table rather than in the VST.
389  bool UseStrtab = false;
390 
391  Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
392 
393  /// If this module uses a string table, pop the reference to the string table
394  /// and return the referenced string and the rest of the record. Otherwise
395  /// just return the record itself.
396  std::pair<StringRef, ArrayRef<uint64_t>>
397  readNameFromStrtab(ArrayRef<uint64_t> Record);
398 
399  bool readBlockInfo();
400 
401  // Contains an arbitrary and optional string identifying the bitcode producer
402  std::string ProducerIdentification;
403 
404  Error error(const Twine &Message);
405 };
406 
407 } // end anonymous namespace
408 
409 Error BitcodeReaderBase::error(const Twine &Message) {
410  std::string FullMsg = Message.str();
411  if (!ProducerIdentification.empty())
412  FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
413  LLVM_VERSION_STRING "')";
414  return ::error(FullMsg);
415 }
416 
418 BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
419  if (Record.empty())
420  return error("Invalid record");
421  unsigned ModuleVersion = Record[0];
422  if (ModuleVersion > 2)
423  return error("Invalid value");
424  UseStrtab = ModuleVersion >= 2;
425  return ModuleVersion;
426 }
427 
428 std::pair<StringRef, ArrayRef<uint64_t>>
429 BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
430  if (!UseStrtab)
431  return {"", Record};
432  // Invalid reference. Let the caller complain about the record being empty.
433  if (Record[0] + Record[1] > Strtab.size())
434  return {"", {}};
435  return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
436 }
437 
438 namespace {
439 
440 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
442  Module *TheModule = nullptr;
443  // Next offset to start scanning for lazy parsing of function bodies.
444  uint64_t NextUnreadBit = 0;
445  // Last function offset found in the VST.
446  uint64_t LastFunctionBlockBit = 0;
447  bool SeenValueSymbolTable = false;
448  uint64_t VSTOffset = 0;
449 
450  std::vector<std::string> SectionTable;
451  std::vector<std::string> GCTable;
452 
453  std::vector<Type*> TypeList;
454  BitcodeReaderValueList ValueList;
455  Optional<MetadataLoader> MDLoader;
456  std::vector<Comdat *> ComdatList;
457  SmallVector<Instruction *, 64> InstructionList;
458 
459  std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
460  std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
461  std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
462  std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
463  std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
464 
465  /// The set of attributes by index. Index zero in the file is for null, and
466  /// is thus not represented here. As such all indices are off by one.
467  std::vector<AttributeList> MAttributes;
468 
469  /// The set of attribute groups.
470  std::map<unsigned, AttributeList> MAttributeGroups;
471 
472  /// While parsing a function body, this is a list of the basic blocks for the
473  /// function.
474  std::vector<BasicBlock*> FunctionBBs;
475 
476  // When reading the module header, this list is populated with functions that
477  // have bodies later in the file.
478  std::vector<Function*> FunctionsWithBodies;
479 
480  // When intrinsic functions are encountered which require upgrading they are
481  // stored here with their replacement function.
482  using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
483  UpdatedIntrinsicMap UpgradedIntrinsics;
484  // Intrinsics which were remangled because of types rename
485  UpdatedIntrinsicMap RemangledIntrinsics;
486 
487  // Several operations happen after the module header has been read, but
488  // before function bodies are processed. This keeps track of whether
489  // we've done this yet.
490  bool SeenFirstFunctionBody = false;
491 
492  /// When function bodies are initially scanned, this map contains info about
493  /// where to find deferred function body in the stream.
494  DenseMap<Function*, uint64_t> DeferredFunctionInfo;
495 
496  /// When Metadata block is initially scanned when parsing the module, we may
497  /// choose to defer parsing of the metadata. This vector contains info about
498  /// which Metadata blocks are deferred.
499  std::vector<uint64_t> DeferredMetadataInfo;
500 
501  /// These are basic blocks forward-referenced by block addresses. They are
502  /// inserted lazily into functions when they're loaded. The basic block ID is
503  /// its index into the vector.
505  std::deque<Function *> BasicBlockFwdRefQueue;
506 
507  /// Indicates that we are using a new encoding for instruction operands where
508  /// most operands in the current FUNCTION_BLOCK are encoded relative to the
509  /// instruction number, for a more compact encoding. Some instruction
510  /// operands are not relative to the instruction ID: basic block numbers, and
511  /// types. Once the old style function blocks have been phased out, we would
512  /// not need this flag.
513  bool UseRelativeIDs = false;
514 
515  /// True if all functions will be materialized, negating the need to process
516  /// (e.g.) blockaddress forward references.
517  bool WillMaterializeAllForwardRefs = false;
518 
519  bool StripDebugInfo = false;
520  TBAAVerifier TBAAVerifyHelper;
521 
522  std::vector<std::string> BundleTags;
524 
525 public:
526  BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
527  StringRef ProducerIdentification, LLVMContext &Context);
528 
529  Error materializeForwardReferencedFunctions();
530 
531  Error materialize(GlobalValue *GV) override;
532  Error materializeModule() override;
533  std::vector<StructType *> getIdentifiedStructTypes() const override;
534 
535  /// Main interface to parsing a bitcode buffer.
536  /// \returns true if an error occurred.
537  Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
538  bool IsImporting = false);
539 
540  static uint64_t decodeSignRotatedValue(uint64_t V);
541 
542  /// Materialize any deferred Metadata block.
543  Error materializeMetadata() override;
544 
545  void setStripDebugInfo() override;
546 
547 private:
548  std::vector<StructType *> IdentifiedStructTypes;
549  StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
550  StructType *createIdentifiedStructType(LLVMContext &Context);
551 
552  Type *getTypeByID(unsigned ID);
553 
554  Value *getFnValueByID(unsigned ID, Type *Ty) {
555  if (Ty && Ty->isMetadataTy())
556  return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
557  return ValueList.getValueFwdRef(ID, Ty);
558  }
559 
560  Metadata *getFnMetadataByID(unsigned ID) {
561  return MDLoader->getMetadataFwdRefOrLoad(ID);
562  }
563 
564  BasicBlock *getBasicBlock(unsigned ID) const {
565  if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
566  return FunctionBBs[ID];
567  }
568 
569  AttributeList getAttributes(unsigned i) const {
570  if (i-1 < MAttributes.size())
571  return MAttributes[i-1];
572  return AttributeList();
573  }
574 
575  /// Read a value/type pair out of the specified record from slot 'Slot'.
576  /// Increment Slot past the number of slots used in the record. Return true on
577  /// failure.
578  bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
579  unsigned InstNum, Value *&ResVal) {
580  if (Slot == Record.size()) return true;
581  unsigned ValNo = (unsigned)Record[Slot++];
582  // Adjust the ValNo, if it was encoded relative to the InstNum.
583  if (UseRelativeIDs)
584  ValNo = InstNum - ValNo;
585  if (ValNo < InstNum) {
586  // If this is not a forward reference, just return the value we already
587  // have.
588  ResVal = getFnValueByID(ValNo, nullptr);
589  return ResVal == nullptr;
590  }
591  if (Slot == Record.size())
592  return true;
593 
594  unsigned TypeNo = (unsigned)Record[Slot++];
595  ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
596  return ResVal == nullptr;
597  }
598 
599  /// Read a value out of the specified record from slot 'Slot'. Increment Slot
600  /// past the number of slots used by the value in the record. Return true if
601  /// there is an error.
602  bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
603  unsigned InstNum, Type *Ty, Value *&ResVal) {
604  if (getValue(Record, Slot, InstNum, Ty, ResVal))
605  return true;
606  // All values currently take a single record slot.
607  ++Slot;
608  return false;
609  }
610 
611  /// Like popValue, but does not increment the Slot number.
612  bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
613  unsigned InstNum, Type *Ty, Value *&ResVal) {
614  ResVal = getValue(Record, Slot, InstNum, Ty);
615  return ResVal == nullptr;
616  }
617 
618  /// Version of getValue that returns ResVal directly, or 0 if there is an
619  /// error.
620  Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
621  unsigned InstNum, Type *Ty) {
622  if (Slot == Record.size()) return nullptr;
623  unsigned ValNo = (unsigned)Record[Slot];
624  // Adjust the ValNo, if it was encoded relative to the InstNum.
625  if (UseRelativeIDs)
626  ValNo = InstNum - ValNo;
627  return getFnValueByID(ValNo, Ty);
628  }
629 
630  /// Like getValue, but decodes signed VBRs.
631  Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
632  unsigned InstNum, Type *Ty) {
633  if (Slot == Record.size()) return nullptr;
634  unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
635  // Adjust the ValNo, if it was encoded relative to the InstNum.
636  if (UseRelativeIDs)
637  ValNo = InstNum - ValNo;
638  return getFnValueByID(ValNo, Ty);
639  }
640 
641  /// Converts alignment exponent (i.e. power of two (or zero)) to the
642  /// corresponding alignment to use. If alignment is too large, returns
643  /// a corresponding error code.
644  Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
645  Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
646  Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
647 
648  Error parseComdatRecord(ArrayRef<uint64_t> Record);
649  Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
650  Error parseFunctionRecord(ArrayRef<uint64_t> Record);
651  Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
652  ArrayRef<uint64_t> Record);
653 
654  Error parseAttributeBlock();
655  Error parseAttributeGroupBlock();
656  Error parseTypeTable();
657  Error parseTypeTableBody();
658  Error parseOperandBundleTags();
659  Error parseSyncScopeNames();
660 
661  Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
662  unsigned NameIndex, Triple &TT);
663  void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
664  ArrayRef<uint64_t> Record);
665  Error parseValueSymbolTable(uint64_t Offset = 0);
666  Error parseGlobalValueSymbolTable();
667  Error parseConstants();
668  Error rememberAndSkipFunctionBodies();
669  Error rememberAndSkipFunctionBody();
670  /// Save the positions of the Metadata blocks and skip parsing the blocks.
671  Error rememberAndSkipMetadata();
672  Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
673  Error parseFunctionBody(Function *F);
674  Error globalCleanup();
675  Error resolveGlobalAndIndirectSymbolInits();
676  Error parseUseLists();
677  Error findFunctionInStream(
678  Function *F,
679  DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
680 
681  SyncScope::ID getDecodedSyncScopeID(unsigned Val);
682 };
683 
684 /// Class to manage reading and parsing function summary index bitcode
685 /// files/sections.
686 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
687  /// The module index built during parsing.
688  ModuleSummaryIndex &TheIndex;
689 
690  /// Indicates whether we have encountered a global value summary section
691  /// yet during parsing.
692  bool SeenGlobalValSummary = false;
693 
694  /// Indicates whether we have already parsed the VST, used for error checking.
695  bool SeenValueSymbolTable = false;
696 
697  /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
698  /// Used to enable on-demand parsing of the VST.
699  uint64_t VSTOffset = 0;
700 
701  // Map to save ValueId to ValueInfo association that was recorded in the
702  // ValueSymbolTable. It is used after the VST is parsed to convert
703  // call graph edges read from the function summary from referencing
704  // callees by their ValueId to using the ValueInfo instead, which is how
705  // they are recorded in the summary index being built.
706  // We save a GUID which refers to the same global as the ValueInfo, but
707  // ignoring the linkage, i.e. for values other than local linkage they are
708  // identical.
710  ValueIdToValueInfoMap;
711 
712  /// Map populated during module path string table parsing, from the
713  /// module ID to a string reference owned by the index's module
714  /// path string table, used to correlate with combined index
715  /// summary records.
716  DenseMap<uint64_t, StringRef> ModuleIdMap;
717 
718  /// Original source file name recorded in a bitcode record.
719  std::string SourceFileName;
720 
721  /// The string identifier given to this module by the client, normally the
722  /// path to the bitcode file.
723  StringRef ModulePath;
724 
725  /// For per-module summary indexes, the unique numerical identifier given to
726  /// this module by the client.
727  unsigned ModuleId;
728 
729 public:
730  ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
731  ModuleSummaryIndex &TheIndex,
732  StringRef ModulePath, unsigned ModuleId);
733 
734  Error parseModule();
735 
736 private:
737  void setValueGUID(uint64_t ValueID, StringRef ValueName,
739  StringRef SourceFileName);
740  Error parseValueSymbolTable(
741  uint64_t Offset,
742  DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
743  std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
744  std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
745  bool IsOldProfileFormat,
746  bool HasProfile,
747  bool HasRelBF);
748  Error parseEntireSummary(unsigned ID);
749  Error parseModuleStringTable();
750 
751  std::pair<ValueInfo, GlobalValue::GUID>
752  getValueInfoFromValueId(unsigned ValueId);
753 
754  void addThisModule();
755  ModuleSummaryIndex::ModuleInfo *getThisModule();
756 };
757 
758 } // end anonymous namespace
759 
761  Error Err) {
762  if (Err) {
763  std::error_code EC;
764  handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
765  EC = EIB.convertToErrorCode();
766  Ctx.emitError(EIB.message());
767  });
768  return EC;
769  }
770  return std::error_code();
771 }
772 
773 BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
774  StringRef ProducerIdentification,
776  : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
777  ValueList(Context) {
778  this->ProducerIdentification = ProducerIdentification;
779 }
780 
781 Error BitcodeReader::materializeForwardReferencedFunctions() {
782  if (WillMaterializeAllForwardRefs)
783  return Error::success();
784 
785  // Prevent recursion.
786  WillMaterializeAllForwardRefs = true;
787 
788  while (!BasicBlockFwdRefQueue.empty()) {
789  Function *F = BasicBlockFwdRefQueue.front();
790  BasicBlockFwdRefQueue.pop_front();
791  assert(F && "Expected valid function");
792  if (!BasicBlockFwdRefs.count(F))
793  // Already materialized.
794  continue;
795 
796  // Check for a function that isn't materializable to prevent an infinite
797  // loop. When parsing a blockaddress stored in a global variable, there
798  // isn't a trivial way to check if a function will have a body without a
799  // linear search through FunctionsWithBodies, so just check it here.
800  if (!F->isMaterializable())
801  return error("Never resolved function from blockaddress");
802 
803  // Try to materialize F.
804  if (Error Err = materialize(F))
805  return Err;
806  }
807  assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
808 
809  // Reset state.
810  WillMaterializeAllForwardRefs = false;
811  return Error::success();
812 }
813 
814 //===----------------------------------------------------------------------===//
815 // Helper functions to implement forward reference resolution, etc.
816 //===----------------------------------------------------------------------===//
817 
818 static bool hasImplicitComdat(size_t Val) {
819  switch (Val) {
820  default:
821  return false;
822  case 1: // Old WeakAnyLinkage
823  case 4: // Old LinkOnceAnyLinkage
824  case 10: // Old WeakODRLinkage
825  case 11: // Old LinkOnceODRLinkage
826  return true;
827  }
828 }
829 
831  switch (Val) {
832  default: // Map unknown/new linkages to external
833  case 0:
835  case 2:
837  case 3:
839  case 5:
840  return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
841  case 6:
842  return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
843  case 7:
845  case 8:
847  case 9:
849  case 12:
851  case 13:
852  return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
853  case 14:
854  return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
855  case 15:
856  return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
857  case 1: // Old value with implicit comdat.
858  case 16:
860  case 10: // Old value with implicit comdat.
861  case 17:
863  case 4: // Old value with implicit comdat.
864  case 18:
866  case 11: // Old value with implicit comdat.
867  case 19:
869  }
870 }
871 
872 static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
874  Flags.ReadNone = RawFlags & 0x1;
875  Flags.ReadOnly = (RawFlags >> 1) & 0x1;
876  Flags.NoRecurse = (RawFlags >> 2) & 0x1;
877  Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
878  Flags.NoInline = (RawFlags >> 4) & 0x1;
879  return Flags;
880 }
881 
882 /// Decode the flags for GlobalValue in the summary.
884  uint64_t Version) {
885  // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
886  // like getDecodedLinkage() above. Any future change to the linkage enum and
887  // to getDecodedLinkage() will need to be taken into account here as above.
888  auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
889  RawFlags = RawFlags >> 4;
890  bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
891  // The Live flag wasn't introduced until version 3. For dead stripping
892  // to work correctly on earlier versions, we must conservatively treat all
893  // values as live.
894  bool Live = (RawFlags & 0x2) || Version < 3;
895  bool Local = (RawFlags & 0x4);
896 
897  return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local);
898 }
899 
900 // Decode the flags for GlobalVariable in the summary
902  return GlobalVarSummary::GVarFlags((RawFlags & 0x1) ? true : false);
903 }
904 
906  switch (Val) {
907  default: // Map unknown visibilities to default.
908  case 0: return GlobalValue::DefaultVisibility;
909  case 1: return GlobalValue::HiddenVisibility;
910  case 2: return GlobalValue::ProtectedVisibility;
911  }
912 }
913 
916  switch (Val) {
917  default: // Map unknown values to default.
918  case 0: return GlobalValue::DefaultStorageClass;
919  case 1: return GlobalValue::DLLImportStorageClass;
920  case 2: return GlobalValue::DLLExportStorageClass;
921  }
922 }
923 
924 static bool getDecodedDSOLocal(unsigned Val) {
925  switch(Val) {
926  default: // Map unknown values to preemptable.
927  case 0: return false;
928  case 1: return true;
929  }
930 }
931 
933  switch (Val) {
934  case 0: return GlobalVariable::NotThreadLocal;
935  default: // Map unknown non-zero value to general dynamic.
939  case 4: return GlobalVariable::LocalExecTLSModel;
940  }
941 }
942 
944  switch (Val) {
945  default: // Map unknown to UnnamedAddr::None.
946  case 0: return GlobalVariable::UnnamedAddr::None;
948  case 2: return GlobalVariable::UnnamedAddr::Local;
949  }
950 }
951 
952 static int getDecodedCastOpcode(unsigned Val) {
953  switch (Val) {
954  default: return -1;
955  case bitc::CAST_TRUNC : return Instruction::Trunc;
956  case bitc::CAST_ZEXT : return Instruction::ZExt;
957  case bitc::CAST_SEXT : return Instruction::SExt;
958  case bitc::CAST_FPTOUI : return Instruction::FPToUI;
959  case bitc::CAST_FPTOSI : return Instruction::FPToSI;
960  case bitc::CAST_UITOFP : return Instruction::UIToFP;
961  case bitc::CAST_SITOFP : return Instruction::SIToFP;
962  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
963  case bitc::CAST_FPEXT : return Instruction::FPExt;
964  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
965  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
966  case bitc::CAST_BITCAST : return Instruction::BitCast;
967  case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
968  }
969 }
970 
971 static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
972  bool IsFP = Ty->isFPOrFPVectorTy();
973  // UnOps are only valid for int/fp or vector of int/fp types
974  if (!IsFP && !Ty->isIntOrIntVectorTy())
975  return -1;
976 
977  switch (Val) {
978  default:
979  return -1;
980  case bitc::UNOP_NEG:
981  return IsFP ? Instruction::FNeg : -1;
982  }
983 }
984 
985 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
986  bool IsFP = Ty->isFPOrFPVectorTy();
987  // BinOps are only valid for int/fp or vector of int/fp types
988  if (!IsFP && !Ty->isIntOrIntVectorTy())
989  return -1;
990 
991  switch (Val) {
992  default:
993  return -1;
994  case bitc::BINOP_ADD:
995  return IsFP ? Instruction::FAdd : Instruction::Add;
996  case bitc::BINOP_SUB:
997  return IsFP ? Instruction::FSub : Instruction::Sub;
998  case bitc::BINOP_MUL:
999  return IsFP ? Instruction::FMul : Instruction::Mul;
1000  case bitc::BINOP_UDIV:
1001  return IsFP ? -1 : Instruction::UDiv;
1002  case bitc::BINOP_SDIV:
1003  return IsFP ? Instruction::FDiv : Instruction::SDiv;
1004  case bitc::BINOP_UREM:
1005  return IsFP ? -1 : Instruction::URem;
1006  case bitc::BINOP_SREM:
1007  return IsFP ? Instruction::FRem : Instruction::SRem;
1008  case bitc::BINOP_SHL:
1009  return IsFP ? -1 : Instruction::Shl;
1010  case bitc::BINOP_LSHR:
1011  return IsFP ? -1 : Instruction::LShr;
1012  case bitc::BINOP_ASHR:
1013  return IsFP ? -1 : Instruction::AShr;
1014  case bitc::BINOP_AND:
1015  return IsFP ? -1 : Instruction::And;
1016  case bitc::BINOP_OR:
1017  return IsFP ? -1 : Instruction::Or;
1018  case bitc::BINOP_XOR:
1019  return IsFP ? -1 : Instruction::Xor;
1020  }
1021 }
1022 
1024  switch (Val) {
1025  default: return AtomicRMWInst::BAD_BINOP;
1026  case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1027  case bitc::RMW_ADD: return AtomicRMWInst::Add;
1028  case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1029  case bitc::RMW_AND: return AtomicRMWInst::And;
1030  case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1031  case bitc::RMW_OR: return AtomicRMWInst::Or;
1032  case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1033  case bitc::RMW_MAX: return AtomicRMWInst::Max;
1034  case bitc::RMW_MIN: return AtomicRMWInst::Min;
1035  case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1036  case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1037  case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1038  case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1039  }
1040 }
1041 
1042 static AtomicOrdering getDecodedOrdering(unsigned Val) {
1043  switch (Val) {
1050  default: // Map unknown orderings to sequentially-consistent.
1052  }
1053 }
1054 
1056  switch (Val) {
1057  default: // Map unknown selection kinds to any.
1059  return Comdat::Any;
1061  return Comdat::ExactMatch;
1063  return Comdat::Largest;
1065  return Comdat::NoDuplicates;
1067  return Comdat::SameSize;
1068  }
1069 }
1070 
1072  FastMathFlags FMF;
1073  if (0 != (Val & bitc::UnsafeAlgebra))
1074  FMF.setFast();
1075  if (0 != (Val & bitc::AllowReassoc))
1076  FMF.setAllowReassoc();
1077  if (0 != (Val & bitc::NoNaNs))
1078  FMF.setNoNaNs();
1079  if (0 != (Val & bitc::NoInfs))
1080  FMF.setNoInfs();
1081  if (0 != (Val & bitc::NoSignedZeros))
1082  FMF.setNoSignedZeros();
1083  if (0 != (Val & bitc::AllowReciprocal))
1084  FMF.setAllowReciprocal();
1085  if (0 != (Val & bitc::AllowContract))
1086  FMF.setAllowContract(true);
1087  if (0 != (Val & bitc::ApproxFunc))
1088  FMF.setApproxFunc();
1089  return FMF;
1090 }
1091 
1092 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1093  switch (Val) {
1096  }
1097 }
1098 
1099 Type *BitcodeReader::getTypeByID(unsigned ID) {
1100  // The type table size is always specified correctly.
1101  if (ID >= TypeList.size())
1102  return nullptr;
1103 
1104  if (Type *Ty = TypeList[ID])
1105  return Ty;
1106 
1107  // If we have a forward reference, the only possible case is when it is to a
1108  // named struct. Just create a placeholder for now.
1109  return TypeList[ID] = createIdentifiedStructType(Context);
1110 }
1111 
1112 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1113  StringRef Name) {
1114  auto *Ret = StructType::create(Context, Name);
1115  IdentifiedStructTypes.push_back(Ret);
1116  return Ret;
1117 }
1118 
1119 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1120  auto *Ret = StructType::create(Context);
1121  IdentifiedStructTypes.push_back(Ret);
1122  return Ret;
1123 }
1124 
1125 //===----------------------------------------------------------------------===//
1126 // Functions for parsing blocks from the bitcode file
1127 //===----------------------------------------------------------------------===//
1128 
1130  switch (Val) {
1132  llvm_unreachable("Synthetic enumerators which should never get here");
1133 
1134  case Attribute::None: return 0;
1135  case Attribute::ZExt: return 1 << 0;
1136  case Attribute::SExt: return 1 << 1;
1137  case Attribute::NoReturn: return 1 << 2;
1138  case Attribute::InReg: return 1 << 3;
1139  case Attribute::StructRet: return 1 << 4;
1140  case Attribute::NoUnwind: return 1 << 5;
1141  case Attribute::NoAlias: return 1 << 6;
1142  case Attribute::ByVal: return 1 << 7;
1143  case Attribute::Nest: return 1 << 8;
1144  case Attribute::ReadNone: return 1 << 9;
1145  case Attribute::ReadOnly: return 1 << 10;
1146  case Attribute::NoInline: return 1 << 11;
1147  case Attribute::AlwaysInline: return 1 << 12;
1148  case Attribute::OptimizeForSize: return 1 << 13;
1149  case Attribute::StackProtect: return 1 << 14;
1150  case Attribute::StackProtectReq: return 1 << 15;
1151  case Attribute::Alignment: return 31 << 16;
1152  case Attribute::NoCapture: return 1 << 21;
1153  case Attribute::NoRedZone: return 1 << 22;
1154  case Attribute::NoImplicitFloat: return 1 << 23;
1155  case Attribute::Naked: return 1 << 24;
1156  case Attribute::InlineHint: return 1 << 25;
1157  case Attribute::StackAlignment: return 7 << 26;
1158  case Attribute::ReturnsTwice: return 1 << 29;
1159  case Attribute::UWTable: return 1 << 30;
1160  case Attribute::NonLazyBind: return 1U << 31;
1161  case Attribute::SanitizeAddress: return 1ULL << 32;
1162  case Attribute::MinSize: return 1ULL << 33;
1163  case Attribute::NoDuplicate: return 1ULL << 34;
1164  case Attribute::StackProtectStrong: return 1ULL << 35;
1165  case Attribute::SanitizeThread: return 1ULL << 36;
1166  case Attribute::SanitizeMemory: return 1ULL << 37;
1167  case Attribute::NoBuiltin: return 1ULL << 38;
1168  case Attribute::Returned: return 1ULL << 39;
1169  case Attribute::Cold: return 1ULL << 40;
1170  case Attribute::Builtin: return 1ULL << 41;
1171  case Attribute::OptimizeNone: return 1ULL << 42;
1172  case Attribute::InAlloca: return 1ULL << 43;
1173  case Attribute::NonNull: return 1ULL << 44;
1174  case Attribute::JumpTable: return 1ULL << 45;
1175  case Attribute::Convergent: return 1ULL << 46;
1176  case Attribute::SafeStack: return 1ULL << 47;
1177  case Attribute::NoRecurse: return 1ULL << 48;
1178  case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1179  case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1180  case Attribute::SwiftSelf: return 1ULL << 51;
1181  case Attribute::SwiftError: return 1ULL << 52;
1182  case Attribute::WriteOnly: return 1ULL << 53;
1183  case Attribute::Speculatable: return 1ULL << 54;
1184  case Attribute::StrictFP: return 1ULL << 55;
1185  case Attribute::SanitizeHWAddress: return 1ULL << 56;
1186  case Attribute::NoCfCheck: return 1ULL << 57;
1187  case Attribute::OptForFuzzing: return 1ULL << 58;
1188  case Attribute::ShadowCallStack: return 1ULL << 59;
1189  case Attribute::SpeculativeLoadHardening:
1190  return 1ULL << 60;
1191  case Attribute::ImmArg:
1192  return 1ULL << 61;
1193  case Attribute::Dereferenceable:
1194  llvm_unreachable("dereferenceable attribute not supported in raw format");
1195  break;
1196  case Attribute::DereferenceableOrNull:
1197  llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1198  "format");
1199  break;
1200  case Attribute::ArgMemOnly:
1201  llvm_unreachable("argmemonly attribute not supported in raw format");
1202  break;
1203  case Attribute::AllocSize:
1204  llvm_unreachable("allocsize not supported in raw format");
1205  break;
1206  }
1207  llvm_unreachable("Unsupported attribute type");
1208 }
1209 
1210 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1211  if (!Val) return;
1212 
1214  I = Attribute::AttrKind(I + 1)) {
1215  if (I == Attribute::Dereferenceable ||
1216  I == Attribute::DereferenceableOrNull ||
1217  I == Attribute::ArgMemOnly ||
1218  I == Attribute::AllocSize)
1219  continue;
1220  if (uint64_t A = (Val & getRawAttributeMask(I))) {
1221  if (I == Attribute::Alignment)
1222  B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1223  else if (I == Attribute::StackAlignment)
1224  B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1225  else
1226  B.addAttribute(I);
1227  }
1228  }
1229 }
1230 
1231 /// This fills an AttrBuilder object with the LLVM attributes that have
1232 /// been decoded from the given integer. This function must stay in sync with
1233 /// 'encodeLLVMAttributesForBitcode'.
1235  uint64_t EncodedAttrs) {
1236  // FIXME: Remove in 4.0.
1237 
1238  // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1239  // the bits above 31 down by 11 bits.
1240  unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1241  assert((!Alignment || isPowerOf2_32(Alignment)) &&
1242  "Alignment must be a power of two.");
1243 
1244  if (Alignment)
1245  B.addAlignmentAttr(Alignment);
1246  addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1247  (EncodedAttrs & 0xffff));
1248 }
1249 
1250 Error BitcodeReader::parseAttributeBlock() {
1252  return error("Invalid record");
1253 
1254  if (!MAttributes.empty())
1255  return error("Invalid multiple blocks");
1256 
1258 
1260 
1261  // Read all the records.
1262  while (true) {
1263  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1264 
1265  switch (Entry.Kind) {
1266  case BitstreamEntry::SubBlock: // Handled for us already.
1267  case BitstreamEntry::Error:
1268  return error("Malformed block");
1270  return Error::success();
1272  // The interesting case.
1273  break;
1274  }
1275 
1276  // Read a record.
1277  Record.clear();
1278  switch (Stream.readRecord(Entry.ID, Record)) {
1279  default: // Default behavior: ignore.
1280  break;
1281  case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1282  // FIXME: Remove in 4.0.
1283  if (Record.size() & 1)
1284  return error("Invalid record");
1285 
1286  for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1287  AttrBuilder B;
1288  decodeLLVMAttributesForBitcode(B, Record[i+1]);
1289  Attrs.push_back(AttributeList::get(Context, Record[i], B));
1290  }
1291 
1292  MAttributes.push_back(AttributeList::get(Context, Attrs));
1293  Attrs.clear();
1294  break;
1295  case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1296  for (unsigned i = 0, e = Record.size(); i != e; ++i)
1297  Attrs.push_back(MAttributeGroups[Record[i]]);
1298 
1299  MAttributes.push_back(AttributeList::get(Context, Attrs));
1300  Attrs.clear();
1301  break;
1302  }
1303  }
1304 }
1305 
1306 // Returns Attribute::None on unrecognized codes.
1307 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1308  switch (Code) {
1309  default:
1310  return Attribute::None;
1312  return Attribute::Alignment;
1314  return Attribute::AlwaysInline;
1316  return Attribute::ArgMemOnly;
1318  return Attribute::Builtin;
1320  return Attribute::ByVal;
1322  return Attribute::InAlloca;
1323  case bitc::ATTR_KIND_COLD:
1324  return Attribute::Cold;
1326  return Attribute::Convergent;
1328  return Attribute::InaccessibleMemOnly;
1330  return Attribute::InaccessibleMemOrArgMemOnly;
1332  return Attribute::InlineHint;
1334  return Attribute::InReg;
1336  return Attribute::JumpTable;
1338  return Attribute::MinSize;
1339  case bitc::ATTR_KIND_NAKED:
1340  return Attribute::Naked;
1341  case bitc::ATTR_KIND_NEST:
1342  return Attribute::Nest;
1344  return Attribute::NoAlias;
1346  return Attribute::NoBuiltin;
1348  return Attribute::NoCapture;
1350  return Attribute::NoDuplicate;
1352  return Attribute::NoImplicitFloat;
1354  return Attribute::NoInline;
1356  return Attribute::NoRecurse;
1358  return Attribute::NonLazyBind;
1360  return Attribute::NonNull;
1362  return Attribute::Dereferenceable;
1364  return Attribute::DereferenceableOrNull;
1366  return Attribute::AllocSize;
1368  return Attribute::NoRedZone;
1370  return Attribute::NoReturn;
1372  return Attribute::NoCfCheck;
1374  return Attribute::NoUnwind;
1376  return Attribute::OptForFuzzing;
1378  return Attribute::OptimizeForSize;
1380  return Attribute::OptimizeNone;
1382  return Attribute::ReadNone;
1384  return Attribute::ReadOnly;
1386  return Attribute::Returned;
1388  return Attribute::ReturnsTwice;
1389  case bitc::ATTR_KIND_S_EXT:
1390  return Attribute::SExt;
1392  return Attribute::Speculatable;
1394  return Attribute::StackAlignment;
1396  return Attribute::StackProtect;
1398  return Attribute::StackProtectReq;
1400  return Attribute::StackProtectStrong;
1402  return Attribute::SafeStack;
1404  return Attribute::ShadowCallStack;
1406  return Attribute::StrictFP;
1408  return Attribute::StructRet;
1410  return Attribute::SanitizeAddress;
1412  return Attribute::SanitizeHWAddress;
1414  return Attribute::SanitizeThread;
1416  return Attribute::SanitizeMemory;
1418  return Attribute::SpeculativeLoadHardening;
1420  return Attribute::SwiftError;
1422  return Attribute::SwiftSelf;
1424  return Attribute::UWTable;
1426  return Attribute::WriteOnly;
1427  case bitc::ATTR_KIND_Z_EXT:
1428  return Attribute::ZExt;
1430  return Attribute::ImmArg;
1431  }
1432 }
1433 
1434 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1435  unsigned &Alignment) {
1436  // Note: Alignment in bitcode files is incremented by 1, so that zero
1437  // can be used for default alignment.
1438  if (Exponent > Value::MaxAlignmentExponent + 1)
1439  return error("Invalid alignment value");
1440  Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1441  return Error::success();
1442 }
1443 
1445  *Kind = getAttrFromCode(Code);
1446  if (*Kind == Attribute::None)
1447  return error("Unknown attribute kind (" + Twine(Code) + ")");
1448  return Error::success();
1449 }
1450 
1451 Error BitcodeReader::parseAttributeGroupBlock() {
1453  return error("Invalid record");
1454 
1455  if (!MAttributeGroups.empty())
1456  return error("Invalid multiple blocks");
1457 
1459 
1460  // Read all the records.
1461  while (true) {
1462  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1463 
1464  switch (Entry.Kind) {
1465  case BitstreamEntry::SubBlock: // Handled for us already.
1466  case BitstreamEntry::Error:
1467  return error("Malformed block");
1469  return Error::success();
1471  // The interesting case.
1472  break;
1473  }
1474 
1475  // Read a record.
1476  Record.clear();
1477  switch (Stream.readRecord(Entry.ID, Record)) {
1478  default: // Default behavior: ignore.
1479  break;
1480  case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1481  if (Record.size() < 3)
1482  return error("Invalid record");
1483 
1484  uint64_t GrpID = Record[0];
1485  uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1486 
1487  AttrBuilder B;
1488  for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1489  if (Record[i] == 0) { // Enum attribute
1491  if (Error Err = parseAttrKind(Record[++i], &Kind))
1492  return Err;
1493 
1494  B.addAttribute(Kind);
1495  } else if (Record[i] == 1) { // Integer attribute
1497  if (Error Err = parseAttrKind(Record[++i], &Kind))
1498  return Err;
1499  if (Kind == Attribute::Alignment)
1500  B.addAlignmentAttr(Record[++i]);
1501  else if (Kind == Attribute::StackAlignment)
1502  B.addStackAlignmentAttr(Record[++i]);
1503  else if (Kind == Attribute::Dereferenceable)
1504  B.addDereferenceableAttr(Record[++i]);
1505  else if (Kind == Attribute::DereferenceableOrNull)
1506  B.addDereferenceableOrNullAttr(Record[++i]);
1507  else if (Kind == Attribute::AllocSize)
1508  B.addAllocSizeAttrFromRawRepr(Record[++i]);
1509  } else { // String attribute
1510  assert((Record[i] == 3 || Record[i] == 4) &&
1511  "Invalid attribute group entry");
1512  bool HasValue = (Record[i++] == 4);
1513  SmallString<64> KindStr;
1514  SmallString<64> ValStr;
1515 
1516  while (Record[i] != 0 && i != e)
1517  KindStr += Record[i++];
1518  assert(Record[i] == 0 && "Kind string not null terminated");
1519 
1520  if (HasValue) {
1521  // Has a value associated with it.
1522  ++i; // Skip the '0' that terminates the "kind" string.
1523  while (Record[i] != 0 && i != e)
1524  ValStr += Record[i++];
1525  assert(Record[i] == 0 && "Value string not null terminated");
1526  }
1527 
1528  B.addAttribute(KindStr.str(), ValStr.str());
1529  }
1530  }
1531 
1532  MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1533  break;
1534  }
1535  }
1536  }
1537 }
1538 
1539 Error BitcodeReader::parseTypeTable() {
1541  return error("Invalid record");
1542 
1543  return parseTypeTableBody();
1544 }
1545 
1546 Error BitcodeReader::parseTypeTableBody() {
1547  if (!TypeList.empty())
1548  return error("Invalid multiple blocks");
1549 
1551  unsigned NumRecords = 0;
1552 
1554 
1555  // Read all the records for this type table.
1556  while (true) {
1557  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1558 
1559  switch (Entry.Kind) {
1560  case BitstreamEntry::SubBlock: // Handled for us already.
1561  case BitstreamEntry::Error:
1562  return error("Malformed block");
1564  if (NumRecords != TypeList.size())
1565  return error("Malformed block");
1566  return Error::success();
1568  // The interesting case.
1569  break;
1570  }
1571 
1572  // Read a record.
1573  Record.clear();
1574  Type *ResultTy = nullptr;
1575  switch (Stream.readRecord(Entry.ID, Record)) {
1576  default:
1577  return error("Invalid value");
1578  case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1579  // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1580  // type list. This allows us to reserve space.
1581  if (Record.size() < 1)
1582  return error("Invalid record");
1583  TypeList.resize(Record[0]);
1584  continue;
1585  case bitc::TYPE_CODE_VOID: // VOID
1586  ResultTy = Type::getVoidTy(Context);
1587  break;
1588  case bitc::TYPE_CODE_HALF: // HALF
1589  ResultTy = Type::getHalfTy(Context);
1590  break;
1591  case bitc::TYPE_CODE_FLOAT: // FLOAT
1592  ResultTy = Type::getFloatTy(Context);
1593  break;
1594  case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1595  ResultTy = Type::getDoubleTy(Context);
1596  break;
1597  case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1598  ResultTy = Type::getX86_FP80Ty(Context);
1599  break;
1600  case bitc::TYPE_CODE_FP128: // FP128
1601  ResultTy = Type::getFP128Ty(Context);
1602  break;
1603  case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1604  ResultTy = Type::getPPC_FP128Ty(Context);
1605  break;
1606  case bitc::TYPE_CODE_LABEL: // LABEL
1607  ResultTy = Type::getLabelTy(Context);
1608  break;
1609  case bitc::TYPE_CODE_METADATA: // METADATA
1610  ResultTy = Type::getMetadataTy(Context);
1611  break;
1612  case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1613  ResultTy = Type::getX86_MMXTy(Context);
1614  break;
1615  case bitc::TYPE_CODE_TOKEN: // TOKEN
1616  ResultTy = Type::getTokenTy(Context);
1617  break;
1618  case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1619  if (Record.size() < 1)
1620  return error("Invalid record");
1621 
1622  uint64_t NumBits = Record[0];
1623  if (NumBits < IntegerType::MIN_INT_BITS ||
1624  NumBits > IntegerType::MAX_INT_BITS)
1625  return error("Bitwidth for integer type out of range");
1626  ResultTy = IntegerType::get(Context, NumBits);
1627  break;
1628  }
1629  case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1630  // [pointee type, address space]
1631  if (Record.size() < 1)
1632  return error("Invalid record");
1633  unsigned AddressSpace = 0;
1634  if (Record.size() == 2)
1635  AddressSpace = Record[1];
1636  ResultTy = getTypeByID(Record[0]);
1637  if (!ResultTy ||
1639  return error("Invalid type");
1640  ResultTy = PointerType::get(ResultTy, AddressSpace);
1641  break;
1642  }
1644  // FIXME: attrid is dead, remove it in LLVM 4.0
1645  // FUNCTION: [vararg, attrid, retty, paramty x N]
1646  if (Record.size() < 3)
1647  return error("Invalid record");
1648  SmallVector<Type*, 8> ArgTys;
1649  for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1650  if (Type *T = getTypeByID(Record[i]))
1651  ArgTys.push_back(T);
1652  else
1653  break;
1654  }
1655 
1656  ResultTy = getTypeByID(Record[2]);
1657  if (!ResultTy || ArgTys.size() < Record.size()-3)
1658  return error("Invalid type");
1659 
1660  ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1661  break;
1662  }
1663  case bitc::TYPE_CODE_FUNCTION: {
1664  // FUNCTION: [vararg, retty, paramty x N]
1665  if (Record.size() < 2)
1666  return error("Invalid record");
1667  SmallVector<Type*, 8> ArgTys;
1668  for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1669  if (Type *T = getTypeByID(Record[i])) {
1671  return error("Invalid function argument type");
1672  ArgTys.push_back(T);
1673  }
1674  else
1675  break;
1676  }
1677 
1678  ResultTy = getTypeByID(Record[1]);
1679  if (!ResultTy || ArgTys.size() < Record.size()-2)
1680  return error("Invalid type");
1681 
1682  ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1683  break;
1684  }
1685  case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1686  if (Record.size() < 1)
1687  return error("Invalid record");
1688  SmallVector<Type*, 8> EltTys;
1689  for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1690  if (Type *T = getTypeByID(Record[i]))
1691  EltTys.push_back(T);
1692  else
1693  break;
1694  }
1695  if (EltTys.size() != Record.size()-1)
1696  return error("Invalid type");
1697  ResultTy = StructType::get(Context, EltTys, Record[0]);
1698  break;
1699  }
1700  case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1701  if (convertToString(Record, 0, TypeName))
1702  return error("Invalid record");
1703  continue;
1704 
1705  case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1706  if (Record.size() < 1)
1707  return error("Invalid record");
1708 
1709  if (NumRecords >= TypeList.size())
1710  return error("Invalid TYPE table");
1711 
1712  // Check to see if this was forward referenced, if so fill in the temp.
1713  StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1714  if (Res) {
1715  Res->setName(TypeName);
1716  TypeList[NumRecords] = nullptr;
1717  } else // Otherwise, create a new struct.
1718  Res = createIdentifiedStructType(Context, TypeName);
1719  TypeName.clear();
1720 
1721  SmallVector<Type*, 8> EltTys;
1722  for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1723  if (Type *T = getTypeByID(Record[i]))
1724  EltTys.push_back(T);
1725  else
1726  break;
1727  }
1728  if (EltTys.size() != Record.size()-1)
1729  return error("Invalid record");
1730  Res->setBody(EltTys, Record[0]);
1731  ResultTy = Res;
1732  break;
1733  }
1734  case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1735  if (Record.size() != 1)
1736  return error("Invalid record");
1737 
1738  if (NumRecords >= TypeList.size())
1739  return error("Invalid TYPE table");
1740 
1741  // Check to see if this was forward referenced, if so fill in the temp.
1742  StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1743  if (Res) {
1744  Res->setName(TypeName);
1745  TypeList[NumRecords] = nullptr;
1746  } else // Otherwise, create a new struct with no body.
1747  Res = createIdentifiedStructType(Context, TypeName);
1748  TypeName.clear();
1749  ResultTy = Res;
1750  break;
1751  }
1752  case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1753  if (Record.size() < 2)
1754  return error("Invalid record");
1755  ResultTy = getTypeByID(Record[1]);
1756  if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1757  return error("Invalid type");
1758  ResultTy = ArrayType::get(ResultTy, Record[0]);
1759  break;
1760  case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1761  if (Record.size() < 2)
1762  return error("Invalid record");
1763  if (Record[0] == 0)
1764  return error("Invalid vector length");
1765  ResultTy = getTypeByID(Record[1]);
1766  if (!ResultTy || !StructType::isValidElementType(ResultTy))
1767  return error("Invalid type");
1768  ResultTy = VectorType::get(ResultTy, Record[0]);
1769  break;
1770  }
1771 
1772  if (NumRecords >= TypeList.size())
1773  return error("Invalid TYPE table");
1774  if (TypeList[NumRecords])
1775  return error(
1776  "Invalid TYPE table: Only named structs can be forward referenced");
1777  assert(ResultTy && "Didn't read a type?");
1778  TypeList[NumRecords++] = ResultTy;
1779  }
1780 }
1781 
1782 Error BitcodeReader::parseOperandBundleTags() {
1784  return error("Invalid record");
1785 
1786  if (!BundleTags.empty())
1787  return error("Invalid multiple blocks");
1788 
1790 
1791  while (true) {
1792  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1793 
1794  switch (Entry.Kind) {
1795  case BitstreamEntry::SubBlock: // Handled for us already.
1796  case BitstreamEntry::Error:
1797  return error("Malformed block");
1799  return Error::success();
1801  // The interesting case.
1802  break;
1803  }
1804 
1805  // Tags are implicitly mapped to integers by their order.
1806 
1807  if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1808  return error("Invalid record");
1809 
1810  // OPERAND_BUNDLE_TAG: [strchr x N]
1811  BundleTags.emplace_back();
1812  if (convertToString(Record, 0, BundleTags.back()))
1813  return error("Invalid record");
1814  Record.clear();
1815  }
1816 }
1817 
1818 Error BitcodeReader::parseSyncScopeNames() {
1820  return error("Invalid record");
1821 
1822  if (!SSIDs.empty())
1823  return error("Invalid multiple synchronization scope names blocks");
1824 
1826  while (true) {
1827  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1828  switch (Entry.Kind) {
1829  case BitstreamEntry::SubBlock: // Handled for us already.
1830  case BitstreamEntry::Error:
1831  return error("Malformed block");
1833  if (SSIDs.empty())
1834  return error("Invalid empty synchronization scope names block");
1835  return Error::success();
1837  // The interesting case.
1838  break;
1839  }
1840 
1841  // Synchronization scope names are implicitly mapped to synchronization
1842  // scope IDs by their order.
1843 
1844  if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
1845  return error("Invalid record");
1846 
1847  SmallString<16> SSN;
1848  if (convertToString(Record, 0, SSN))
1849  return error("Invalid record");
1850 
1851  SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
1852  Record.clear();
1853  }
1854 }
1855 
1856 /// Associate a value with its name from the given index in the provided record.
1857 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1858  unsigned NameIndex, Triple &TT) {
1860  if (convertToString(Record, NameIndex, ValueName))
1861  return error("Invalid record");
1862  unsigned ValueID = Record[0];
1863  if (ValueID >= ValueList.size() || !ValueList[ValueID])
1864  return error("Invalid record");
1865  Value *V = ValueList[ValueID];
1866 
1867  StringRef NameStr(ValueName.data(), ValueName.size());
1868  if (NameStr.find_first_of(0) != StringRef::npos)
1869  return error("Invalid value name");
1870  V->setName(NameStr);
1871  auto *GO = dyn_cast<GlobalObject>(V);
1872  if (GO) {
1873  if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1874  if (TT.supportsCOMDAT())
1875  GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1876  else
1877  GO->setComdat(nullptr);
1878  }
1879  }
1880  return V;
1881 }
1882 
1883 /// Helper to note and return the current location, and jump to the given
1884 /// offset.
1885 static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1886  BitstreamCursor &Stream) {
1887  // Save the current parsing location so we can jump back at the end
1888  // of the VST read.
1889  uint64_t CurrentBit = Stream.GetCurrentBitNo();
1890  Stream.JumpToBit(Offset * 32);
1891 #ifndef NDEBUG
1892  // Do some checking if we are in debug mode.
1893  BitstreamEntry Entry = Stream.advance();
1896 #else
1897  // In NDEBUG mode ignore the output so we don't get an unused variable
1898  // warning.
1899  Stream.advance();
1900 #endif
1901  return CurrentBit;
1902 }
1903 
1904 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
1905  Function *F,
1906  ArrayRef<uint64_t> Record) {
1907  // Note that we subtract 1 here because the offset is relative to one word
1908  // before the start of the identification or module block, which was
1909  // historically always the start of the regular bitcode header.
1910  uint64_t FuncWordOffset = Record[1] - 1;
1911  uint64_t FuncBitOffset = FuncWordOffset * 32;
1912  DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1913  // Set the LastFunctionBlockBit to point to the last function block.
1914  // Later when parsing is resumed after function materialization,
1915  // we can simply skip that last function block.
1916  if (FuncBitOffset > LastFunctionBlockBit)
1917  LastFunctionBlockBit = FuncBitOffset;
1918 }
1919 
1920 /// Read a new-style GlobalValue symbol table.
1921 Error BitcodeReader::parseGlobalValueSymbolTable() {
1922  unsigned FuncBitcodeOffsetDelta =
1924 
1926  return error("Invalid record");
1927 
1929  while (true) {
1930  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1931 
1932  switch (Entry.Kind) {
1934  case BitstreamEntry::Error:
1935  return error("Malformed block");
1937  return Error::success();
1939  break;
1940  }
1941 
1942  Record.clear();
1943  switch (Stream.readRecord(Entry.ID, Record)) {
1944  case bitc::VST_CODE_FNENTRY: // [valueid, offset]
1945  setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
1946  cast<Function>(ValueList[Record[0]]), Record);
1947  break;
1948  }
1949  }
1950 }
1951 
1952 /// Parse the value symbol table at either the current parsing location or
1953 /// at the given bit offset if provided.
1954 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1955  uint64_t CurrentBit;
1956  // Pass in the Offset to distinguish between calling for the module-level
1957  // VST (where we want to jump to the VST offset) and the function-level
1958  // VST (where we don't).
1959  if (Offset > 0) {
1960  CurrentBit = jumpToValueSymbolTable(Offset, Stream);
1961  // If this module uses a string table, read this as a module-level VST.
1962  if (UseStrtab) {
1963  if (Error Err = parseGlobalValueSymbolTable())
1964  return Err;
1965  Stream.JumpToBit(CurrentBit);
1966  return Error::success();
1967  }
1968  // Otherwise, the VST will be in a similar format to a function-level VST,
1969  // and will contain symbol names.
1970  }
1971 
1972  // Compute the delta between the bitcode indices in the VST (the word offset
1973  // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1974  // expected by the lazy reader. The reader's EnterSubBlock expects to have
1975  // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1976  // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1977  // just before entering the VST subblock because: 1) the EnterSubBlock
1978  // changes the AbbrevID width; 2) the VST block is nested within the same
1979  // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1980  // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1981  // jump to the FUNCTION_BLOCK using this offset later, we don't want
1982  // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1983  unsigned FuncBitcodeOffsetDelta =
1985 
1987  return error("Invalid record");
1988 
1990 
1991  Triple TT(TheModule->getTargetTriple());
1992 
1993  // Read all the records for this value table.
1995 
1996  while (true) {
1997  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1998 
1999  switch (Entry.Kind) {
2000  case BitstreamEntry::SubBlock: // Handled for us already.
2001  case BitstreamEntry::Error:
2002  return error("Malformed block");
2004  if (Offset > 0)
2005  Stream.JumpToBit(CurrentBit);
2006  return Error::success();
2008  // The interesting case.
2009  break;
2010  }
2011 
2012  // Read a record.
2013  Record.clear();
2014  switch (Stream.readRecord(Entry.ID, Record)) {
2015  default: // Default behavior: unknown type.
2016  break;
2017  case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
2018  Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2019  if (Error Err = ValOrErr.takeError())
2020  return Err;
2021  ValOrErr.get();
2022  break;
2023  }
2024  case bitc::VST_CODE_FNENTRY: {
2025  // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2026  Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2027  if (Error Err = ValOrErr.takeError())
2028  return Err;
2029  Value *V = ValOrErr.get();
2030 
2031  // Ignore function offsets emitted for aliases of functions in older
2032  // versions of LLVM.
2033  if (auto *F = dyn_cast<Function>(V))
2034  setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2035  break;
2036  }
2037  case bitc::VST_CODE_BBENTRY: {
2038  if (convertToString(Record, 1, ValueName))
2039  return error("Invalid record");
2040  BasicBlock *BB = getBasicBlock(Record[0]);
2041  if (!BB)
2042  return error("Invalid record");
2043 
2044  BB->setName(StringRef(ValueName.data(), ValueName.size()));
2045  ValueName.clear();
2046  break;
2047  }
2048  }
2049  }
2050 }
2051 
2052 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2053 /// encoding.
2054 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2055  if ((V & 1) == 0)
2056  return V >> 1;
2057  if (V != 1)
2058  return -(V >> 1);
2059  // There is no such thing as -0 with integers. "-0" really means MININT.
2060  return 1ULL << 63;
2061 }
2062 
2063 /// Resolve all of the initializers for global values and aliases that we can.
2064 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2065  std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2066  std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
2067  IndirectSymbolInitWorklist;
2068  std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2069  std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2070  std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2071 
2072  GlobalInitWorklist.swap(GlobalInits);
2073  IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2074  FunctionPrefixWorklist.swap(FunctionPrefixes);
2075  FunctionPrologueWorklist.swap(FunctionPrologues);
2076  FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2077 
2078  while (!GlobalInitWorklist.empty()) {
2079  unsigned ValID = GlobalInitWorklist.back().second;
2080  if (ValID >= ValueList.size()) {
2081  // Not ready to resolve this yet, it requires something later in the file.
2082  GlobalInits.push_back(GlobalInitWorklist.back());
2083  } else {
2084  if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2085  GlobalInitWorklist.back().first->setInitializer(C);
2086  else
2087  return error("Expected a constant");
2088  }
2089  GlobalInitWorklist.pop_back();
2090  }
2091 
2092  while (!IndirectSymbolInitWorklist.empty()) {
2093  unsigned ValID = IndirectSymbolInitWorklist.back().second;
2094  if (ValID >= ValueList.size()) {
2095  IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2096  } else {
2097  Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2098  if (!C)
2099  return error("Expected a constant");
2100  GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2101  if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2102  return error("Alias and aliasee types don't match");
2103  GIS->setIndirectSymbol(C);
2104  }
2105  IndirectSymbolInitWorklist.pop_back();
2106  }
2107 
2108  while (!FunctionPrefixWorklist.empty()) {
2109  unsigned ValID = FunctionPrefixWorklist.back().second;
2110  if (ValID >= ValueList.size()) {
2111  FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2112  } else {
2113  if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2114  FunctionPrefixWorklist.back().first->setPrefixData(C);
2115  else
2116  return error("Expected a constant");
2117  }
2118  FunctionPrefixWorklist.pop_back();
2119  }
2120 
2121  while (!FunctionPrologueWorklist.empty()) {
2122  unsigned ValID = FunctionPrologueWorklist.back().second;
2123  if (ValID >= ValueList.size()) {
2124  FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2125  } else {
2126  if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2127  FunctionPrologueWorklist.back().first->setPrologueData(C);
2128  else
2129  return error("Expected a constant");
2130  }
2131  FunctionPrologueWorklist.pop_back();
2132  }
2133 
2134  while (!FunctionPersonalityFnWorklist.empty()) {
2135  unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2136  if (ValID >= ValueList.size()) {
2137  FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2138  } else {
2139  if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2140  FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2141  else
2142  return error("Expected a constant");
2143  }
2144  FunctionPersonalityFnWorklist.pop_back();
2145  }
2146 
2147  return Error::success();
2148 }
2149 
2150 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2151  SmallVector<uint64_t, 8> Words(Vals.size());
2152  transform(Vals, Words.begin(),
2153  BitcodeReader::decodeSignRotatedValue);
2154 
2155  return APInt(TypeBits, Words);
2156 }
2157 
2158 Error BitcodeReader::parseConstants() {
2160  return error("Invalid record");
2161 
2163 
2164  // Read all the records for this value table.
2165  Type *CurTy = Type::getInt32Ty(Context);
2166  unsigned NextCstNo = ValueList.size();
2167 
2168  while (true) {
2169  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2170 
2171  switch (Entry.Kind) {
2172  case BitstreamEntry::SubBlock: // Handled for us already.
2173  case BitstreamEntry::Error:
2174  return error("Malformed block");
2176  if (NextCstNo != ValueList.size())
2177  return error("Invalid constant reference");
2178 
2179  // Once all the constants have been read, go through and resolve forward
2180  // references.
2181  ValueList.resolveConstantForwardRefs();
2182  return Error::success();
2184  // The interesting case.
2185  break;
2186  }
2187 
2188  // Read a record.
2189  Record.clear();
2190  Type *VoidType = Type::getVoidTy(Context);
2191  Value *V = nullptr;
2192  unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2193  switch (BitCode) {
2194  default: // Default behavior: unknown constant
2195  case bitc::CST_CODE_UNDEF: // UNDEF
2196  V = UndefValue::get(CurTy);
2197  break;
2198  case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2199  if (Record.empty())
2200  return error("Invalid record");
2201  if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2202  return error("Invalid record");
2203  if (TypeList[Record[0]] == VoidType)
2204  return error("Invalid constant type");
2205  CurTy = TypeList[Record[0]];
2206  continue; // Skip the ValueList manipulation.
2207  case bitc::CST_CODE_NULL: // NULL
2208  V = Constant::getNullValue(CurTy);
2209  break;
2210  case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2211  if (!CurTy->isIntegerTy() || Record.empty())
2212  return error("Invalid record");
2213  V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2214  break;
2215  case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2216  if (!CurTy->isIntegerTy() || Record.empty())
2217  return error("Invalid record");
2218 
2219  APInt VInt =
2220  readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2221  V = ConstantInt::get(Context, VInt);
2222 
2223  break;
2224  }
2225  case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2226  if (Record.empty())
2227  return error("Invalid record");
2228  if (CurTy->isHalfTy())
2229  V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2230  APInt(16, (uint16_t)Record[0])));
2231  else if (CurTy->isFloatTy())
2233  APInt(32, (uint32_t)Record[0])));
2234  else if (CurTy->isDoubleTy())
2236  APInt(64, Record[0])));
2237  else if (CurTy->isX86_FP80Ty()) {
2238  // Bits are not stored the same way as a normal i80 APInt, compensate.
2239  uint64_t Rearrange[2];
2240  Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2241  Rearrange[1] = Record[0] >> 48;
2243  APInt(80, Rearrange)));
2244  } else if (CurTy->isFP128Ty())
2245  V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2246  APInt(128, Record)));
2247  else if (CurTy->isPPC_FP128Ty())
2249  APInt(128, Record)));
2250  else
2251  V = UndefValue::get(CurTy);
2252  break;
2253  }
2254 
2255  case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2256  if (Record.empty())
2257  return error("Invalid record");
2258 
2259  unsigned Size = Record.size();
2261 
2262  if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2263  for (unsigned i = 0; i != Size; ++i)
2264  Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2265  STy->getElementType(i)));
2266  V = ConstantStruct::get(STy, Elts);
2267  } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2268  Type *EltTy = ATy->getElementType();
2269  for (unsigned i = 0; i != Size; ++i)
2270  Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2271  V = ConstantArray::get(ATy, Elts);
2272  } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2273  Type *EltTy = VTy->getElementType();
2274  for (unsigned i = 0; i != Size; ++i)
2275  Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2276  V = ConstantVector::get(Elts);
2277  } else {
2278  V = UndefValue::get(CurTy);
2279  }
2280  break;
2281  }
2282  case bitc::CST_CODE_STRING: // STRING: [values]
2283  case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2284  if (Record.empty())
2285  return error("Invalid record");
2286 
2287  SmallString<16> Elts(Record.begin(), Record.end());
2288  V = ConstantDataArray::getString(Context, Elts,
2289  BitCode == bitc::CST_CODE_CSTRING);
2290  break;
2291  }
2292  case bitc::CST_CODE_DATA: {// DATA: [n x value]
2293  if (Record.empty())
2294  return error("Invalid record");
2295 
2296  Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2297  if (EltTy->isIntegerTy(8)) {
2298  SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2299  if (isa<VectorType>(CurTy))
2300  V = ConstantDataVector::get(Context, Elts);
2301  else
2302  V = ConstantDataArray::get(Context, Elts);
2303  } else if (EltTy->isIntegerTy(16)) {
2304  SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2305  if (isa<VectorType>(CurTy))
2306  V = ConstantDataVector::get(Context, Elts);
2307  else
2308  V = ConstantDataArray::get(Context, Elts);
2309  } else if (EltTy->isIntegerTy(32)) {
2310  SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2311  if (isa<VectorType>(CurTy))
2312  V = ConstantDataVector::get(Context, Elts);
2313  else
2314  V = ConstantDataArray::get(Context, Elts);
2315  } else if (EltTy->isIntegerTy(64)) {
2316  SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2317  if (isa<VectorType>(CurTy))
2318  V = ConstantDataVector::get(Context, Elts);
2319  else
2320  V = ConstantDataArray::get(Context, Elts);
2321  } else if (EltTy->isHalfTy()) {
2322  SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2323  if (isa<VectorType>(CurTy))
2324  V = ConstantDataVector::getFP(Context, Elts);
2325  else
2326  V = ConstantDataArray::getFP(Context, Elts);
2327  } else if (EltTy->isFloatTy()) {
2328  SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2329  if (isa<VectorType>(CurTy))
2330  V = ConstantDataVector::getFP(Context, Elts);
2331  else
2332  V = ConstantDataArray::getFP(Context, Elts);
2333  } else if (EltTy->isDoubleTy()) {
2334  SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2335  if (isa<VectorType>(CurTy))
2336  V = ConstantDataVector::getFP(Context, Elts);
2337  else
2338  V = ConstantDataArray::getFP(Context, Elts);
2339  } else {
2340  return error("Invalid type for value");
2341  }
2342  break;
2343  }
2344  case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
2345  if (Record.size() < 2)
2346  return error("Invalid record");
2347  int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
2348  if (Opc < 0) {
2349  V = UndefValue::get(CurTy); // Unknown unop.
2350  } else {
2351  Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2352  unsigned Flags = 0;
2353  V = ConstantExpr::get(Opc, LHS, Flags);
2354  }
2355  break;
2356  }
2357  case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2358  if (Record.size() < 3)
2359  return error("Invalid record");
2360  int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2361  if (Opc < 0) {
2362  V = UndefValue::get(CurTy); // Unknown binop.
2363  } else {
2364  Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2365  Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2366  unsigned Flags = 0;
2367  if (Record.size() >= 4) {
2368  if (Opc == Instruction::Add ||
2369  Opc == Instruction::Sub ||
2370  Opc == Instruction::Mul ||
2371  Opc == Instruction::Shl) {
2372  if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2374  if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2376  } else if (Opc == Instruction::SDiv ||
2377  Opc == Instruction::UDiv ||
2378  Opc == Instruction::LShr ||
2379  Opc == Instruction::AShr) {
2380  if (Record[3] & (1 << bitc::PEO_EXACT))
2381  Flags |= SDivOperator::IsExact;
2382  }
2383  }
2384  V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2385  }
2386  break;
2387  }
2388  case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2389  if (Record.size() < 3)
2390  return error("Invalid record");
2391  int Opc = getDecodedCastOpcode(Record[0]);
2392  if (Opc < 0) {
2393  V = UndefValue::get(CurTy); // Unknown cast.
2394  } else {
2395  Type *OpTy = getTypeByID(Record[1]);
2396  if (!OpTy)
2397  return error("Invalid record");
2398  Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2399  V = UpgradeBitCastExpr(Opc, Op, CurTy);
2400  if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2401  }
2402  break;
2403  }
2404  case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2405  case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2406  case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2407  // operands]
2408  unsigned OpNum = 0;
2409  Type *PointeeType = nullptr;
2411  Record.size() % 2)
2412  PointeeType = getTypeByID(Record[OpNum++]);
2413 
2414  bool InBounds = false;
2415  Optional<unsigned> InRangeIndex;
2417  uint64_t Op = Record[OpNum++];
2418  InBounds = Op & 1;
2419  InRangeIndex = Op >> 1;
2420  } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2421  InBounds = true;
2422 
2424  while (OpNum != Record.size()) {
2425  Type *ElTy = getTypeByID(Record[OpNum++]);
2426  if (!ElTy)
2427  return error("Invalid record");
2428  Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2429  }
2430 
2431  if (Elts.size() < 1)
2432  return error("Invalid gep with no operands");
2433 
2434  Type *ImplicitPointeeType =
2435  cast<PointerType>(Elts[0]->getType()->getScalarType())
2436  ->getElementType();
2437  if (!PointeeType)
2438  PointeeType = ImplicitPointeeType;
2439  else if (PointeeType != ImplicitPointeeType)
2440  return error("Explicit gep operator type does not match pointee type "
2441  "of pointer operand");
2442 
2443  ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2444  V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2445  InBounds, InRangeIndex);
2446  break;
2447  }
2448  case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2449  if (Record.size() < 3)
2450  return error("Invalid record");
2451 
2452  Type *SelectorTy = Type::getInt1Ty(Context);
2453 
2454  // The selector might be an i1 or an <n x i1>
2455  // Get the type from the ValueList before getting a forward ref.
2456  if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2457  if (Value *V = ValueList[Record[0]])
2458  if (SelectorTy != V->getType())
2459  SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2460 
2461  V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2462  SelectorTy),
2463  ValueList.getConstantFwdRef(Record[1],CurTy),
2464  ValueList.getConstantFwdRef(Record[2],CurTy));
2465  break;
2466  }
2468  : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2469  if (Record.size() < 3)
2470  return error("Invalid record");
2471  VectorType *OpTy =
2472  dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2473  if (!OpTy)
2474  return error("Invalid record");
2475  Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2476  Constant *Op1 = nullptr;
2477  if (Record.size() == 4) {
2478  Type *IdxTy = getTypeByID(Record[2]);
2479  if (!IdxTy)
2480  return error("Invalid record");
2481  Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2482  } else // TODO: Remove with llvm 4.0
2483  Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2484  if (!Op1)
2485  return error("Invalid record");
2486  V = ConstantExpr::getExtractElement(Op0, Op1);
2487  break;
2488  }
2490  : { // CE_INSERTELT: [opval, opval, opty, opval]
2491  VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2492  if (Record.size() < 3 || !OpTy)
2493  return error("Invalid record");
2494  Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2495  Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2496  OpTy->getElementType());
2497  Constant *Op2 = nullptr;
2498  if (Record.size() == 4) {
2499  Type *IdxTy = getTypeByID(Record[2]);
2500  if (!IdxTy)
2501  return error("Invalid record");
2502  Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2503  } else // TODO: Remove with llvm 4.0
2504  Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2505  if (!Op2)
2506  return error("Invalid record");
2507  V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2508  break;
2509  }
2510  case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2511  VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2512  if (Record.size() < 3 || !OpTy)
2513  return error("Invalid record");
2514  Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2515  Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2516  Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2517  OpTy->getNumElements());
2518  Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2519  V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2520  break;
2521  }
2522  case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2523  VectorType *RTy = dyn_cast<VectorType>(CurTy);
2524  VectorType *OpTy =
2525  dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2526  if (Record.size() < 4 || !RTy || !OpTy)
2527  return error("Invalid record");
2528  Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2529  Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2530  Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2531  RTy->getNumElements());
2532  Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2533  V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2534  break;
2535  }
2536  case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2537  if (Record.size() < 4)
2538  return error("Invalid record");
2539  Type *OpTy = getTypeByID(Record[0]);
2540  if (!OpTy)
2541  return error("Invalid record");
2542  Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2543  Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2544 
2545  if (OpTy->isFPOrFPVectorTy())
2546  V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2547  else
2548  V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2549  break;
2550  }
2551  // This maintains backward compatibility, pre-asm dialect keywords.
2552  // FIXME: Remove with the 4.0 release.
2554  if (Record.size() < 2)
2555  return error("Invalid record");
2556  std::string AsmStr, ConstrStr;
2557  bool HasSideEffects = Record[0] & 1;
2558  bool IsAlignStack = Record[0] >> 1;
2559  unsigned AsmStrSize = Record[1];
2560  if (2+AsmStrSize >= Record.size())
2561  return error("Invalid record");
2562  unsigned ConstStrSize = Record[2+AsmStrSize];
2563  if (3+AsmStrSize+ConstStrSize > Record.size())
2564  return error("Invalid record");
2565 
2566  for (unsigned i = 0; i != AsmStrSize; ++i)
2567  AsmStr += (char)Record[2+i];
2568  for (unsigned i = 0; i != ConstStrSize; ++i)
2569  ConstrStr += (char)Record[3+AsmStrSize+i];
2570  PointerType *PTy = cast<PointerType>(CurTy);
2571  UpgradeInlineAsmString(&AsmStr);
2572  V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2573  AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2574  break;
2575  }
2576  // This version adds support for the asm dialect keywords (e.g.,
2577  // inteldialect).
2578  case bitc::CST_CODE_INLINEASM: {
2579  if (Record.size() < 2)
2580  return error("Invalid record");
2581  std::string AsmStr, ConstrStr;
2582  bool HasSideEffects = Record[0] & 1;
2583  bool IsAlignStack = (Record[0] >> 1) & 1;
2584  unsigned AsmDialect = Record[0] >> 2;
2585  unsigned AsmStrSize = Record[1];
2586  if (2+AsmStrSize >= Record.size())
2587  return error("Invalid record");
2588  unsigned ConstStrSize = Record[2+AsmStrSize];
2589  if (3+AsmStrSize+ConstStrSize > Record.size())
2590  return error("Invalid record");
2591 
2592  for (unsigned i = 0; i != AsmStrSize; ++i)
2593  AsmStr += (char)Record[2+i];
2594  for (unsigned i = 0; i != ConstStrSize; ++i)
2595  ConstrStr += (char)Record[3+AsmStrSize+i];
2596  PointerType *PTy = cast<PointerType>(CurTy);
2597  UpgradeInlineAsmString(&AsmStr);
2598  V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2599  AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2600  InlineAsm::AsmDialect(AsmDialect));
2601  break;
2602  }
2604  if (Record.size() < 3)
2605  return error("Invalid record");
2606  Type *FnTy = getTypeByID(Record[0]);
2607  if (!FnTy)
2608  return error("Invalid record");
2609  Function *Fn =
2610  dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2611  if (!Fn)
2612  return error("Invalid record");
2613 
2614  // If the function is already parsed we can insert the block address right
2615  // away.
2616  BasicBlock *BB;
2617  unsigned BBID = Record[2];
2618  if (!BBID)
2619  // Invalid reference to entry block.
2620  return error("Invalid ID");
2621  if (!Fn->empty()) {
2622  Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2623  for (size_t I = 0, E = BBID; I != E; ++I) {
2624  if (BBI == BBE)
2625  return error("Invalid ID");
2626  ++BBI;
2627  }
2628  BB = &*BBI;
2629  } else {
2630  // Otherwise insert a placeholder and remember it so it can be inserted
2631  // when the function is parsed.
2632  auto &FwdBBs = BasicBlockFwdRefs[Fn];
2633  if (FwdBBs.empty())
2634  BasicBlockFwdRefQueue.push_back(Fn);
2635  if (FwdBBs.size() < BBID + 1)
2636  FwdBBs.resize(BBID + 1);
2637  if (!FwdBBs[BBID])
2638  FwdBBs[BBID] = BasicBlock::Create(Context);
2639  BB = FwdBBs[BBID];
2640  }
2641  V = BlockAddress::get(Fn, BB);
2642  break;
2643  }
2644  }
2645 
2646  ValueList.assignValue(V, NextCstNo);
2647  ++NextCstNo;
2648  }
2649 }
2650 
2651 Error BitcodeReader::parseUseLists() {
2653  return error("Invalid record");
2654 
2655  // Read all the records.
2657 
2658  while (true) {
2659  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2660 
2661  switch (Entry.Kind) {
2662  case BitstreamEntry::SubBlock: // Handled for us already.
2663  case BitstreamEntry::Error:
2664  return error("Malformed block");
2666  return Error::success();
2668  // The interesting case.
2669  break;
2670  }
2671 
2672  // Read a use list record.
2673  Record.clear();
2674  bool IsBB = false;
2675  switch (Stream.readRecord(Entry.ID, Record)) {
2676  default: // Default behavior: unknown type.
2677  break;
2678  case bitc::USELIST_CODE_BB:
2679  IsBB = true;
2682  unsigned RecordLength = Record.size();
2683  if (RecordLength < 3)
2684  // Records should have at least an ID and two indexes.
2685  return error("Invalid record");
2686  unsigned ID = Record.back();
2687  Record.pop_back();
2688 
2689  Value *V;
2690  if (IsBB) {
2691  assert(ID < FunctionBBs.size() && "Basic block not found");
2692  V = FunctionBBs[ID];
2693  } else
2694  V = ValueList[ID];
2695  unsigned NumUses = 0;
2697  for (const Use &U : V->materialized_uses()) {
2698  if (++NumUses > Record.size())
2699  break;
2700  Order[&U] = Record[NumUses - 1];
2701  }
2702  if (Order.size() != Record.size() || NumUses > Record.size())
2703  // Mismatches can happen if the functions are being materialized lazily
2704  // (out-of-order), or a value has been upgraded.
2705  break;
2706 
2707  V->sortUseList([&](const Use &L, const Use &R) {
2708  return Order.lookup(&L) < Order.lookup(&R);
2709  });
2710  break;
2711  }
2712  }
2713  }
2714 }
2715 
2716 /// When we see the block for metadata, remember where it is and then skip it.
2717 /// This lets us lazily deserialize the metadata.
2718 Error BitcodeReader::rememberAndSkipMetadata() {
2719  // Save the current stream state.
2720  uint64_t CurBit = Stream.GetCurrentBitNo();
2721  DeferredMetadataInfo.push_back(CurBit);
2722 
2723  // Skip over the block for now.
2724  if (Stream.SkipBlock())
2725  return error("Invalid record");
2726  return Error::success();
2727 }
2728 
2729 Error BitcodeReader::materializeMetadata() {
2730  for (uint64_t BitPos : DeferredMetadataInfo) {
2731  // Move the bit stream to the saved position.
2732  Stream.JumpToBit(BitPos);
2733  if (Error Err = MDLoader->parseModuleMetadata())
2734  return Err;
2735  }
2736 
2737  // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
2738  // metadata.
2739  if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
2740  NamedMDNode *LinkerOpts =
2741  TheModule->getOrInsertNamedMetadata("llvm.linker.options");
2742  for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
2743  LinkerOpts->addOperand(cast<MDNode>(MDOptions));
2744  }
2745 
2746  DeferredMetadataInfo.clear();
2747  return Error::success();
2748 }
2749 
2750 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2751 
2752 /// When we see the block for a function body, remember where it is and then
2753 /// skip it. This lets us lazily deserialize the functions.
2754 Error BitcodeReader::rememberAndSkipFunctionBody() {
2755  // Get the function we are talking about.
2756  if (FunctionsWithBodies.empty())
2757  return error("Insufficient function protos");
2758 
2759  Function *Fn = FunctionsWithBodies.back();
2760  FunctionsWithBodies.pop_back();
2761 
2762  // Save the current stream state.
2763  uint64_t CurBit = Stream.GetCurrentBitNo();
2764  assert(
2765  (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2766  "Mismatch between VST and scanned function offsets");
2767  DeferredFunctionInfo[Fn] = CurBit;
2768 
2769  // Skip over the function block for now.
2770  if (Stream.SkipBlock())
2771  return error("Invalid record");
2772  return Error::success();
2773 }
2774 
2775 Error BitcodeReader::globalCleanup() {
2776  // Patch the initializers for globals and aliases up.
2777  if (Error Err = resolveGlobalAndIndirectSymbolInits())
2778  return Err;
2779  if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2780  return error("Malformed global initializer set");
2781 
2782  // Look for intrinsic functions which need to be upgraded at some point
2783  for (Function &F : *TheModule) {
2784  MDLoader->upgradeDebugIntrinsics(F);
2785  Function *NewFn;
2786  if (UpgradeIntrinsicFunction(&F, NewFn))
2787  UpgradedIntrinsics[&F] = NewFn;
2788  else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2789  // Some types could be renamed during loading if several modules are
2790  // loaded in the same LLVMContext (LTO scenario). In this case we should
2791  // remangle intrinsics names as well.
2792  RemangledIntrinsics[&F] = Remangled.getValue();
2793  }
2794 
2795  // Look for global variables which need to be renamed.
2796  for (GlobalVariable &GV : TheModule->globals())
2797  UpgradeGlobalVariable(&GV);
2798 
2799  // Force deallocation of memory for these vectors to favor the client that
2800  // want lazy deserialization.
2801  std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
2802  std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
2803  IndirectSymbolInits);
2804  return Error::success();
2805 }
2806 
2807 /// Support for lazy parsing of function bodies. This is required if we
2808 /// either have an old bitcode file without a VST forward declaration record,
2809 /// or if we have an anonymous function being materialized, since anonymous
2810 /// functions do not have a name and are therefore not in the VST.
2811 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2812  Stream.JumpToBit(NextUnreadBit);
2813 
2814  if (Stream.AtEndOfStream())
2815  return error("Could not find function in stream");
2816 
2817  if (!SeenFirstFunctionBody)
2818  return error("Trying to materialize functions before seeing function blocks");
2819 
2820  // An old bitcode file with the symbol table at the end would have
2821  // finished the parse greedily.
2822  assert(SeenValueSymbolTable);
2823 
2825 
2826  while (true) {
2827  BitstreamEntry Entry = Stream.advance();
2828  switch (Entry.Kind) {
2829  default:
2830  return error("Expect SubBlock");
2832  switch (Entry.ID) {
2833  default:
2834  return error("Expect function block");
2836  if (Error Err = rememberAndSkipFunctionBody())
2837  return Err;
2838  NextUnreadBit = Stream.GetCurrentBitNo();
2839  return Error::success();
2840  }
2841  }
2842  }
2843 }
2844 
2845 bool BitcodeReaderBase::readBlockInfo() {
2846  Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2847  if (!NewBlockInfo)
2848  return true;
2849  BlockInfo = std::move(*NewBlockInfo);
2850  return false;
2851 }
2852 
2853 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
2854  // v1: [selection_kind, name]
2855  // v2: [strtab_offset, strtab_size, selection_kind]
2856  StringRef Name;
2857  std::tie(Name, Record) = readNameFromStrtab(Record);
2858 
2859  if (Record.empty())
2860  return error("Invalid record");
2862  std::string OldFormatName;
2863  if (!UseStrtab) {
2864  if (Record.size() < 2)
2865  return error("Invalid record");
2866  unsigned ComdatNameSize = Record[1];
2867  OldFormatName.reserve(ComdatNameSize);
2868  for (unsigned i = 0; i != ComdatNameSize; ++i)
2869  OldFormatName += (char)Record[2 + i];
2870  Name = OldFormatName;
2871  }
2872  Comdat *C = TheModule->getOrInsertComdat(Name);
2873  C->setSelectionKind(SK);
2874  ComdatList.push_back(C);
2875  return Error::success();
2876 }
2877 
2878 static void inferDSOLocal(GlobalValue *GV) {
2879  // infer dso_local from linkage and visibility if it is not encoded.
2880  if (GV->hasLocalLinkage() ||
2881  (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
2882  GV->setDSOLocal(true);
2883 }
2884 
2885 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
2886  // v1: [pointer type, isconst, initid, linkage, alignment, section,
2887  // visibility, threadlocal, unnamed_addr, externally_initialized,
2888  // dllstorageclass, comdat, attributes, preemption specifier] (name in VST)
2889  // v2: [strtab_offset, strtab_size, v1]
2890  StringRef Name;
2891  std::tie(Name, Record) = readNameFromStrtab(Record);
2892 
2893  if (Record.size() < 6)
2894  return error("Invalid record");
2895  Type *Ty = getTypeByID(Record[0]);
2896  if (!Ty)
2897  return error("Invalid record");
2898  bool isConstant = Record[1] & 1;
2899  bool explicitType = Record[1] & 2;
2900  unsigned AddressSpace;
2901  if (explicitType) {
2902  AddressSpace = Record[1] >> 2;
2903  } else {
2904  if (!Ty->isPointerTy())
2905  return error("Invalid type for value");
2906  AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2907  Ty = cast<PointerType>(Ty)->getElementType();
2908  }
2909 
2910  uint64_t RawLinkage = Record[3];
2911  GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2912  unsigned Alignment;
2913  if (Error Err = parseAlignmentValue(Record[4], Alignment))
2914  return Err;
2915  std::string Section;
2916  if (Record[5]) {
2917  if (Record[5] - 1 >= SectionTable.size())
2918  return error("Invalid ID");
2919  Section = SectionTable[Record[5] - 1];
2920  }
2922  // Local linkage must have default visibility.
2923  if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2924  // FIXME: Change to an error if non-default in 4.0.
2925  Visibility = getDecodedVisibility(Record[6]);
2926 
2928  if (Record.size() > 7)
2929  TLM = getDecodedThreadLocalMode(Record[7]);
2930 
2932  if (Record.size() > 8)
2933  UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2934 
2935  bool ExternallyInitialized = false;
2936  if (Record.size() > 9)
2937  ExternallyInitialized = Record[9];
2938 
2939  GlobalVariable *NewGV =
2940  new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
2941  nullptr, TLM, AddressSpace, ExternallyInitialized);
2942  NewGV->setAlignment(Alignment);
2943  if (!Section.empty())
2944  NewGV->setSection(Section);
2945  NewGV->setVisibility(Visibility);
2946  NewGV->setUnnamedAddr(UnnamedAddr);
2947 
2948  if (Record.size() > 10)
2949  NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2950  else
2951  upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2952 
2953  ValueList.push_back(NewGV);
2954 
2955  // Remember which value to use for the global initializer.
2956  if (unsigned InitID = Record[2])
2957  GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
2958 
2959  if (Record.size() > 11) {
2960  if (unsigned ComdatID = Record[11]) {
2961  if (ComdatID > ComdatList.size())
2962  return error("Invalid global variable comdat ID");
2963  NewGV->setComdat(ComdatList[ComdatID - 1]);
2964  }
2965  } else if (hasImplicitComdat(RawLinkage)) {
2966  NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2967  }
2968 
2969  if (Record.size() > 12) {
2970  auto AS = getAttributes(Record[12]).getFnAttributes();
2971  NewGV->setAttributes(AS);
2972  }
2973 
2974  if (Record.size() > 13) {
2975  NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
2976  }
2977  inferDSOLocal(NewGV);
2978 
2979  return Error::success();
2980 }
2981 
2982 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
2983  // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
2984  // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
2985  // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
2986  // v2: [strtab_offset, strtab_size, v1]
2987  StringRef Name;
2988  std::tie(Name, Record) = readNameFromStrtab(Record);
2989 
2990  if (Record.size() < 8)
2991  return error("Invalid record");
2992  Type *Ty = getTypeByID(Record[0]);
2993  if (!Ty)
2994  return error("Invalid record");
2995  if (auto *PTy = dyn_cast<PointerType>(Ty))
2996  Ty = PTy->getElementType();
2997  auto *FTy = dyn_cast<FunctionType>(Ty);
2998  if (!FTy)
2999  return error("Invalid type for value");
3000  auto CC = static_cast<CallingConv::ID>(Record[1]);
3001  if (CC & ~CallingConv::MaxID)
3002  return error("Invalid calling convention ID");
3003 
3004  unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3005  if (Record.size() > 16)
3006  AddrSpace = Record[16];
3007 
3009  AddrSpace, Name, TheModule);
3010 
3011  Func->setCallingConv(CC);
3012  bool isProto = Record[2];
3013  uint64_t RawLinkage = Record[3];
3014  Func->setLinkage(getDecodedLinkage(RawLinkage));
3015  Func->setAttributes(getAttributes(Record[4]));
3016 
3017  unsigned Alignment;
3018  if (Error Err = parseAlignmentValue(Record[5], Alignment))
3019  return Err;
3020  Func->setAlignment(Alignment);
3021  if (Record[6]) {
3022  if (Record[6] - 1 >= SectionTable.size())
3023  return error("Invalid ID");
3024  Func->setSection(SectionTable[Record[6] - 1]);
3025  }
3026  // Local linkage must have default visibility.
3027  if (!Func->hasLocalLinkage())
3028  // FIXME: Change to an error if non-default in 4.0.
3029  Func->setVisibility(getDecodedVisibility(Record[7]));
3030  if (Record.size() > 8 && Record[8]) {
3031  if (Record[8] - 1 >= GCTable.size())
3032  return error("Invalid ID");
3033  Func->setGC(GCTable[Record[8] - 1]);
3034  }
3036  if (Record.size() > 9)
3037  UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3038  Func->setUnnamedAddr(UnnamedAddr);
3039  if (Record.size() > 10 && Record[10] != 0)
3040  FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
3041 
3042  if (Record.size() > 11)
3043  Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3044  else
3045  upgradeDLLImportExportLinkage(Func, RawLinkage);
3046 
3047  if (Record.size() > 12) {
3048  if (unsigned ComdatID = Record[12]) {
3049  if (ComdatID > ComdatList.size())
3050  return error("Invalid function comdat ID");
3051  Func->setComdat(ComdatList[ComdatID - 1]);
3052  }
3053  } else if (hasImplicitComdat(RawLinkage)) {
3054  Func->setComdat(reinterpret_cast<Comdat *>(1));
3055  }
3056 
3057  if (Record.size() > 13 && Record[13] != 0)
3058  FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
3059 
3060  if (Record.size() > 14 && Record[14] != 0)
3061  FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3062 
3063  if (Record.size() > 15) {
3064  Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3065  }
3066  inferDSOLocal(Func);
3067 
3068  ValueList.push_back(Func);
3069 
3070  // If this is a function with a body, remember the prototype we are
3071  // creating now, so that we can match up the body with them later.
3072  if (!isProto) {
3073  Func->setIsMaterializable(true);
3074  FunctionsWithBodies.push_back(Func);
3075  DeferredFunctionInfo[Func] = 0;
3076  }
3077  return Error::success();
3078 }
3079 
3080 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3081  unsigned BitCode, ArrayRef<uint64_t> Record) {
3082  // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3083  // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3084  // dllstorageclass, threadlocal, unnamed_addr,
3085  // preemption specifier] (name in VST)
3086  // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3087  // visibility, dllstorageclass, threadlocal, unnamed_addr,
3088  // preemption specifier] (name in VST)
3089  // v2: [strtab_offset, strtab_size, v1]
3090  StringRef Name;
3091  std::tie(Name, Record) = readNameFromStrtab(Record);
3092 
3093  bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3094  if (Record.size() < (3 + (unsigned)NewRecord))
3095  return error("Invalid record");
3096  unsigned OpNum = 0;
3097  Type *Ty = getTypeByID(Record[OpNum++]);
3098  if (!Ty)
3099  return error("Invalid record");
3100 
3101  unsigned AddrSpace;
3102  if (!NewRecord) {
3103  auto *PTy = dyn_cast<PointerType>(Ty);
3104  if (!PTy)
3105  return error("Invalid type for value");
3106  Ty = PTy->getElementType();
3107  AddrSpace = PTy->getAddressSpace();
3108  } else {
3109  AddrSpace = Record[OpNum++];
3110  }
3111 
3112  auto Val = Record[OpNum++];
3113  auto Linkage = Record[OpNum++];
3114  GlobalIndirectSymbol *NewGA;
3115  if (BitCode == bitc::MODULE_CODE_ALIAS ||
3116  BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3117  NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3118  TheModule);
3119  else
3120  NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3121  nullptr, TheModule);
3122  // Old bitcode files didn't have visibility field.
3123  // Local linkage must have default visibility.
3124  if (OpNum != Record.size()) {
3125  auto VisInd = OpNum++;
3126  if (!NewGA->hasLocalLinkage())
3127  // FIXME: Change to an error if non-default in 4.0.
3128  NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3129  }
3130  if (BitCode == bitc::MODULE_CODE_ALIAS ||
3131  BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
3132  if (OpNum != Record.size())
3133  NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3134  else
3135  upgradeDLLImportExportLinkage(NewGA, Linkage);
3136  if (OpNum != Record.size())
3137  NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3138  if (OpNum != Record.size())
3139  NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3140  }
3141  if (OpNum != Record.size())
3142  NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3143  inferDSOLocal(NewGA);
3144 
3145  ValueList.push_back(NewGA);
3146  IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3147  return Error::success();
3148 }
3149 
3150 Error BitcodeReader::parseModule(uint64_t ResumeBit,
3151  bool ShouldLazyLoadMetadata) {
3152  if (ResumeBit)
3153  Stream.JumpToBit(ResumeBit);
3154  else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3155  return error("Invalid record");
3156 
3158 
3159  // Read all the records for this module.
3160  while (true) {
3161  BitstreamEntry Entry = Stream.advance();
3162 
3163  switch (Entry.Kind) {
3164  case BitstreamEntry::Error:
3165  return error("Malformed block");
3167  return globalCleanup();
3168 
3170  switch (Entry.ID) {
3171  default: // Skip unknown content.
3172  if (Stream.SkipBlock())
3173  return error("Invalid record");
3174  break;
3176  if (readBlockInfo())
3177  return error("Malformed block");
3178  break;
3180  if (Error Err = parseAttributeBlock())
3181  return Err;
3182  break;
3184  if (Error Err = parseAttributeGroupBlock())
3185  return Err;
3186  break;
3188  if (Error Err = parseTypeTable())
3189  return Err;
3190  break;
3192  if (!SeenValueSymbolTable) {
3193  // Either this is an old form VST without function index and an
3194  // associated VST forward declaration record (which would have caused
3195  // the VST to be jumped to and parsed before it was encountered
3196  // normally in the stream), or there were no function blocks to
3197  // trigger an earlier parsing of the VST.
3198  assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3199  if (Error Err = parseValueSymbolTable())
3200  return Err;
3201  SeenValueSymbolTable = true;
3202  } else {
3203  // We must have had a VST forward declaration record, which caused
3204  // the parser to jump to and parse the VST earlier.
3205  assert(VSTOffset > 0);
3206  if (Stream.SkipBlock())
3207  return error("Invalid record");
3208  }
3209  break;
3211  if (Error Err = parseConstants())
3212  return Err;
3213  if (Error Err = resolveGlobalAndIndirectSymbolInits())
3214  return Err;
3215  break;
3217  if (ShouldLazyLoadMetadata) {
3218  if (Error Err = rememberAndSkipMetadata())
3219  return Err;
3220  break;
3221  }
3222  assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3223  if (Error Err = MDLoader->parseModuleMetadata())
3224  return Err;
3225  break;
3227  if (Error Err = MDLoader->parseMetadataKinds())
3228  return Err;
3229  break;
3231  // If this is the first function body we've seen, reverse the
3232  // FunctionsWithBodies list.
3233  if (!SeenFirstFunctionBody) {
3234  std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3235  if (Error Err = globalCleanup())
3236  return Err;
3237  SeenFirstFunctionBody = true;
3238  }
3239 
3240  if (VSTOffset > 0) {
3241  // If we have a VST forward declaration record, make sure we
3242  // parse the VST now if we haven't already. It is needed to
3243  // set up the DeferredFunctionInfo vector for lazy reading.
3244  if (!SeenValueSymbolTable) {
3245  if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3246  return Err;
3247  SeenValueSymbolTable = true;
3248  // Fall through so that we record the NextUnreadBit below.
3249  // This is necessary in case we have an anonymous function that
3250  // is later materialized. Since it will not have a VST entry we
3251  // need to fall back to the lazy parse to find its offset.
3252  } else {
3253  // If we have a VST forward declaration record, but have already
3254  // parsed the VST (just above, when the first function body was
3255  // encountered here), then we are resuming the parse after
3256  // materializing functions. The ResumeBit points to the
3257  // start of the last function block recorded in the
3258  // DeferredFunctionInfo map. Skip it.
3259  if (Stream.SkipBlock())
3260  return error("Invalid record");
3261  continue;
3262  }
3263  }
3264 
3265  // Support older bitcode files that did not have the function
3266  // index in the VST, nor a VST forward declaration record, as
3267  // well as anonymous functions that do not have VST entries.
3268  // Build the DeferredFunctionInfo vector on the fly.
3269  if (Error Err = rememberAndSkipFunctionBody())
3270  return Err;
3271 
3272  // Suspend parsing when we reach the function bodies. Subsequent
3273  // materialization calls will resume it when necessary. If the bitcode
3274  // file is old, the symbol table will be at the end instead and will not
3275  // have been seen yet. In this case, just finish the parse now.
3276  if (SeenValueSymbolTable) {
3277  NextUnreadBit = Stream.GetCurrentBitNo();
3278  // After the VST has been parsed, we need to make sure intrinsic name
3279  // are auto-upgraded.
3280  return globalCleanup();
3281  }
3282  break;
3284  if (Error Err = parseUseLists())
3285  return Err;
3286  break;
3288  if (Error Err = parseOperandBundleTags())
3289  return Err;
3290  break;
3292  if (Error Err = parseSyncScopeNames())
3293  return Err;
3294  break;
3295  }
3296  continue;
3297 
3299  // The interesting case.
3300  break;
3301  }
3302 
3303  // Read a record.
3304  auto BitCode = Stream.readRecord(Entry.ID, Record);
3305  switch (BitCode) {
3306  default: break; // Default behavior, ignore unknown content.
3308  Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3309  if (!VersionOrErr)
3310  return VersionOrErr.takeError();
3311  UseRelativeIDs = *VersionOrErr >= 1;
3312  break;
3313  }
3314  case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3315  std::string S;
3316  if (convertToString(Record, 0, S))
3317  return error("Invalid record");
3318  TheModule->setTargetTriple(S);
3319  break;
3320  }
3321  case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3322  std::string S;
3323  if (convertToString(Record, 0, S))
3324  return error("Invalid record");
3325  TheModule->setDataLayout(S);
3326  break;
3327  }
3328  case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3329  std::string S;
3330  if (convertToString(Record, 0, S))
3331  return error("Invalid record");
3332  TheModule->setModuleInlineAsm(S);
3333  break;
3334  }
3335  case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3336  // FIXME: Remove in 4.0.
3337  std::string S;
3338  if (convertToString(Record, 0, S))
3339  return error("Invalid record");
3340  // Ignore value.
3341  break;
3342  }
3343  case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3344  std::string S;
3345  if (convertToString(Record, 0, S))
3346  return error("Invalid record");
3347  SectionTable.push_back(S);
3348  break;
3349  }
3350  case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3351  std::string S;
3352  if (convertToString(Record, 0, S))
3353  return error("Invalid record");
3354  GCTable.push_back(S);
3355  break;
3356  }
3358  if (Error Err = parseComdatRecord(Record))
3359  return Err;
3360  break;
3362  if (Error Err = parseGlobalVarRecord(Record))
3363  return Err;
3364  break;
3366  if (Error Err = parseFunctionRecord(Record))
3367  return Err;
3368  break;
3372  if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3373  return Err;
3374  break;
3375  /// MODULE_CODE_VSTOFFSET: [offset]
3377  if (Record.size() < 1)
3378  return error("Invalid record");
3379  // Note that we subtract 1 here because the offset is relative to one word
3380  // before the start of the identification or module block, which was
3381  // historically always the start of the regular bitcode header.
3382  VSTOffset = Record[0] - 1;
3383  break;
3384  /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3387  if (convertToString(Record, 0, ValueName))
3388  return error("Invalid record");
3389  TheModule->setSourceFileName(ValueName);
3390  break;
3391  }
3392  Record.clear();
3393  }
3394 }
3395 
3396 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3397  bool IsImporting) {
3398  TheModule = M;
3399  MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3400  [&](unsigned ID) { return getTypeByID(ID); });
3401  return parseModule(0, ShouldLazyLoadMetadata);
3402 }
3403 
3404 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3405  if (!isa<PointerType>(PtrType))
3406  return error("Load/Store operand is not a pointer type");
3407  Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3408 
3409  if (ValType && ValType != ElemType)
3410  return error("Explicit load/store type does not match pointee "
3411  "type of pointer operand");
3413  return error("Cannot load/store from pointer");
3414  return Error::success();
3415 }
3416 
3417 /// Lazily parse the specified function body block.
3418 Error BitcodeReader::parseFunctionBody(Function *F) {
3420  return error("Invalid record");
3421 
3422  // Unexpected unresolved metadata when parsing function.
3423  if (MDLoader->hasFwdRefs())
3424  return error("Invalid function metadata: incoming forward references");
3425 
3426  InstructionList.clear();
3427  unsigned ModuleValueListSize = ValueList.size();
3428  unsigned ModuleMDLoaderSize = MDLoader->size();
3429 
3430  // Add all the function arguments to the value table.
3431  for (Argument &I : F->args())
3432  ValueList.push_back(&I);
3433 
3434  unsigned NextValueNo = ValueList.size();
3435  BasicBlock *CurBB = nullptr;
3436  unsigned CurBBNo = 0;
3437 
3438  DebugLoc LastLoc;
3439  auto getLastInstruction = [&]() -> Instruction * {
3440  if (CurBB && !CurBB->empty())
3441  return &CurBB->back();
3442  else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3443  !FunctionBBs[CurBBNo - 1]->empty())
3444  return &FunctionBBs[CurBBNo - 1]->back();
3445  return nullptr;
3446  };
3447 
3448  std::vector<OperandBundleDef> OperandBundles;
3449 
3450  // Read all the records.
3452 
3453  while (true) {
3454  BitstreamEntry Entry = Stream.advance();
3455 
3456  switch (Entry.Kind) {
3457  case BitstreamEntry::Error:
3458  return error("Malformed block");
3460  goto OutOfRecordLoop;
3461 
3463  switch (Entry.ID) {
3464  default: // Skip unknown content.
3465  if (Stream.SkipBlock())
3466  return error("Invalid record");
3467  break;
3469  if (Error Err = parseConstants())
3470  return Err;
3471  NextValueNo = ValueList.size();
3472  break;
3474  if (Error Err = parseValueSymbolTable())
3475  return Err;
3476  break;
3478  if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3479  return Err;
3480  break;
3482  assert(DeferredMetadataInfo.empty() &&
3483  "Must read all module-level metadata before function-level");
3484  if (Error Err = MDLoader->parseFunctionMetadata())
3485  return Err;
3486  break;
3488  if (Error Err = parseUseLists())
3489  return Err;
3490  break;
3491  }
3492  continue;
3493 
3495  // The interesting case.
3496  break;
3497  }
3498 
3499  // Read a record.
3500  Record.clear();
3501  Instruction *I = nullptr;
3502  unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3503  switch (BitCode) {
3504  default: // Default behavior: reject
3505  return error("Invalid value");
3506  case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3507  if (Record.size() < 1 || Record[0] == 0)
3508  return error("Invalid record");
3509  // Create all the basic blocks for the function.
3510  FunctionBBs.resize(Record[0]);
3511 
3512  // See if anything took the address of blocks in this function.
3513  auto BBFRI = BasicBlockFwdRefs.find(F);
3514  if (BBFRI == BasicBlockFwdRefs.end()) {
3515  for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3516  FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3517  } else {
3518  auto &BBRefs = BBFRI->second;
3519  // Check for invalid basic block references.
3520  if (BBRefs.size() > FunctionBBs.size())
3521  return error("Invalid ID");
3522  assert(!BBRefs.empty() && "Unexpected empty array");
3523  assert(!BBRefs.front() && "Invalid reference to entry block");
3524  for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3525  ++I)
3526  if (I < RE && BBRefs[I]) {
3527  BBRefs[I]->insertInto(F);
3528  FunctionBBs[I] = BBRefs[I];
3529  } else {
3530  FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3531  }
3532 
3533  // Erase from the table.
3534  BasicBlockFwdRefs.erase(BBFRI);
3535  }
3536 
3537  CurBB = FunctionBBs[0];
3538  continue;
3539  }
3540 
3541  case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3542  // This record indicates that the last instruction is at the same
3543  // location as the previous instruction with a location.
3544  I = getLastInstruction();
3545 
3546  if (!I)
3547  return error("Invalid record");
3548  I->setDebugLoc(LastLoc);
3549  I = nullptr;
3550  continue;
3551 
3552  case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3553  I = getLastInstruction();
3554  if (!I || Record.size() < 4)
3555  return error("Invalid record");
3556 
3557  unsigned Line = Record[0], Col = Record[1];
3558  unsigned ScopeID = Record[2], IAID = Record[3];
3559  bool isImplicitCode = Record.size() == 5 && Record[4];
3560 
3561  MDNode *Scope = nullptr, *IA = nullptr;
3562  if (ScopeID) {
3563  Scope = dyn_cast_or_null<MDNode>(
3564  MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
3565  if (!Scope)
3566  return error("Invalid record");
3567  }
3568  if (IAID) {
3569  IA = dyn_cast_or_null<MDNode>(
3570  MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
3571  if (!IA)
3572  return error("Invalid record");
3573  }
3574  LastLoc = DebugLoc::get(Line, Col, Scope, IA, isImplicitCode);
3575  I->setDebugLoc(LastLoc);
3576  I = nullptr;
3577  continue;
3578  }
3579  case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
3580  unsigned OpNum = 0;
3581  Value *LHS;
3582  if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3583  OpNum+1 > Record.size())
3584  return error("Invalid record");
3585 
3586  int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
3587  if (Opc == -1)
3588  return error("Invalid record");
3590  InstructionList.push_back(I);
3591  if (OpNum < Record.size()) {
3592  if (isa<FPMathOperator>(I)) {
3593  FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3594  if (FMF.any())
3595  I->setFastMathFlags(FMF);
3596  }
3597  }
3598  break;
3599  }
3600  case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3601  unsigned OpNum = 0;
3602  Value *LHS, *RHS;
3603  if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3604  popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3605  OpNum+1 > Record.size())
3606  return error("Invalid record");
3607 
3608  int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3609  if (Opc == -1)
3610  return error("Invalid record");
3611  I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3612  InstructionList.push_back(I);
3613  if (OpNum < Record.size()) {
3614  if (Opc == Instruction::Add ||
3615  Opc == Instruction::Sub ||
3616  Opc == Instruction::Mul ||
3617  Opc == Instruction::Shl) {
3618  if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3619  cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3620  if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3621  cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3622  } else if (Opc == Instruction::SDiv ||
3623  Opc == Instruction::UDiv ||
3624  Opc == Instruction::LShr ||
3625  Opc == Instruction::AShr) {
3626  if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3627  cast<BinaryOperator>(I)->setIsExact(true);
3628  } else if (isa<FPMathOperator>(I)) {
3629  FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3630  if (FMF.any())
3631  I->setFastMathFlags(FMF);
3632  }
3633 
3634  }
3635  break;
3636  }
3637  case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3638  unsigned OpNum = 0;
3639  Value *Op;
3640  if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3641  OpNum+2 != Record.size())
3642  return error("Invalid record");
3643 
3644  Type *ResTy = getTypeByID(Record[OpNum]);
3645  int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3646  if (Opc == -1 || !ResTy)
3647  return error("Invalid record");
3648  Instruction *Temp = nullptr;
3649  if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3650  if (Temp) {
3651  InstructionList.push_back(Temp);
3652  CurBB->getInstList().push_back(Temp);
3653  }
3654  } else {
3655  auto CastOp = (Instruction::CastOps)Opc;
3656  if (!CastInst::castIsValid(CastOp, Op, ResTy))
3657  return error("Invalid cast");
3658  I = CastInst::Create(CastOp, Op, ResTy);
3659  }
3660  InstructionList.push_back(I);
3661  break;
3662  }
3665  case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3666  unsigned OpNum = 0;
3667 
3668  Type *Ty;
3669  bool InBounds;
3670 
3671  if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3672  InBounds = Record[OpNum++];
3673  Ty = getTypeByID(Record[OpNum++]);
3674  } else {
3675  InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3676  Ty = nullptr;
3677  }
3678 
3679  Value *BasePtr;
3680  if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3681  return error("Invalid record");
3682 
3683  if (!Ty)
3684  Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
3685  ->getElementType();
3686  else if (Ty !=
3687  cast<PointerType>(BasePtr->getType()->getScalarType())
3688  ->getElementType())
3689  return error(
3690  "Explicit gep type does not match pointee type of pointer operand");
3691 
3692  SmallVector<Value*, 16> GEPIdx;
3693  while (OpNum != Record.size()) {
3694  Value *Op;
3695  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3696  return error("Invalid record");
3697  GEPIdx.push_back(Op);
3698  }
3699 
3700  I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3701 
3702  InstructionList.push_back(I);
3703  if (InBounds)
3704  cast<GetElementPtrInst>(I)->setIsInBounds(true);
3705  break;
3706  }
3707 
3709  // EXTRACTVAL: [opty, opval, n x indices]
3710  unsigned OpNum = 0;
3711  Value *Agg;
3712  if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3713  return error("Invalid record");
3714 
3715  unsigned RecSize = Record.size();
3716  if (OpNum == RecSize)
3717  return error("EXTRACTVAL: Invalid instruction with 0 indices");
3718 
3719  SmallVector<unsigned, 4> EXTRACTVALIdx;
3720  Type *CurTy = Agg->getType();
3721  for (; OpNum != RecSize; ++OpNum) {
3722  bool IsArray = CurTy->isArrayTy();
3723  bool IsStruct = CurTy->isStructTy();
3724  uint64_t Index = Record[OpNum];
3725 
3726  if (!IsStruct && !IsArray)
3727  return error("EXTRACTVAL: Invalid type");
3728  if ((unsigned)Index != Index)
3729  return error("Invalid value");
3730  if (IsStruct && Index >= CurTy->getStructNumElements())
3731  return error("EXTRACTVAL: Invalid struct index");
3732  if (IsArray && Index >= CurTy->getArrayNumElements())
3733  return error("EXTRACTVAL: Invalid array index");
3734  EXTRACTVALIdx.push_back((unsigned)Index);
3735 
3736  if (IsStruct)
3737  CurTy = CurTy->getStructElementType(Index);
3738  else
3739  CurTy = CurTy->getArrayElementType();
3740  }
3741 
3742  I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3743  InstructionList.push_back(I);
3744  break;
3745  }
3746 
3748  // INSERTVAL: [opty, opval, opty, opval, n x indices]
3749  unsigned OpNum = 0;
3750  Value *Agg;
3751  if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3752  return error("Invalid record");
3753  Value *Val;
3754  if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3755  return error("Invalid record");
3756 
3757  unsigned RecSize = Record.size();
3758  if (OpNum == RecSize)
3759  return error("INSERTVAL: Invalid instruction with 0 indices");
3760 
3761  SmallVector<unsigned, 4> INSERTVALIdx;
3762  Type *CurTy = Agg->getType();
3763  for (; OpNum != RecSize; ++OpNum) {
3764  bool IsArray = CurTy->isArrayTy();
3765  bool IsStruct = CurTy->isStructTy();
3766  uint64_t Index = Record[OpNum];
3767 
3768  if (!IsStruct && !IsArray)
3769  return error("INSERTVAL: Invalid type");
3770  if ((unsigned)Index != Index)
3771  return error("Invalid value");
3772  if (IsStruct && Index >= CurTy->getStructNumElements())
3773  return error("INSERTVAL: Invalid struct index");
3774  if (IsArray && Index >= CurTy->getArrayNumElements())
3775  return error("INSERTVAL: Invalid array index");
3776 
3777  INSERTVALIdx.push_back((unsigned)Index);
3778  if (IsStruct)
3779  CurTy = CurTy->getStructElementType(Index);
3780  else
3781  CurTy = CurTy->getArrayElementType();
3782  }
3783 
3784  if (CurTy != Val->getType())
3785  return error("Inserted value type doesn't match aggregate type");
3786 
3787  I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3788  InstructionList.push_back(I);
3789  break;
3790  }
3791 
3792  case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3793  // obsolete form of select
3794  // handles select i1 ... in old bitcode
3795  unsigned OpNum = 0;
3796  Value *TrueVal, *FalseVal, *Cond;
3797  if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3798  popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3799  popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3800  return error("Invalid record");
3801 
3802  I = SelectInst::Create(Cond, TrueVal, FalseVal);
3803  InstructionList.push_back(I);
3804  break;
3805  }
3806 
3807  case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3808  // new form of select
3809  // handles select i1 or select [N x i1]
3810  unsigned OpNum = 0;
3811  Value *TrueVal, *FalseVal, *Cond;
3812  if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3813  popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3814  getValueTypePair(Record, OpNum, NextValueNo, Cond))
3815  return error("Invalid record");
3816 
3817  // select condition can be either i1 or [N x i1]
3818  if (VectorType* vector_type =
3819  dyn_cast<VectorType>(Cond->getType())) {
3820  // expect <n x i1>
3821  if (vector_type->getElementType() != Type::getInt1Ty(Context))
3822  return error("Invalid type for value");
3823  } else {
3824  // expect i1
3825  if (Cond->getType() != Type::getInt1Ty(Context))
3826  return error("Invalid type for value");
3827  }
3828 
3829  I = SelectInst::Create(Cond, TrueVal, FalseVal);
3830  InstructionList.push_back(I);
3831  break;
3832  }
3833 
3834  case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3835  unsigned OpNum = 0;
3836  Value *Vec, *Idx;
3837  if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3838  getValueTypePair(Record, OpNum, NextValueNo, Idx))
3839  return error("Invalid record");
3840  if (!Vec->getType()->isVectorTy())
3841  return error("Invalid type for value");
3842  I = ExtractElementInst::Create(Vec, Idx);
3843  InstructionList.push_back(I);
3844  break;
3845  }
3846 
3847  case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3848  unsigned OpNum = 0;
3849  Value *Vec, *Elt, *Idx;
3850  if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3851  return error("Invalid record");
3852  if (!Vec->getType()->isVectorTy())
3853  return error("Invalid type for value");
3854  if (popValue(Record, OpNum, NextValueNo,
3855  cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3856  getValueTypePair(Record, OpNum, NextValueNo, Idx))
3857  return error("Invalid record");
3858  I = InsertElementInst::Create(Vec, Elt, Idx);
3859  InstructionList.push_back(I);
3860  break;
3861  }
3862 
3863  case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3864  unsigned OpNum = 0;
3865  Value *Vec1, *Vec2, *Mask;
3866  if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3867  popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3868  return error("Invalid record");
3869 
3870  if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3871  return error("Invalid record");
3872  if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3873  return error("Invalid type for value");
3874  I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3875  InstructionList.push_back(I);
3876  break;
3877  }
3878 
3879  case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3880  // Old form of ICmp/FCmp returning bool
3881  // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3882  // both legal on vectors but had different behaviour.
3883  case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3884  // FCmp/ICmp returning bool or vector of bool
3885 
3886  unsigned OpNum = 0;
3887  Value *LHS, *RHS;
3888  if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3889  popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3890  return error("Invalid record");
3891 
3892  unsigned PredVal = Record[OpNum];
3893  bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3894  FastMathFlags FMF;
3895  if (IsFP && Record.size() > OpNum+1)
3896  FMF = getDecodedFastMathFlags(Record[++OpNum]);
3897 
3898  if (OpNum+1 != Record.size())
3899  return error("Invalid record");
3900 
3901  if (LHS->getType()->isFPOrFPVectorTy())
3902  I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3903  else
3904  I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3905 
3906  if (FMF.any())
3907  I->setFastMathFlags(FMF);
3908  InstructionList.push_back(I);
3909  break;
3910  }
3911 
3912  case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3913  {
3914  unsigned Size = Record.size();
3915  if (Size == 0) {
3916  I = ReturnInst::Create(Context);
3917  InstructionList.push_back(I);
3918  break;
3919  }
3920 
3921  unsigned OpNum = 0;
3922  Value *Op = nullptr;
3923  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3924  return error("Invalid record");
3925  if (OpNum != Record.size())
3926  return error("Invalid record");
3927 
3928  I = ReturnInst::Create(Context, Op);
3929  InstructionList.push_back(I);
3930  break;
3931  }
3932  case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3933  if (Record.size() != 1 && Record.size() != 3)
3934  return error("Invalid record");
3935  BasicBlock *TrueDest = getBasicBlock(Record[0]);
3936  if (!TrueDest)
3937  return error("Invalid record");
3938 
3939  if (Record.size() == 1) {
3940  I = BranchInst::Create(TrueDest);
3941  InstructionList.push_back(I);
3942  }
3943  else {
3944  BasicBlock *FalseDest = getBasicBlock(Record[1]);
3945  Value *Cond = getValue(Record, 2, NextValueNo,
3946  Type::getInt1Ty(Context));
3947  if (!FalseDest || !Cond)
3948  return error("Invalid record");
3949  I = BranchInst::Create(TrueDest, FalseDest, Cond);
3950  InstructionList.push_back(I);
3951  }
3952  break;
3953  }
3954  case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
3955  if (Record.size() != 1 && Record.size() != 2)
3956  return error("Invalid record");
3957  unsigned Idx = 0;
3958  Value *CleanupPad =
3959  getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3960  if (!CleanupPad)
3961  return error("Invalid record");
3962  BasicBlock *UnwindDest = nullptr;
3963  if (Record.size() == 2) {
3964  UnwindDest = getBasicBlock(Record[Idx++]);
3965  if (!UnwindDest)
3966  return error("Invalid record");
3967  }
3968 
3969  I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
3970  InstructionList.push_back(I);
3971  break;
3972  }
3973  case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3974  if (Record.size() != 2)
3975  return error("Invalid record");
3976  unsigned Idx = 0;
3977  Value *CatchPad =
3978  getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3979  if (!CatchPad)
3980  return error("Invalid record");
3981  BasicBlock *BB = getBasicBlock(Record[Idx++]);
3982  if (!BB)
3983  return error("Invalid record");
3984 
3985  I = CatchReturnInst::Create(CatchPad, BB);
3986  InstructionList.push_back(I);
3987  break;
3988  }
3989  case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3990  // We must have, at minimum, the outer scope and the number of arguments.
3991  if (Record.size() < 2)
3992  return error("Invalid record");
3993 
3994  unsigned Idx = 0;
3995 
3996  Value *ParentPad =
3997  getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3998 
3999  unsigned NumHandlers = Record[Idx++];
4000 
4002  for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4003  BasicBlock *BB = getBasicBlock(Record[Idx++]);
4004  if (!BB)
4005  return error("Invalid record");
4006  Handlers.push_back(BB);
4007  }
4008 
4009  BasicBlock *UnwindDest = nullptr;
4010  if (Idx + 1 == Record.size()) {
4011  UnwindDest = getBasicBlock(Record[Idx++]);
4012  if (!UnwindDest)
4013  return error("Invalid record");
4014  }
4015 
4016  if (Record.size() != Idx)
4017  return error("Invalid record");
4018 
4019  auto *CatchSwitch =
4020  CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4021  for (BasicBlock *Handler : Handlers)
4022  CatchSwitch->addHandler(Handler);
4023  I = CatchSwitch;
4024  InstructionList.push_back(I);
4025  break;
4026  }
4028  case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4029  // We must have, at minimum, the outer scope and the number of arguments.
4030  if (Record.size() < 2)
4031  return error("Invalid record");
4032 
4033  unsigned Idx = 0;
4034 
4035  Value *ParentPad =
4036  getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4037 
4038  unsigned NumArgOperands = Record[Idx++];
4039 
4041  for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4042  Value *Val;
4043  if (getValueTypePair(Record, Idx, NextValueNo, Val))
4044  return error("Invalid record");
4045  Args.push_back(Val);
4046  }
4047 
4048  if (Record.size() != Idx)
4049  return error("Invalid record");
4050 
4051  if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4052  I = CleanupPadInst::Create(ParentPad, Args);
4053  else
4054  I = CatchPadInst::Create(ParentPad, Args);
4055  InstructionList.push_back(I);
4056  break;
4057  }
4058  case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4059  // Check magic
4060  if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4061  // "New" SwitchInst format with case ranges. The changes to write this
4062  // format were reverted but we still recognize bitcode that uses it.
4063  // Hopefully someday we will have support for case ranges and can use
4064  // this format again.
4065 
4066  Type *OpTy = getTypeByID(Record[1]);
4067  unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4068 
4069  Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4070  BasicBlock *Default = getBasicBlock(Record[3]);
4071  if (!OpTy || !Cond || !Default)
4072  return error("Invalid record");
4073 
4074  unsigned NumCases = Record[4];
4075 
4076  SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4077  InstructionList.push_back(SI);
4078 
4079  unsigned CurIdx = 5;
4080  for (unsigned i = 0; i != NumCases; ++i) {
4082  unsigned NumItems = Record[CurIdx++];
4083  for (unsigned ci = 0; ci != NumItems; ++ci) {
4084  bool isSingleNumber = Record[CurIdx++];
4085 
4086  APInt Low;
4087  unsigned ActiveWords = 1;
4088  if (ValueBitWidth > 64)
4089  ActiveWords = Record[CurIdx++];
4090  Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4091  ValueBitWidth);
4092  CurIdx += ActiveWords;
4093 
4094  if (!isSingleNumber) {
4095  ActiveWords = 1;
4096  if (ValueBitWidth > 64)
4097  ActiveWords = Record[CurIdx++];
4099  makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4100  CurIdx += ActiveWords;
4101 
4102  // FIXME: It is not clear whether values in the range should be
4103  // compared as signed or unsigned values. The partially
4104  // implemented changes that used this format in the past used
4105  // unsigned comparisons.
4106  for ( ; Low.ule(High); ++Low)
4107  CaseVals.push_back(ConstantInt::get(Context, Low));
4108  } else
4109  CaseVals.push_back(ConstantInt::get(Context, Low));
4110  }
4111  BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4112  for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4113  cve = CaseVals.end(); cvi != cve; ++cvi)
4114  SI->addCase(*cvi, DestBB);
4115  }
4116  I = SI;
4117  break;
4118  }
4119 
4120  // Old SwitchInst format without case ranges.
4121 
4122  if (Record.size() < 3 || (Record.size() & 1) == 0)
4123  return error("Invalid record");
4124  Type *OpTy = getTypeByID(Record[0]);
4125  Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4126  BasicBlock *Default = getBasicBlock(Record[2]);
4127  if (!OpTy || !Cond || !Default)
4128  return error("Invalid record");
4129  unsigned NumCases = (Record.size()-3)/2;
4130  SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4131  InstructionList.push_back(SI);
4132  for (unsigned i = 0, e = NumCases; i != e; ++i) {
4133  ConstantInt *CaseVal =
4134  dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4135  BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4136  if (!CaseVal || !DestBB) {
4137  delete SI;
4138  return error("Invalid record");
4139  }
4140  SI->addCase(CaseVal, DestBB);
4141  }
4142  I = SI;
4143  break;
4144  }
4145  case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4146  if (Record.size() < 2)
4147  return error("Invalid record");
4148  Type *OpTy = getTypeByID(Record[0]);
4149  Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4150  if (!OpTy || !Address)
4151  return error("Invalid record");
4152  unsigned NumDests = Record.size()-2;
4153  IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4154  InstructionList.push_back(IBI);
4155  for (unsigned i = 0, e = NumDests; i != e; ++i) {
4156  if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4157  IBI->addDestination(DestBB);
4158  } else {
4159  delete IBI;
4160  return error("Invalid record");
4161  }
4162  }
4163  I = IBI;
4164  break;
4165  }
4166 
4168  // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4169  if (Record.size() < 4)
4170  return error("Invalid record");
4171  unsigned OpNum = 0;
4172  AttributeList PAL = getAttributes(Record[OpNum++]);
4173  unsigned CCInfo = Record[OpNum++];
4174  BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4175  BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4176 
4177  FunctionType *FTy = nullptr;
4178  if (CCInfo >> 13 & 1 &&
4179  !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4180  return error("Explicit invoke type is not a function type");
4181 
4182  Value *Callee;
4183  if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4184  return error("Invalid record");
4185 
4186  PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4187  if (!CalleeTy)
4188  return error("Callee is not a pointer");
4189  if (!FTy) {
4190  FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4191  if (!FTy)
4192  return error("Callee is not of pointer to function type");
4193  } else if (CalleeTy->getElementType() != FTy)
4194  return error("Explicit invoke type does not match pointee type of "
4195  "callee operand");
4196  if (Record.size() < FTy->getNumParams() + OpNum)
4197  return error("Insufficient operands to call");
4198 
4200  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4201  Ops.push_back(getValue(Record, OpNum, NextValueNo,
4202  FTy->getParamType(i)));
4203  if (!Ops.back())
4204  return error("Invalid record");
4205  }
4206 
4207  if (!FTy->isVarArg()) {
4208  if (Record.size() != OpNum)
4209  return error("Invalid record");
4210  } else {
4211  // Read type/value pairs for varargs params.
4212  while (OpNum != Record.size()) {
4213  Value *Op;
4214  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4215  return error("Invalid record");
4216  Ops.push_back(Op);
4217  }
4218  }
4219 
4220  I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
4221  OperandBundles);
4222  OperandBundles.clear();
4223  InstructionList.push_back(I);
4224  cast<InvokeInst>(I)->setCallingConv(
4225  static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4226  cast<InvokeInst>(I)->setAttributes(PAL);
4227  break;
4228  }
4229  case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4230  unsigned Idx = 0;
4231  Value *Val = nullptr;
4232  if (getValueTypePair(Record, Idx, NextValueNo, Val))
4233  return error("Invalid record");
4234  I = ResumeInst::Create(Val);
4235  InstructionList.push_back(I);
4236  break;
4237  }
4239  // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
4240  unsigned OpNum = 0;
4241  AttributeList PAL = getAttributes(Record[OpNum++]);
4242  unsigned CCInfo = Record[OpNum++];
4243 
4244  BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
4245  unsigned NumIndirectDests = Record[OpNum++];
4246  SmallVector<BasicBlock *, 16> IndirectDests;
4247  for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
4248  IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
4249 
4250  FunctionType *FTy = nullptr;
4251  if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4252  !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4253  return error("Explicit call type is not a function type");
4254 
4255  Value *Callee;
4256  if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4257  return error("Invalid record");
4258 
4259  PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4260  if (!OpTy)
4261  return error("Callee is not a pointer type");
4262  if (!FTy) {
4263  FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4264  if (!FTy)
4265  return error("Callee is not of pointer to function type");
4266  } else if (OpTy->getElementType() != FTy)
4267  return error("Explicit call type does not match pointee type of "
4268  "callee operand");
4269  if (Record.size() < FTy->getNumParams() + OpNum)
4270  return error("Insufficient operands to call");
4271 
4273  // Read the fixed params.
4274  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4275  if (FTy->getParamType(i)->isLabelTy())
4276  Args.push_back(getBasicBlock(Record[OpNum]));
4277  else
4278  Args.push_back(getValue(Record, OpNum, NextValueNo,
4279  FTy->getParamType(i)));
4280  if (!Args.back())
4281  return error("Invalid record");
4282  }
4283 
4284  // Read type/value pairs for varargs params.
4285  if (!FTy->isVarArg()) {
4286  if (OpNum != Record.size())
4287  return error("Invalid record");
4288  } else {
4289  while (OpNum != Record.size()) {
4290  Value *Op;
4291  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4292  return error("Invalid record");
4293  Args.push_back(Op);
4294  }
4295  }
4296 
4297  I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
4298  OperandBundles);
4299  OperandBundles.clear();
4300  InstructionList.push_back(I);
4301  cast<CallBrInst>(I)->setCallingConv(
4302  static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4303  cast<CallBrInst>(I)->setAttributes(PAL);
4304  break;
4305  }
4306  case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4307  I = new UnreachableInst(Context);
4308  InstructionList.push_back(I);
4309  break;
4310  case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4311  if (Record.size() < 1 || ((Record.size()-1)&1))
4312  return error("Invalid record");
4313  Type *Ty = getTypeByID(Record[0]);
4314  if (!Ty)
4315  return error("Invalid record");
4316 
4317  PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4318  InstructionList.push_back(PN);
4319 
4320  for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4321  Value *V;
4322  // With the new function encoding, it is possible that operands have
4323  // negative IDs (for forward references). Use a signed VBR
4324  // representation to keep the encoding small.
4325  if (UseRelativeIDs)
4326  V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4327  else
4328  V = getValue(Record, 1+i, NextValueNo, Ty);
4329  BasicBlock *BB = getBasicBlock(Record[2+i]);
4330  if (!V || !BB)
4331  return error("Invalid record");
4332  PN->addIncoming(V, BB);
4333  }
4334  I = PN;
4335  break;
4336  }
4337 
4340  // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4341  unsigned Idx = 0;
4342  if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4343  if (Record.size() < 3)
4344  return error("Invalid record");
4345  } else {
4347  if (Record.size() < 4)
4348  return error("Invalid record");
4349  }
4350  Type *Ty = getTypeByID(Record[Idx++]);
4351  if (!Ty)
4352  return error("Invalid record");
4353  if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4354  Value *PersFn = nullptr;
4355  if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4356  return error("Invalid record");
4357 
4358  if (!F->hasPersonalityFn())
4359  F->setPersonalityFn(cast<Constant>(PersFn));
4360  else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4361  return error("Personality function mismatch");
4362  }
4363 
4364  bool IsCleanup = !!Record[Idx++];
4365  unsigned NumClauses = Record[Idx++];
4366  LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4367  LP->setCleanup(IsCleanup);
4368  for (unsigned J = 0; J != NumClauses; ++J) {
4370  LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4371  Value *Val;
4372 
4373  if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4374  delete LP;
4375  return error("Invalid record");
4376  }
4377 
4378  assert((CT != LandingPadInst::Catch ||
4379  !isa<ArrayType>(Val->getType())) &&
4380  "Catch clause has a invalid type!");
4381  assert((CT != LandingPadInst::Filter ||
4382  isa<ArrayType>(Val->getType())) &&
4383  "Filter clause has invalid type!");
4384  LP->addClause(cast<Constant>(Val));
4385  }
4386 
4387  I = LP;
4388  InstructionList.push_back(I);
4389  break;
4390  }
4391 
4392  case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4393  if (Record.size() != 4)
4394  return error("Invalid record");
4395  uint64_t AlignRecord = Record[3];
4396  const uint64_t InAllocaMask = uint64_t(1) << 5;
4397  const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4398  const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4399  const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4400  SwiftErrorMask;
4401  bool InAlloca = AlignRecord & InAllocaMask;
4402  bool SwiftError = AlignRecord & SwiftErrorMask;
4403  Type *Ty = getTypeByID(Record[0]);
4404  if ((AlignRecord & ExplicitTypeMask) == 0) {
4405  auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4406  if (!PTy)
4407  return error("Old-style alloca with a non-pointer type");
4408  Ty = PTy->getElementType();
4409  }
4410  Type *OpTy = getTypeByID(Record[1]);
4411  Value *Size = getFnValueByID(Record[2], OpTy);
4412  unsigned Align;
4413  if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4414  return Err;
4415  }
4416  if (!Ty || !Size)
4417  return error("Invalid record");
4418 
4419  // FIXME: Make this an optional field.
4420  const DataLayout &DL = TheModule->getDataLayout();
4421  unsigned AS = DL.getAllocaAddrSpace();
4422 
4423  AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
4424  AI->setUsedWithInAlloca(InAlloca);
4425  AI->setSwiftError(SwiftError);
4426  I = AI;
4427  InstructionList.push_back(I);
4428  break;
4429  }
4430  case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4431  unsigned OpNum = 0;
4432  Value *Op;
4433  if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4434  (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4435  return error("Invalid record");
4436 
4437  Type *Ty = nullptr;
4438  if (OpNum + 3 == Record.size())
4439  Ty = getTypeByID(Record[OpNum++]);
4440  if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4441  return Err;
4442  if (!Ty)
4443  Ty = cast<PointerType>(Op->getType())->getElementType();
4444 
4445  unsigned Align;
4446  if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4447  return Err;
4448  I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4449 
4450  InstructionList.push_back(I);
4451  break;
4452  }
4454  // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
4455  unsigned OpNum = 0;
4456  Value *Op;
4457  if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4458  (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4459  return error("Invalid record");
4460 
4461  Type *Ty = nullptr;
4462  if (OpNum + 5 == Record.size())
4463  Ty = getTypeByID(Record[OpNum++]);
4464  if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4465  return Err;
4466  if (!Ty)
4467  Ty = cast<PointerType>(Op->getType())->getElementType();
4468 
4469  AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4470  if (Ordering == AtomicOrdering::NotAtomic ||
4471  Ordering == AtomicOrdering::Release ||
4472  Ordering == AtomicOrdering::AcquireRelease)
4473  return error("Invalid record");
4474  if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4475  return error("Invalid record");
4476  SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4477 
4478  unsigned Align;
4479  if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4480  return Err;
4481  I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align, Ordering, SSID);
4482 
4483  InstructionList.push_back(I);
4484  break;
4485  }
4487  case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4488  unsigned OpNum = 0;
4489  Value *Val, *Ptr;
4490  if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4491  (BitCode == bitc::FUNC_CODE_INST_STORE
4492  ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4493  : popValue(Record, OpNum, NextValueNo,
4494  cast<PointerType>(Ptr->getType())->getElementType(),
4495  Val)) ||
4496  OpNum + 2 != Record.size())
4497  return error("Invalid record");
4498 
4499  if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4500  return Err;
4501  unsigned Align;
4502  if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4503  return Err;
4504  I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4505  InstructionList.push_back(I);
4506  break;
4507  }
4510  // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
4511  unsigned OpNum = 0;
4512  Value *Val, *Ptr;
4513  if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4514  !isa<PointerType>(Ptr->getType()) ||
4516  ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4517  : popValue(Record, OpNum, NextValueNo,
4518  cast<PointerType>(Ptr->getType())->getElementType(),
4519  Val)) ||
4520  OpNum + 4 != Record.size())
4521  return error("Invalid record");
4522 
4523  if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4524  return Err;
4525  AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4526  if (Ordering == AtomicOrdering::NotAtomic ||
4527  Ordering == AtomicOrdering::Acquire ||
4528  Ordering == AtomicOrdering::AcquireRelease)
4529  return error("Invalid record");
4530  SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4531  if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4532  return error("Invalid record");
4533 
4534  unsigned Align;
4535  if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4536  return Err;
4537  I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
4538  InstructionList.push_back(I);
4539  break;
4540  }
4543  // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
4544  // failureordering?, isweak?]
4545  unsigned OpNum = 0;
4546  Value *Ptr, *Cmp, *New;
4547  if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4548  (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4549  ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4550  : popValue(Record, OpNum, NextValueNo,
4551  cast<PointerType>(Ptr->getType())->getElementType(),
4552  Cmp)) ||
4553  popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4554  Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4555  return error("Invalid record");
4556  AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4557  if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4558  SuccessOrdering == AtomicOrdering::Unordered)
4559  return error("Invalid record");
4560  SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
4561 
4562  if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4563  return Err;
4564  AtomicOrdering FailureOrdering;
4565  if (Record.size() < 7)
4566  FailureOrdering =
4568  else
4569  FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4570 
4571  I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4572  SSID);
4573  cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4574 
4575  if (Record.size() < 8) {
4576  // Before weak cmpxchgs existed, the instruction simply returned the
4577  // value loaded from memory, so bitcode files from that era will be
4578  // expecting the first component of a modern cmpxchg.
4579  CurBB->getInstList().push_back(I);
4580  I = ExtractValueInst::Create(I, 0);
4581  } else {
4582  cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4583  }
4584 
4585  InstructionList.push_back(I);
4586  break;
4587  }
4589  // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
4590  unsigned OpNum = 0;
4591  Value *Ptr, *Val;
4592  if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4593  !isa<PointerType>(Ptr->getType()) ||
4594  popValue(Record, OpNum, NextValueNo,
4595  cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4596  OpNum+4 != Record.size())
4597  return error("Invalid record");
4599  if (Operation < AtomicRMWInst::FIRST_BINOP ||
4600  Operation > AtomicRMWInst::LAST_BINOP)
4601  return error("Invalid record");
4602  AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4603  if (Ordering == AtomicOrdering::NotAtomic ||
4604  Ordering == AtomicOrdering::Unordered)
4605  return error("Invalid record");
4606  SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4607  I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
4608  cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4609  InstructionList.push_back(I);
4610  break;
4611  }
4612  case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
4613  if (2 != Record.size())
4614  return error("Invalid record");
4615  AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4616  if (Ordering == AtomicOrdering::NotAtomic ||
4617  Ordering == AtomicOrdering::Unordered ||
4618  Ordering == AtomicOrdering::Monotonic)
4619  return error("Invalid record");
4620  SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
4621  I = new FenceInst(Context, Ordering, SSID);
4622  InstructionList.push_back(I);
4623  break;
4624  }
4626  // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4627  if (Record.size() < 3)
4628  return error("Invalid record");
4629 
4630  unsigned OpNum = 0;
4631  AttributeList PAL = getAttributes(Record[OpNum++]);
4632  unsigned CCInfo = Record[OpNum++];
4633 
4634  FastMathFlags FMF;
4635  if ((CCInfo >> bitc::CALL_FMF) & 1) {
4636  FMF = getDecodedFastMathFlags(Record[OpNum++]);
4637  if (!FMF.any())
4638  return error("Fast math flags indicator set for call with no FMF");
4639  }
4640 
4641  FunctionType *FTy = nullptr;
4642  if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4643  !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4644  return error("Explicit call type is not a function type");
4645 
4646  Value *Callee;
4647  if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4648  return error("Invalid record");
4649 
4650  PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4651  if (!OpTy)
4652  return error("Callee is not a pointer type");
4653  if (!FTy) {
4654  FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4655  if (!FTy)
4656  return error("Callee is not of pointer to function type");
4657  } else if (OpTy->getElementType() != FTy)
4658  return error("Explicit call type does not match pointee type of "
4659  "callee operand");
4660  if (Record.size() < FTy->getNumParams() + OpNum)
4661  return error("Insufficient operands to call");
4662 
4664  // Read the fixed params.
4665  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4666  if (FTy->getParamType(i)->isLabelTy())
4667  Args.push_back(getBasicBlock(Record[OpNum]));
4668  else
4669  Args.push_back(getValue(Record, OpNum, NextValueNo,
4670  FTy->getParamType(i)));
4671  if (!Args.back())
4672  return error("Invalid record");
4673  }
4674 
4675  // Read type/value pairs for varargs params.
4676  if (!FTy->isVarArg()) {
4677  if (OpNum != Record.size())
4678  return error("Invalid record");
4679  } else {
4680  while (OpNum != Record.size()) {
4681  Value *Op;
4682  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4683  return error("Invalid record");
4684  Args.push_back(Op);
4685  }
4686  }
4687 
4688  I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4689  OperandBundles.clear();
4690  InstructionList.push_back(I);
4691  cast<CallInst>(I)->setCallingConv(
4692  static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4694  if (CCInfo & 1 << bitc::CALL_TAIL)
4695  TCK = CallInst::TCK_Tail;
4696  if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
4697  TCK = CallInst::TCK_MustTail;
4698  if (CCInfo & (1 << bitc::CALL_NOTAIL))
4699  TCK = CallInst::TCK_NoTail;
4700  cast<CallInst>(I)->setTailCallKind(TCK);
4701  cast<CallInst>(I)->setAttributes(PAL);
4702  if (FMF.any()) {
4703  if (!isa<FPMathOperator>(I))
4704  return error("Fast-math-flags specified for call without "
4705  "floating-point scalar or vector return type");
4706  I->setFastMathFlags(FMF);
4707  }
4708  break;
4709  }
4710  case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4711  if (Record.size() < 3)
4712  return error("Invalid record");
4713  Type *OpTy = getTypeByID(Record[0]);
4714  Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4715  Type *ResTy = getTypeByID(Record[2]);
4716  if (!OpTy || !Op || !ResTy)
4717  return error("Invalid record");
4718  I = new VAArgInst(Op, ResTy);
4719  InstructionList.push_back(I);
4720  break;
4721  }
4722 
4724  // A call or an invoke can be optionally prefixed with some variable
4725  // number of operand bundle blocks. These blocks are read into
4726  // OperandBundles and consumed at the next call or invoke instruction.
4727 
4728  if (Record.size() < 1 || Record[0] >= BundleTags.size())
4729  return error("Invalid record");
4730 
4731  std::vector<Value *> Inputs;
4732 
4733  unsigned OpNum = 1;
4734  while (OpNum != Record.size()) {
4735  Value *Op;
4736  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4737  return error("Invalid record");
4738  Inputs.push_back(Op);
4739  }
4740 
4741  OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4742  continue;
4743  }
4744  }
4745 
4746  // Add instruction to end of current BB. If there is no current BB, reject
4747  // this file.
4748  if (!CurBB) {
4749  I->deleteValue();
4750  return error("Invalid instruction with no BB");
4751  }
4752  if (!OperandBundles.empty()) {
4753  I->deleteValue();
4754  return error("Operand bundles found with no consumer");
4755  }
4756  CurBB->getInstList().push_back(I);
4757 
4758  // If this was a terminator instruction, move to the next block.
4759  if (I->isTerminator()) {
4760  ++CurBBNo;
4761  CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4762  }
4763 
4764  // Non-void values get registered in the value table for future use.
4765  if (I && !I->getType()->isVoidTy())
4766  ValueList.assignValue(I, NextValueNo++);
4767  }
4768 
4769 OutOfRecordLoop:
4770 
4771  if (!OperandBundles.empty())
4772  return error("Operand bundles found with no consumer");
4773 
4774  // Check the function list for unresolved values.
4775  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4776  if (!A->getParent()) {
4777  // We found at least one unresolved value. Nuke them all to avoid leaks.
4778  for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4779  if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4780  A->replaceAllUsesWith(UndefValue::get(A->getType()));
4781  delete A;
4782  }
4783  }
4784  return error("Never resolved value found in function");
4785  }
4786  }
4787 
4788  // Unexpected unresolved metadata about to be dropped.
4789  if (MDLoader->hasFwdRefs())
4790  return error("Invalid function metadata: outgoing forward refs");
4791 
4792  // Trim the value list down to the size it was before we parsed this function.
4793  ValueList.shrinkTo(ModuleValueListSize);
4794  MDLoader->shrinkTo(ModuleMDLoaderSize);
4795  std::vector<BasicBlock*>().swap(FunctionBBs);
4796  return Error::success();
4797 }
4798 
4799 /// Find the function body in the bitcode stream
4800 Error BitcodeReader::findFunctionInStream(
4801  Function *F,
4802  DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4803  while (DeferredFunctionInfoIterator->second == 0) {
4804  // This is the fallback handling for the old format bitcode that
4805  // didn't contain the function index in the VST, or when we have
4806  // an anonymous function which would not have a VST entry.
4807  // Assert that we have one of those two cases.
4808  assert(VSTOffset == 0 || !F->hasName());
4809  // Parse the next body in the stream and set its position in the
4810  // DeferredFunctionInfo map.
4811  if (Error Err = rememberAndSkipFunctionBodies())
4812  return Err;
4813  }
4814  return Error::success();
4815 }
4816 
4817 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
4818  if (Val == SyncScope::SingleThread || Val == SyncScope::System)
4819  return SyncScope::ID(Val);
4820  if (Val >= SSIDs.size())
4821  return SyncScope::System; // Map unknown synchronization scopes to system.
4822  return SSIDs[Val];
4823 }
4824 
4825 //===----------------------------------------------------------------------===//
4826 // GVMaterializer implementation
4827 //===----------------------------------------------------------------------===//
4828 
4829 Error BitcodeReader::materialize(GlobalValue *GV) {
4830  Function *F = dyn_cast<Function>(GV);
4831  // If it's not a function or is already material, ignore the request.
4832  if (!F || !F->isMaterializable())
4833  return Error::success();
4834 
4835  DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4836  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4837  // If its position is recorded as 0, its body is somewhere in the stream
4838  // but we haven't seen it yet.
4839  if (DFII->second == 0)
4840  if (Error Err = findFunctionInStream(F, DFII))
4841  return Err;
4842 
4843  // Materialize metadata before parsing any function bodies.
4844  if (Error Err = materializeMetadata())
4845  return Err;
4846 
4847  // Move the bit stream to the saved position of the deferred function body.
4848  Stream.JumpToBit(DFII->second);
4849 
4850  if (Error Err = parseFunctionBody(F))
4851  return Err;
4852  F->setIsMaterializable(false);
4853 
4854  if (StripDebugInfo)
4855  stripDebugInfo(*F);
4856 
4857  // Upgrade any old intrinsic calls in the function.
4858  for (auto &I : UpgradedIntrinsics) {
4859  for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4860  UI != UE;) {
4861  User *U = *UI;
4862  ++UI;
4863  if (CallInst *CI = dyn_cast<CallInst>(U))
4864  UpgradeIntrinsicCall(CI, I.second);
4865  }
4866  }
4867 
4868  // Update calls to the remangled intrinsics
4869  for (auto &I : RemangledIntrinsics)
4870  for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4871  UI != UE;)
4872  // Don't expect any other users than call sites
4873  CallSite(*UI++).setCalledFunction(I.second);
4874 
4875  // Finish fn->subprogram upgrade for materialized functions.
4876  if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
4877  F->setSubprogram(SP);
4878 
4879  // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4880  if (!MDLoader->isStrippingTBAA()) {
4881  for (auto &I : instructions(F)) {
4882  MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4883  if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4884  continue;
4885  MDLoader->setStripTBAA(true);
4886  stripTBAA(F->getParent());
4887  }
4888  }
4889 
4890  // Bring in any functions that this function forward-referenced via
4891  // blockaddresses.
4892  return materializeForwardReferencedFunctions();
4893 }
4894 
4895 Error BitcodeReader::materializeModule() {
4896  if (Error Err = materializeMetadata())
4897  return Err;
4898 
4899  // Promise to materialize all forward references.
4900  WillMaterializeAllForwardRefs = true;
4901 
4902  // Iterate over the module, deserializing any functions that are still on
4903  // disk.
4904  for (Function &F : *TheModule) {
4905  if (Error Err = materialize(&F))
4906  return Err;
4907  }
4908  // At this point, if there are any function bodies, parse the rest of
4909  // the bits in the module past the last function block we have recorded
4910  // through either lazy scanning or the VST.
4911  if (LastFunctionBlockBit || NextUnreadBit)
4912  if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4913  ? LastFunctionBlockBit
4914  : NextUnreadBit))
4915  return Err;
4916 
4917  // Check that all block address forward references got resolved (as we
4918  // promised above).
4919  if (!BasicBlockFwdRefs.empty())
4920  return error("Never resolved function from blockaddress");
4921 
4922  // Upgrade any intrinsic calls that slipped through (should not happen!) and
4923  // delete the old functions to clean up. We can't do this unless the entire
4924  // module is materialized because there could always be another function body
4925  // with calls to the old function.
4926  for (auto &I : UpgradedIntrinsics) {
4927  for (auto *U : I.first->users()) {
4928  if (CallInst *CI = dyn_cast<CallInst>(U))
4929  UpgradeIntrinsicCall(CI, I.second);
4930  }
4931  if (!I.first->use_empty())
4932  I.first->replaceAllUsesWith(I.second);
4933  I.first->eraseFromParent();
4934  }
4935  UpgradedIntrinsics.clear();
4936  // Do the same for remangled intrinsics
4937  for (auto &I : RemangledIntrinsics) {
4938  I.first->replaceAllUsesWith(I.second);
4939  I.first->eraseFromParent();
4940  }
4941  RemangledIntrinsics.clear();
4942 
4943  UpgradeDebugInfo(*TheModule);
4944 
4945  UpgradeModuleFlags(*TheModule);
4946 
4947  UpgradeRetainReleaseMarker(*TheModule);
4948 
4949  return Error::success();
4950 }
4951 
4952 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4953  return IdentifiedStructTypes;
4954 }
4955 
4956 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4957  BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
4958  StringRef ModulePath, unsigned ModuleId)
4959  : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4960  ModulePath(ModulePath), ModuleId(ModuleId) {}
4961 
4962 void ModuleSummaryIndexBitcodeReader::addThisModule() {
4963  TheIndex.addModule(ModulePath, ModuleId);
4964 }
4965 
4967 ModuleSummaryIndexBitcodeReader::getThisModule() {
4968  return TheIndex.getModule(ModulePath);
4969 }
4970 
4971 std::pair<ValueInfo, GlobalValue::GUID>
4972 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
4973  auto VGI = ValueIdToValueInfoMap[ValueId];
4974  assert(VGI.first);
4975  return VGI;
4976 }
4977 
4978 void ModuleSummaryIndexBitcodeReader::setValueGUID(
4979  uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
4980  StringRef SourceFileName) {
4981  std::string GlobalId =
4982  GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4983  auto ValueGUID = GlobalValue::getGUID(GlobalId);
4984  auto OriginalNameID = ValueGUID;
4985  if (GlobalValue::isLocalLinkage(Linkage))
4986  OriginalNameID = GlobalValue::getGUID(ValueName);
4987  if (PrintSummaryGUIDs)
4988  dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4989  << ValueName << "\n";
4990 
4991  // UseStrtab is false for legacy summary formats and value names are
4992  // created on stack. In that case we save the name in a string saver in
4993  // the index so that the value name can be recorded.
4994  ValueIdToValueInfoMap[ValueID] = std::make_pair(
4995  TheIndex.getOrInsertValueInfo(
4996  ValueGUID,
4997  UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
4998  OriginalNameID);
4999 }
5000 
5001 // Specialized value symbol table parser used when reading module index
5002 // blocks where we don't actually create global values. The parsed information
5003 // is saved in the bitcode reader for use when later parsing summaries.
5004 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5005  uint64_t Offset,
5006  DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5007  // With a strtab the VST is not required to parse the summary.
5008  if (UseStrtab)
5009  return Error::success();
5010 
5011  assert(Offset > 0 && "Expected non-zero VST offset");
5012  uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5013 
5015  return error("Invalid record");
5016 
5018 
5019  // Read all the records for this value table.
5021 
5022  while (true) {
5023  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5024 
5025  switch (Entry.Kind) {
5026  case BitstreamEntry::SubBlock: // Handled for us already.
5027  case BitstreamEntry::Error:
5028  return error("Malformed block");
5030  // Done parsing VST, jump back to wherever we came from.
5031  Stream.JumpToBit(CurrentBit);
5032  return Error::success();
5034  // The interesting case.
5035  break;
5036  }
5037 
5038  // Read a record.
5039  Record.clear();
5040  switch (Stream.readRecord(Entry.ID, Record)) {
5041  default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5042  break;
5043  case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5044  if (convertToString(Record, 1, ValueName))
5045  return error("Invalid record");
5046  unsigned ValueID = Record[0];
5047  assert(!SourceFileName.empty());
5048  auto VLI = ValueIdToLinkageMap.find(ValueID);
5049  assert(VLI != ValueIdToLinkageMap.end() &&
5050  "No linkage found for VST entry?");
5051  auto Linkage = VLI->second;
5052  setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5053  ValueName.clear();
5054  break;
5055  }
5056  case bitc::VST_CODE_FNENTRY: {
5057  // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5058  if (convertToString(Record, 2, ValueName))
5059  return error("Invalid record");
5060  unsigned ValueID = Record[0];
5061  assert(!SourceFileName.empty());
5062  auto VLI = ValueIdToLinkageMap.find(ValueID);
5063  assert(VLI != ValueIdToLinkageMap.end() &&
5064  "No linkage found for VST entry?");
5065  auto Linkage = VLI->second;
5066  setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5067  ValueName.clear();
5068  break;
5069  }
5071  // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5072  unsigned ValueID = Record[0];
5073  GlobalValue::GUID RefGUID = Record[1];
5074  // The "original name", which is the second value of the pair will be
5075  // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5076  ValueIdToValueInfoMap[ValueID] =
5077  std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5078  break;
5079  }
5080  }
5081  }
5082 }
5083 
5084 // Parse just the blocks needed for building the index out of the module.
5085 // At the end of this routine the module Index is populated with a map
5086 // from global value id to GlobalValueSummary objects.
5089  return error("Invalid record");
5090 
5093  unsigned ValueId = 0;
5094 
5095  // Read the index for this module.
5096  while (true) {
5097  BitstreamEntry Entry = Stream.advance();
5098 
5099  switch (Entry.Kind) {
5100  case BitstreamEntry::Error:
5101  return error("Malformed block");
5103  return Error::success();
5104 
5106  switch (Entry.ID) {
5107  default: // Skip unknown content.
5108  if (Stream.SkipBlock())
5109  return error("Invalid record");
5110  break;
5112  // Need to parse these to get abbrev ids (e.g. for VST)
5113  if (readBlockInfo())
5114  return error("Malformed block");
5115  break;
5117  // Should have been parsed earlier via VSTOffset, unless there
5118  // is no summary section.
5119  assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5120  !SeenGlobalValSummary) &&
5121  "Expected early VST parse via VSTOffset record");
5122  if (Stream.SkipBlock())
5123  return error("Invalid record");
5124  break;
5127  // Add the module if it is a per-module index (has a source file name).
5128  if (!SourceFileName.empty())
5129  addThisModule();
5130  assert(!SeenValueSymbolTable &&
5131  "Already read VST when parsing summary block?");
5132  // We might not have a VST if there were no values in the
5133  // summary. An empty summary block generated when we are
5134  // performing ThinLTO compiles so we don't later invoke
5135  // the regular LTO process on them.
5136  if (VSTOffset > 0) {
5137  if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5138  return Err;
5139  SeenValueSymbolTable = true;
5140  }
5141  SeenGlobalValSummary = true;
5142  if (Error Err = parseEntireSummary(Entry.ID))
5143  return Err;
5144  break;
5146  if (Error Err = parseModuleStringTable())
5147  return Err;
5148  break;
5149  }
5150  continue;
5151 
5152  case BitstreamEntry::Record: {
5153  Record.clear();
5154  auto BitCode = Stream.readRecord(Entry.ID, Record);
5155  switch (BitCode) {
5156  default:
5157  break; // Default behavior, ignore unknown content.
5159  if (Error Err = parseVersionRecord(Record).takeError())
5160  return Err;
5161  break;
5162  }
5163  /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5166  if (convertToString(Record, 0, ValueName))
5167  return error("Invalid record");
5168  SourceFileName = ValueName.c_str();
5169  break;
5170  }
5171  /// MODULE_CODE_HASH: [5*i32]
5172  case bitc::MODULE_CODE_HASH: {
5173  if (Record.size() != 5)
5174  return error("Invalid hash length " + Twine(Record.size()).str());
5175  auto &Hash = getThisModule()->second.second;
5176  int Pos = 0;
5177  for (auto &Val : Record) {
5178  assert(!(Val >> 32) && "Unexpected high bits set");
5179  Hash[Pos++] = Val;
5180  }
5181  break;
5182  }
5183  /// MODULE_CODE_VSTOFFSET: [offset]
5185  if (Record.size() < 1)
5186  return error("Invalid record");
5187  // Note that we subtract 1 here because the offset is relative to one
5188  // word before the start of the identification or module block, which
5189  // was historically always the start of the regular bitcode header.
5190  VSTOffset = Record[0] - 1;
5191  break;
5192  // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
5193  // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
5194  // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
5195  // v2: [strtab offset, strtab size, v1]
5198  case bitc::MODULE_CODE_ALIAS: {
5199  StringRef Name;
5200  ArrayRef<uint64_t> GVRecord;
5201  std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5202  if (GVRecord.size() <= 3)
5203  return error("Invalid record");
5204  uint64_t RawLinkage = GVRecord[3];
5205  GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5206  if (!UseStrtab) {
5207  ValueIdToLinkageMap[ValueId++] = Linkage;
5208  break;
5209  }
5210 
5211  setValueGUID(ValueId++, Name, Linkage, SourceFileName);
5212  break;
5213  }
5214  }
5215  }
5216  continue;
5217  }
5218  }
5219 }
5220 
5221 std::vector<ValueInfo>
5222 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5223  std::vector<ValueInfo> Ret;
5224  Ret.reserve(Record.size());
5225  for (uint64_t RefValueId : Record)
5226  Ret.push_back(getValueInfoFromValueId(RefValueId).first);
5227  return Ret;
5228 }
5229 
5230 std::vector<FunctionSummary::EdgeTy>
5231 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
5232  bool IsOldProfileFormat,
5233  bool HasProfile, bool HasRelBF) {
5234  std::vector<FunctionSummary::EdgeTy> Ret;
5235  Ret.reserve(Record.size());
5236  for (unsigned I = 0, E = Record.size(); I != E; ++I) {
5238  uint64_t RelBF = 0;
5239  ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
5240  if (IsOldProfileFormat) {
5241  I += 1; // Skip old callsitecount field
5242  if (HasProfile)
5243  I += 1; // Skip old profilecount field
5244  } else if (HasProfile)
5245  Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
5246  else if (HasRelBF)
5247  RelBF = Record[++I];
5248  Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
5249  }
5250  return Ret;
5251 }
5252 
5253 static void
5256  uint64_t ArgNum = Record[Slot++];
5258  Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
5259  Slot += ArgNum;
5260 
5261  B.TheKind =
5262  static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
5263  B.Info = Record[Slot++];
5264  B.Byte = Record[Slot++];
5265  B.Bit = Record[Slot++];
5266 }
5267 
5269  StringRef Strtab, size_t &Slot,
5270  TypeIdSummary &TypeId) {
5271  uint64_t Id = Record[Slot++];
5272  WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
5273 
5274  Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
5275  Wpd.SingleImplName = {Strtab.data() + Record[Slot],
5276  static_cast<size_t>(Record[Slot + 1])};
5277  Slot += 2;
5278 
5279  uint64_t ResByArgNum = Record[Slot++];
5280  for (uint64_t I = 0; I != ResByArgNum; ++I)
5281  parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
5282 }
5283 
5285  StringRef Strtab,
5286  ModuleSummaryIndex &TheIndex) {
5287  size_t Slot = 0;
5288  TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
5289  {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
5290  Slot += 2;
5291 
5292  TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
5293  TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
5294  TypeId.TTRes.AlignLog2 = Record[Slot++];
5295  TypeId.TTRes.SizeM1 = Record[Slot++];
5296  TypeId.TTRes.BitMask = Record[Slot++];
5297  TypeId.TTRes.InlineBits = Record[Slot++];
5298 
5299  while (Slot < Record.size())
5300  parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
5301 }
5302 
5303 static void setImmutableRefs(std::vector<ValueInfo> &Refs, unsigned Count) {
5304  // Read-only refs are in the end of the refs list.
5305  for (unsigned RefNo = Refs.size() - Count; RefNo < Refs.size(); ++RefNo)
5306  Refs[RefNo].setReadOnly();
5307 }
5308 
5309 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
5310 // objects in the index.
5311 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
5312  if (Stream.EnterSubBlock(ID))
5313  return error("Invalid record");
5315 
5316  // Parse version
5317  {
5318  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5319  if (Entry.Kind != BitstreamEntry::Record)
5320  return error("Invalid Summary Block: record for version expected");
5321  if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
5322  return error("Invalid Summary Block: version expected");
5323  }
5324  const uint64_t Version = Record[0];
5325  const bool IsOldProfileFormat = Version == 1;
5326  if (Version < 1 || Version > 6)
5327  return error("Invalid summary version " + Twine(Version) +
5328  ". Version should be in the range [1-6].");
5329  Record.clear();
5330 
5331  // Keep around the last seen summary to be used when we see an optional
5332  // "OriginalName" attachement.
5333  GlobalValueSummary *LastSeenSummary = nullptr;
5334  GlobalValue::GUID LastSeenGUID = 0;
5335 
5336  // We can expect to see any number of type ID information records before
5337  // each function summary records; these variables store the information
5338  // collected so far so that it can be used to create the summary object.
5339  std::vector<GlobalValue::GUID> PendingTypeTests;
5340  std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
5341  PendingTypeCheckedLoadVCalls;
5342  std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
5343  PendingTypeCheckedLoadConstVCalls;
5344 
5345  while (true) {
5346  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5347 
5348  switch (Entry.Kind) {
5349  case BitstreamEntry::SubBlock: // Handled for us already.
5350  case BitstreamEntry::Error:
5351  return error("Malformed block");
5353  return Error::success();
5355  // The interesting case.
5356  break;
5357  }
5358 
5359  // Read a record. The record format depends on whether this
5360  // is a per-module index or a combined index file. In the per-module
5361  // case the records contain the associated value's ID for correlation
5362  // with VST entries. In the combined index the correlation is done
5363  // via the bitcode offset of the summary records (which were saved
5364  // in the combined index VST entries). The records also contain
5365  // information used for ThinLTO renaming and importing.
5366  Record.clear();
5367  auto BitCode = Stream.readRecord(Entry.ID, Record);
5368  switch (BitCode) {
5369  default: // Default behavior: ignore.
5370  break;
5371  case bitc::FS_FLAGS: { // [flags]
5372  uint64_t Flags = Record[0];
5373  // Scan flags.
5374  assert(Flags <= 0x1f && "Unexpected bits in flag");
5375 
5376  // 1 bit: WithGlobalValueDeadStripping flag.
5377  // Set on combined index only.
5378  if (Flags & 0x1)
5380  // 1 bit: SkipModuleByDistributedBackend flag.
5381  // Set on combined index only.
5382  if (Flags & 0x2)
5384  // 1 bit: HasSyntheticEntryCounts flag.
5385  // Set on combined index only.
5386  if (Flags & 0x4)
5387  TheIndex.setHasSyntheticEntryCounts();
5388  // 1 bit: DisableSplitLTOUnit flag.
5389  // Set on per module indexes. It is up to the client to validate
5390  // the consistency of this flag across modules being linked.
5391  if (Flags & 0x8)
5392  TheIndex.setEnableSplitLTOUnit();
5393  // 1 bit: PartiallySplitLTOUnits flag.
5394  // Set on combined index only.
5395  if (Flags & 0x10)
5396  TheIndex.setPartiallySplitLTOUnits();
5397  break;
5398  }
5399  case bitc::FS_VALUE_GUID: { // [valueid, refguid]