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