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