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