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