LLVM API Documentation

BitcodeReader.cpp
Go to the documentation of this file.
00001 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "llvm/Bitcode/ReaderWriter.h"
00011 #include "BitcodeReader.h"
00012 #include "llvm/ADT/SmallString.h"
00013 #include "llvm/ADT/SmallVector.h"
00014 #include "llvm/Bitcode/LLVMBitCodes.h"
00015 #include "llvm/IR/AutoUpgrade.h"
00016 #include "llvm/IR/Constants.h"
00017 #include "llvm/IR/DerivedTypes.h"
00018 #include "llvm/IR/InlineAsm.h"
00019 #include "llvm/IR/IntrinsicInst.h"
00020 #include "llvm/IR/LLVMContext.h"
00021 #include "llvm/IR/Module.h"
00022 #include "llvm/IR/OperandTraits.h"
00023 #include "llvm/IR/Operator.h"
00024 #include "llvm/Support/DataStream.h"
00025 #include "llvm/Support/MathExtras.h"
00026 #include "llvm/Support/MemoryBuffer.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 using namespace llvm;
00029 
00030 enum {
00031   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
00032 };
00033 
00034 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
00035   if (WillMaterializeAllForwardRefs)
00036     return std::error_code();
00037 
00038   // Prevent recursion.
00039   WillMaterializeAllForwardRefs = true;
00040 
00041   while (!BasicBlockFwdRefQueue.empty()) {
00042     Function *F = BasicBlockFwdRefQueue.front();
00043     BasicBlockFwdRefQueue.pop_front();
00044     assert(F && "Expected valid function");
00045     if (!BasicBlockFwdRefs.count(F))
00046       // Already materialized.
00047       continue;
00048 
00049     // Check for a function that isn't materializable to prevent an infinite
00050     // loop.  When parsing a blockaddress stored in a global variable, there
00051     // isn't a trivial way to check if a function will have a body without a
00052     // linear search through FunctionsWithBodies, so just check it here.
00053     if (!F->isMaterializable())
00054       return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
00055 
00056     // Try to materialize F.
00057     if (std::error_code EC = Materialize(F))
00058       return EC;
00059   }
00060   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
00061 
00062   // Reset state.
00063   WillMaterializeAllForwardRefs = false;
00064   return std::error_code();
00065 }
00066 
00067 void BitcodeReader::FreeState() {
00068   Buffer = nullptr;
00069   std::vector<Type*>().swap(TypeList);
00070   ValueList.clear();
00071   MDValueList.clear();
00072   std::vector<Comdat *>().swap(ComdatList);
00073 
00074   std::vector<AttributeSet>().swap(MAttributes);
00075   std::vector<BasicBlock*>().swap(FunctionBBs);
00076   std::vector<Function*>().swap(FunctionsWithBodies);
00077   DeferredFunctionInfo.clear();
00078   MDKindMap.clear();
00079 
00080   assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
00081   BasicBlockFwdRefQueue.clear();
00082 }
00083 
00084 //===----------------------------------------------------------------------===//
00085 //  Helper functions to implement forward reference resolution, etc.
00086 //===----------------------------------------------------------------------===//
00087 
00088 /// ConvertToString - Convert a string from a record into an std::string, return
00089 /// true on failure.
00090 template<typename StrTy>
00091 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
00092                             StrTy &Result) {
00093   if (Idx > Record.size())
00094     return true;
00095 
00096   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
00097     Result += (char)Record[i];
00098   return false;
00099 }
00100 
00101 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
00102   switch (Val) {
00103   default: // Map unknown/new linkages to external
00104   case 0:  return GlobalValue::ExternalLinkage;
00105   case 1:  return GlobalValue::WeakAnyLinkage;
00106   case 2:  return GlobalValue::AppendingLinkage;
00107   case 3:  return GlobalValue::InternalLinkage;
00108   case 4:  return GlobalValue::LinkOnceAnyLinkage;
00109   case 5:  return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
00110   case 6:  return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
00111   case 7:  return GlobalValue::ExternalWeakLinkage;
00112   case 8:  return GlobalValue::CommonLinkage;
00113   case 9:  return GlobalValue::PrivateLinkage;
00114   case 10: return GlobalValue::WeakODRLinkage;
00115   case 11: return GlobalValue::LinkOnceODRLinkage;
00116   case 12: return GlobalValue::AvailableExternallyLinkage;
00117   case 13:
00118     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
00119   case 14:
00120     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
00121   }
00122 }
00123 
00124 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
00125   switch (Val) {
00126   default: // Map unknown visibilities to default.
00127   case 0: return GlobalValue::DefaultVisibility;
00128   case 1: return GlobalValue::HiddenVisibility;
00129   case 2: return GlobalValue::ProtectedVisibility;
00130   }
00131 }
00132 
00133 static GlobalValue::DLLStorageClassTypes
00134 GetDecodedDLLStorageClass(unsigned Val) {
00135   switch (Val) {
00136   default: // Map unknown values to default.
00137   case 0: return GlobalValue::DefaultStorageClass;
00138   case 1: return GlobalValue::DLLImportStorageClass;
00139   case 2: return GlobalValue::DLLExportStorageClass;
00140   }
00141 }
00142 
00143 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
00144   switch (Val) {
00145     case 0: return GlobalVariable::NotThreadLocal;
00146     default: // Map unknown non-zero value to general dynamic.
00147     case 1: return GlobalVariable::GeneralDynamicTLSModel;
00148     case 2: return GlobalVariable::LocalDynamicTLSModel;
00149     case 3: return GlobalVariable::InitialExecTLSModel;
00150     case 4: return GlobalVariable::LocalExecTLSModel;
00151   }
00152 }
00153 
00154 static int GetDecodedCastOpcode(unsigned Val) {
00155   switch (Val) {
00156   default: return -1;
00157   case bitc::CAST_TRUNC   : return Instruction::Trunc;
00158   case bitc::CAST_ZEXT    : return Instruction::ZExt;
00159   case bitc::CAST_SEXT    : return Instruction::SExt;
00160   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
00161   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
00162   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
00163   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
00164   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
00165   case bitc::CAST_FPEXT   : return Instruction::FPExt;
00166   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
00167   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
00168   case bitc::CAST_BITCAST : return Instruction::BitCast;
00169   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
00170   }
00171 }
00172 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
00173   switch (Val) {
00174   default: return -1;
00175   case bitc::BINOP_ADD:
00176     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
00177   case bitc::BINOP_SUB:
00178     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
00179   case bitc::BINOP_MUL:
00180     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
00181   case bitc::BINOP_UDIV: return Instruction::UDiv;
00182   case bitc::BINOP_SDIV:
00183     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
00184   case bitc::BINOP_UREM: return Instruction::URem;
00185   case bitc::BINOP_SREM:
00186     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
00187   case bitc::BINOP_SHL:  return Instruction::Shl;
00188   case bitc::BINOP_LSHR: return Instruction::LShr;
00189   case bitc::BINOP_ASHR: return Instruction::AShr;
00190   case bitc::BINOP_AND:  return Instruction::And;
00191   case bitc::BINOP_OR:   return Instruction::Or;
00192   case bitc::BINOP_XOR:  return Instruction::Xor;
00193   }
00194 }
00195 
00196 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
00197   switch (Val) {
00198   default: return AtomicRMWInst::BAD_BINOP;
00199   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
00200   case bitc::RMW_ADD: return AtomicRMWInst::Add;
00201   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
00202   case bitc::RMW_AND: return AtomicRMWInst::And;
00203   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
00204   case bitc::RMW_OR: return AtomicRMWInst::Or;
00205   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
00206   case bitc::RMW_MAX: return AtomicRMWInst::Max;
00207   case bitc::RMW_MIN: return AtomicRMWInst::Min;
00208   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
00209   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
00210   }
00211 }
00212 
00213 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
00214   switch (Val) {
00215   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
00216   case bitc::ORDERING_UNORDERED: return Unordered;
00217   case bitc::ORDERING_MONOTONIC: return Monotonic;
00218   case bitc::ORDERING_ACQUIRE: return Acquire;
00219   case bitc::ORDERING_RELEASE: return Release;
00220   case bitc::ORDERING_ACQREL: return AcquireRelease;
00221   default: // Map unknown orderings to sequentially-consistent.
00222   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
00223   }
00224 }
00225 
00226 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
00227   switch (Val) {
00228   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
00229   default: // Map unknown scopes to cross-thread.
00230   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
00231   }
00232 }
00233 
00234 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
00235   switch (Val) {
00236   default: // Map unknown selection kinds to any.
00237   case bitc::COMDAT_SELECTION_KIND_ANY:
00238     return Comdat::Any;
00239   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
00240     return Comdat::ExactMatch;
00241   case bitc::COMDAT_SELECTION_KIND_LARGEST:
00242     return Comdat::Largest;
00243   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
00244     return Comdat::NoDuplicates;
00245   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
00246     return Comdat::SameSize;
00247   }
00248 }
00249 
00250 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
00251   switch (Val) {
00252   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
00253   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
00254   }
00255 }
00256 
00257 namespace llvm {
00258 namespace {
00259   /// @brief A class for maintaining the slot number definition
00260   /// as a placeholder for the actual definition for forward constants defs.
00261   class ConstantPlaceHolder : public ConstantExpr {
00262     void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
00263   public:
00264     // allocate space for exactly one operand
00265     void *operator new(size_t s) {
00266       return User::operator new(s, 1);
00267     }
00268     explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
00269       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
00270       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
00271     }
00272 
00273     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
00274     static bool classof(const Value *V) {
00275       return isa<ConstantExpr>(V) &&
00276              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
00277     }
00278 
00279 
00280     /// Provide fast operand accessors
00281     //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00282   };
00283 }
00284 
00285 // FIXME: can we inherit this from ConstantExpr?
00286 template <>
00287 struct OperandTraits<ConstantPlaceHolder> :
00288   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
00289 };
00290 }
00291 
00292 
00293 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
00294   if (Idx == size()) {
00295     push_back(V);
00296     return;
00297   }
00298 
00299   if (Idx >= size())
00300     resize(Idx+1);
00301 
00302   WeakVH &OldV = ValuePtrs[Idx];
00303   if (!OldV) {
00304     OldV = V;
00305     return;
00306   }
00307 
00308   // Handle constants and non-constants (e.g. instrs) differently for
00309   // efficiency.
00310   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
00311     ResolveConstants.push_back(std::make_pair(PHC, Idx));
00312     OldV = V;
00313   } else {
00314     // If there was a forward reference to this value, replace it.
00315     Value *PrevVal = OldV;
00316     OldV->replaceAllUsesWith(V);
00317     delete PrevVal;
00318   }
00319 }
00320 
00321 
00322 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
00323                                                     Type *Ty) {
00324   if (Idx >= size())
00325     resize(Idx + 1);
00326 
00327   if (Value *V = ValuePtrs[Idx]) {
00328     assert(Ty == V->getType() && "Type mismatch in constant table!");
00329     return cast<Constant>(V);
00330   }
00331 
00332   // Create and return a placeholder, which will later be RAUW'd.
00333   Constant *C = new ConstantPlaceHolder(Ty, Context);
00334   ValuePtrs[Idx] = C;
00335   return C;
00336 }
00337 
00338 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
00339   if (Idx >= size())
00340     resize(Idx + 1);
00341 
00342   if (Value *V = ValuePtrs[Idx]) {
00343     assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
00344     return V;
00345   }
00346 
00347   // No type specified, must be invalid reference.
00348   if (!Ty) return nullptr;
00349 
00350   // Create and return a placeholder, which will later be RAUW'd.
00351   Value *V = new Argument(Ty);
00352   ValuePtrs[Idx] = V;
00353   return V;
00354 }
00355 
00356 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
00357 /// resolves any forward references.  The idea behind this is that we sometimes
00358 /// get constants (such as large arrays) which reference *many* forward ref
00359 /// constants.  Replacing each of these causes a lot of thrashing when
00360 /// building/reuniquing the constant.  Instead of doing this, we look at all the
00361 /// uses and rewrite all the place holders at once for any constant that uses
00362 /// a placeholder.
00363 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
00364   // Sort the values by-pointer so that they are efficient to look up with a
00365   // binary search.
00366   std::sort(ResolveConstants.begin(), ResolveConstants.end());
00367 
00368   SmallVector<Constant*, 64> NewOps;
00369 
00370   while (!ResolveConstants.empty()) {
00371     Value *RealVal = operator[](ResolveConstants.back().second);
00372     Constant *Placeholder = ResolveConstants.back().first;
00373     ResolveConstants.pop_back();
00374 
00375     // Loop over all users of the placeholder, updating them to reference the
00376     // new value.  If they reference more than one placeholder, update them all
00377     // at once.
00378     while (!Placeholder->use_empty()) {
00379       auto UI = Placeholder->user_begin();
00380       User *U = *UI;
00381 
00382       // If the using object isn't uniqued, just update the operands.  This
00383       // handles instructions and initializers for global variables.
00384       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
00385         UI.getUse().set(RealVal);
00386         continue;
00387       }
00388 
00389       // Otherwise, we have a constant that uses the placeholder.  Replace that
00390       // constant with a new constant that has *all* placeholder uses updated.
00391       Constant *UserC = cast<Constant>(U);
00392       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
00393            I != E; ++I) {
00394         Value *NewOp;
00395         if (!isa<ConstantPlaceHolder>(*I)) {
00396           // Not a placeholder reference.
00397           NewOp = *I;
00398         } else if (*I == Placeholder) {
00399           // Common case is that it just references this one placeholder.
00400           NewOp = RealVal;
00401         } else {
00402           // Otherwise, look up the placeholder in ResolveConstants.
00403           ResolveConstantsTy::iterator It =
00404             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
00405                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
00406                                                             0));
00407           assert(It != ResolveConstants.end() && It->first == *I);
00408           NewOp = operator[](It->second);
00409         }
00410 
00411         NewOps.push_back(cast<Constant>(NewOp));
00412       }
00413 
00414       // Make the new constant.
00415       Constant *NewC;
00416       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
00417         NewC = ConstantArray::get(UserCA->getType(), NewOps);
00418       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
00419         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
00420       } else if (isa<ConstantVector>(UserC)) {
00421         NewC = ConstantVector::get(NewOps);
00422       } else {
00423         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
00424         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
00425       }
00426 
00427       UserC->replaceAllUsesWith(NewC);
00428       UserC->destroyConstant();
00429       NewOps.clear();
00430     }
00431 
00432     // Update all ValueHandles, they should be the only users at this point.
00433     Placeholder->replaceAllUsesWith(RealVal);
00434     delete Placeholder;
00435   }
00436 }
00437 
00438 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
00439   if (Idx == size()) {
00440     push_back(V);
00441     return;
00442   }
00443 
00444   if (Idx >= size())
00445     resize(Idx+1);
00446 
00447   WeakVH &OldV = MDValuePtrs[Idx];
00448   if (!OldV) {
00449     OldV = V;
00450     return;
00451   }
00452 
00453   // If there was a forward reference to this value, replace it.
00454   MDNode *PrevVal = cast<MDNode>(OldV);
00455   OldV->replaceAllUsesWith(V);
00456   MDNode::deleteTemporary(PrevVal);
00457   // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
00458   // value for Idx.
00459   MDValuePtrs[Idx] = V;
00460 }
00461 
00462 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
00463   if (Idx >= size())
00464     resize(Idx + 1);
00465 
00466   if (Value *V = MDValuePtrs[Idx]) {
00467     assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
00468     return V;
00469   }
00470 
00471   // Create and return a placeholder, which will later be RAUW'd.
00472   Value *V = MDNode::getTemporary(Context, None);
00473   MDValuePtrs[Idx] = V;
00474   return V;
00475 }
00476 
00477 Type *BitcodeReader::getTypeByID(unsigned ID) {
00478   // The type table size is always specified correctly.
00479   if (ID >= TypeList.size())
00480     return nullptr;
00481 
00482   if (Type *Ty = TypeList[ID])
00483     return Ty;
00484 
00485   // If we have a forward reference, the only possible case is when it is to a
00486   // named struct.  Just create a placeholder for now.
00487   return TypeList[ID] = StructType::create(Context);
00488 }
00489 
00490 
00491 //===----------------------------------------------------------------------===//
00492 //  Functions for parsing blocks from the bitcode file
00493 //===----------------------------------------------------------------------===//
00494 
00495 
00496 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
00497 /// been decoded from the given integer. This function must stay in sync with
00498 /// 'encodeLLVMAttributesForBitcode'.
00499 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
00500                                            uint64_t EncodedAttrs) {
00501   // FIXME: Remove in 4.0.
00502 
00503   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
00504   // the bits above 31 down by 11 bits.
00505   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
00506   assert((!Alignment || isPowerOf2_32(Alignment)) &&
00507          "Alignment must be a power of two.");
00508 
00509   if (Alignment)
00510     B.addAlignmentAttr(Alignment);
00511   B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
00512                 (EncodedAttrs & 0xffff));
00513 }
00514 
00515 std::error_code BitcodeReader::ParseAttributeBlock() {
00516   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
00517     return Error(BitcodeError::InvalidRecord);
00518 
00519   if (!MAttributes.empty())
00520     return Error(BitcodeError::InvalidMultipleBlocks);
00521 
00522   SmallVector<uint64_t, 64> Record;
00523 
00524   SmallVector<AttributeSet, 8> Attrs;
00525 
00526   // Read all the records.
00527   while (1) {
00528     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
00529 
00530     switch (Entry.Kind) {
00531     case BitstreamEntry::SubBlock: // Handled for us already.
00532     case BitstreamEntry::Error:
00533       return Error(BitcodeError::MalformedBlock);
00534     case BitstreamEntry::EndBlock:
00535       return std::error_code();
00536     case BitstreamEntry::Record:
00537       // The interesting case.
00538       break;
00539     }
00540 
00541     // Read a record.
00542     Record.clear();
00543     switch (Stream.readRecord(Entry.ID, Record)) {
00544     default:  // Default behavior: ignore.
00545       break;
00546     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
00547       // FIXME: Remove in 4.0.
00548       if (Record.size() & 1)
00549         return Error(BitcodeError::InvalidRecord);
00550 
00551       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
00552         AttrBuilder B;
00553         decodeLLVMAttributesForBitcode(B, Record[i+1]);
00554         Attrs.push_back(AttributeSet::get(Context, Record[i], B));
00555       }
00556 
00557       MAttributes.push_back(AttributeSet::get(Context, Attrs));
00558       Attrs.clear();
00559       break;
00560     }
00561     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
00562       for (unsigned i = 0, e = Record.size(); i != e; ++i)
00563         Attrs.push_back(MAttributeGroups[Record[i]]);
00564 
00565       MAttributes.push_back(AttributeSet::get(Context, Attrs));
00566       Attrs.clear();
00567       break;
00568     }
00569     }
00570   }
00571 }
00572 
00573 // Returns Attribute::None on unrecognized codes.
00574 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
00575   switch (Code) {
00576   default:
00577     return Attribute::None;
00578   case bitc::ATTR_KIND_ALIGNMENT:
00579     return Attribute::Alignment;
00580   case bitc::ATTR_KIND_ALWAYS_INLINE:
00581     return Attribute::AlwaysInline;
00582   case bitc::ATTR_KIND_BUILTIN:
00583     return Attribute::Builtin;
00584   case bitc::ATTR_KIND_BY_VAL:
00585     return Attribute::ByVal;
00586   case bitc::ATTR_KIND_IN_ALLOCA:
00587     return Attribute::InAlloca;
00588   case bitc::ATTR_KIND_COLD:
00589     return Attribute::Cold;
00590   case bitc::ATTR_KIND_INLINE_HINT:
00591     return Attribute::InlineHint;
00592   case bitc::ATTR_KIND_IN_REG:
00593     return Attribute::InReg;
00594   case bitc::ATTR_KIND_JUMP_TABLE:
00595     return Attribute::JumpTable;
00596   case bitc::ATTR_KIND_MIN_SIZE:
00597     return Attribute::MinSize;
00598   case bitc::ATTR_KIND_NAKED:
00599     return Attribute::Naked;
00600   case bitc::ATTR_KIND_NEST:
00601     return Attribute::Nest;
00602   case bitc::ATTR_KIND_NO_ALIAS:
00603     return Attribute::NoAlias;
00604   case bitc::ATTR_KIND_NO_BUILTIN:
00605     return Attribute::NoBuiltin;
00606   case bitc::ATTR_KIND_NO_CAPTURE:
00607     return Attribute::NoCapture;
00608   case bitc::ATTR_KIND_NO_DUPLICATE:
00609     return Attribute::NoDuplicate;
00610   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
00611     return Attribute::NoImplicitFloat;
00612   case bitc::ATTR_KIND_NO_INLINE:
00613     return Attribute::NoInline;
00614   case bitc::ATTR_KIND_NON_LAZY_BIND:
00615     return Attribute::NonLazyBind;
00616   case bitc::ATTR_KIND_NON_NULL:
00617     return Attribute::NonNull;
00618   case bitc::ATTR_KIND_DEREFERENCEABLE:
00619     return Attribute::Dereferenceable;
00620   case bitc::ATTR_KIND_NO_RED_ZONE:
00621     return Attribute::NoRedZone;
00622   case bitc::ATTR_KIND_NO_RETURN:
00623     return Attribute::NoReturn;
00624   case bitc::ATTR_KIND_NO_UNWIND:
00625     return Attribute::NoUnwind;
00626   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
00627     return Attribute::OptimizeForSize;
00628   case bitc::ATTR_KIND_OPTIMIZE_NONE:
00629     return Attribute::OptimizeNone;
00630   case bitc::ATTR_KIND_READ_NONE:
00631     return Attribute::ReadNone;
00632   case bitc::ATTR_KIND_READ_ONLY:
00633     return Attribute::ReadOnly;
00634   case bitc::ATTR_KIND_RETURNED:
00635     return Attribute::Returned;
00636   case bitc::ATTR_KIND_RETURNS_TWICE:
00637     return Attribute::ReturnsTwice;
00638   case bitc::ATTR_KIND_S_EXT:
00639     return Attribute::SExt;
00640   case bitc::ATTR_KIND_STACK_ALIGNMENT:
00641     return Attribute::StackAlignment;
00642   case bitc::ATTR_KIND_STACK_PROTECT:
00643     return Attribute::StackProtect;
00644   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
00645     return Attribute::StackProtectReq;
00646   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
00647     return Attribute::StackProtectStrong;
00648   case bitc::ATTR_KIND_STRUCT_RET:
00649     return Attribute::StructRet;
00650   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
00651     return Attribute::SanitizeAddress;
00652   case bitc::ATTR_KIND_SANITIZE_THREAD:
00653     return Attribute::SanitizeThread;
00654   case bitc::ATTR_KIND_SANITIZE_MEMORY:
00655     return Attribute::SanitizeMemory;
00656   case bitc::ATTR_KIND_UW_TABLE:
00657     return Attribute::UWTable;
00658   case bitc::ATTR_KIND_Z_EXT:
00659     return Attribute::ZExt;
00660   }
00661 }
00662 
00663 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code,
00664                                              Attribute::AttrKind *Kind) {
00665   *Kind = GetAttrFromCode(Code);
00666   if (*Kind == Attribute::None)
00667     return Error(BitcodeError::InvalidValue);
00668   return std::error_code();
00669 }
00670 
00671 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
00672   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
00673     return Error(BitcodeError::InvalidRecord);
00674 
00675   if (!MAttributeGroups.empty())
00676     return Error(BitcodeError::InvalidMultipleBlocks);
00677 
00678   SmallVector<uint64_t, 64> Record;
00679 
00680   // Read all the records.
00681   while (1) {
00682     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
00683 
00684     switch (Entry.Kind) {
00685     case BitstreamEntry::SubBlock: // Handled for us already.
00686     case BitstreamEntry::Error:
00687       return Error(BitcodeError::MalformedBlock);
00688     case BitstreamEntry::EndBlock:
00689       return std::error_code();
00690     case BitstreamEntry::Record:
00691       // The interesting case.
00692       break;
00693     }
00694 
00695     // Read a record.
00696     Record.clear();
00697     switch (Stream.readRecord(Entry.ID, Record)) {
00698     default:  // Default behavior: ignore.
00699       break;
00700     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
00701       if (Record.size() < 3)
00702         return Error(BitcodeError::InvalidRecord);
00703 
00704       uint64_t GrpID = Record[0];
00705       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
00706 
00707       AttrBuilder B;
00708       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
00709         if (Record[i] == 0) {        // Enum attribute
00710           Attribute::AttrKind Kind;
00711           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
00712             return EC;
00713 
00714           B.addAttribute(Kind);
00715         } else if (Record[i] == 1) { // Integer attribute
00716           Attribute::AttrKind Kind;
00717           if (std::error_code EC = ParseAttrKind(Record[++i], &Kind))
00718             return EC;
00719           if (Kind == Attribute::Alignment)
00720             B.addAlignmentAttr(Record[++i]);
00721           else if (Kind == Attribute::StackAlignment)
00722             B.addStackAlignmentAttr(Record[++i]);
00723           else if (Kind == Attribute::Dereferenceable)
00724             B.addDereferenceableAttr(Record[++i]);
00725         } else {                     // String attribute
00726           assert((Record[i] == 3 || Record[i] == 4) &&
00727                  "Invalid attribute group entry");
00728           bool HasValue = (Record[i++] == 4);
00729           SmallString<64> KindStr;
00730           SmallString<64> ValStr;
00731 
00732           while (Record[i] != 0 && i != e)
00733             KindStr += Record[i++];
00734           assert(Record[i] == 0 && "Kind string not null terminated");
00735 
00736           if (HasValue) {
00737             // Has a value associated with it.
00738             ++i; // Skip the '0' that terminates the "kind" string.
00739             while (Record[i] != 0 && i != e)
00740               ValStr += Record[i++];
00741             assert(Record[i] == 0 && "Value string not null terminated");
00742           }
00743 
00744           B.addAttribute(KindStr.str(), ValStr.str());
00745         }
00746       }
00747 
00748       MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
00749       break;
00750     }
00751     }
00752   }
00753 }
00754 
00755 std::error_code BitcodeReader::ParseTypeTable() {
00756   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
00757     return Error(BitcodeError::InvalidRecord);
00758 
00759   return ParseTypeTableBody();
00760 }
00761 
00762 std::error_code BitcodeReader::ParseTypeTableBody() {
00763   if (!TypeList.empty())
00764     return Error(BitcodeError::InvalidMultipleBlocks);
00765 
00766   SmallVector<uint64_t, 64> Record;
00767   unsigned NumRecords = 0;
00768 
00769   SmallString<64> TypeName;
00770 
00771   // Read all the records for this type table.
00772   while (1) {
00773     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
00774 
00775     switch (Entry.Kind) {
00776     case BitstreamEntry::SubBlock: // Handled for us already.
00777     case BitstreamEntry::Error:
00778       return Error(BitcodeError::MalformedBlock);
00779     case BitstreamEntry::EndBlock:
00780       if (NumRecords != TypeList.size())
00781         return Error(BitcodeError::MalformedBlock);
00782       return std::error_code();
00783     case BitstreamEntry::Record:
00784       // The interesting case.
00785       break;
00786     }
00787 
00788     // Read a record.
00789     Record.clear();
00790     Type *ResultTy = nullptr;
00791     switch (Stream.readRecord(Entry.ID, Record)) {
00792     default:
00793       return Error(BitcodeError::InvalidValue);
00794     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
00795       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
00796       // type list.  This allows us to reserve space.
00797       if (Record.size() < 1)
00798         return Error(BitcodeError::InvalidRecord);
00799       TypeList.resize(Record[0]);
00800       continue;
00801     case bitc::TYPE_CODE_VOID:      // VOID
00802       ResultTy = Type::getVoidTy(Context);
00803       break;
00804     case bitc::TYPE_CODE_HALF:     // HALF
00805       ResultTy = Type::getHalfTy(Context);
00806       break;
00807     case bitc::TYPE_CODE_FLOAT:     // FLOAT
00808       ResultTy = Type::getFloatTy(Context);
00809       break;
00810     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
00811       ResultTy = Type::getDoubleTy(Context);
00812       break;
00813     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
00814       ResultTy = Type::getX86_FP80Ty(Context);
00815       break;
00816     case bitc::TYPE_CODE_FP128:     // FP128
00817       ResultTy = Type::getFP128Ty(Context);
00818       break;
00819     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
00820       ResultTy = Type::getPPC_FP128Ty(Context);
00821       break;
00822     case bitc::TYPE_CODE_LABEL:     // LABEL
00823       ResultTy = Type::getLabelTy(Context);
00824       break;
00825     case bitc::TYPE_CODE_METADATA:  // METADATA
00826       ResultTy = Type::getMetadataTy(Context);
00827       break;
00828     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
00829       ResultTy = Type::getX86_MMXTy(Context);
00830       break;
00831     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
00832       if (Record.size() < 1)
00833         return Error(BitcodeError::InvalidRecord);
00834 
00835       ResultTy = IntegerType::get(Context, Record[0]);
00836       break;
00837     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
00838                                     //          [pointee type, address space]
00839       if (Record.size() < 1)
00840         return Error(BitcodeError::InvalidRecord);
00841       unsigned AddressSpace = 0;
00842       if (Record.size() == 2)
00843         AddressSpace = Record[1];
00844       ResultTy = getTypeByID(Record[0]);
00845       if (!ResultTy)
00846         return Error(BitcodeError::InvalidType);
00847       ResultTy = PointerType::get(ResultTy, AddressSpace);
00848       break;
00849     }
00850     case bitc::TYPE_CODE_FUNCTION_OLD: {
00851       // FIXME: attrid is dead, remove it in LLVM 4.0
00852       // FUNCTION: [vararg, attrid, retty, paramty x N]
00853       if (Record.size() < 3)
00854         return Error(BitcodeError::InvalidRecord);
00855       SmallVector<Type*, 8> ArgTys;
00856       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
00857         if (Type *T = getTypeByID(Record[i]))
00858           ArgTys.push_back(T);
00859         else
00860           break;
00861       }
00862 
00863       ResultTy = getTypeByID(Record[2]);
00864       if (!ResultTy || ArgTys.size() < Record.size()-3)
00865         return Error(BitcodeError::InvalidType);
00866 
00867       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
00868       break;
00869     }
00870     case bitc::TYPE_CODE_FUNCTION: {
00871       // FUNCTION: [vararg, retty, paramty x N]
00872       if (Record.size() < 2)
00873         return Error(BitcodeError::InvalidRecord);
00874       SmallVector<Type*, 8> ArgTys;
00875       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
00876         if (Type *T = getTypeByID(Record[i]))
00877           ArgTys.push_back(T);
00878         else
00879           break;
00880       }
00881 
00882       ResultTy = getTypeByID(Record[1]);
00883       if (!ResultTy || ArgTys.size() < Record.size()-2)
00884         return Error(BitcodeError::InvalidType);
00885 
00886       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
00887       break;
00888     }
00889     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
00890       if (Record.size() < 1)
00891         return Error(BitcodeError::InvalidRecord);
00892       SmallVector<Type*, 8> EltTys;
00893       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
00894         if (Type *T = getTypeByID(Record[i]))
00895           EltTys.push_back(T);
00896         else
00897           break;
00898       }
00899       if (EltTys.size() != Record.size()-1)
00900         return Error(BitcodeError::InvalidType);
00901       ResultTy = StructType::get(Context, EltTys, Record[0]);
00902       break;
00903     }
00904     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
00905       if (ConvertToString(Record, 0, TypeName))
00906         return Error(BitcodeError::InvalidRecord);
00907       continue;
00908 
00909     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
00910       if (Record.size() < 1)
00911         return Error(BitcodeError::InvalidRecord);
00912 
00913       if (NumRecords >= TypeList.size())
00914         return Error(BitcodeError::InvalidTYPETable);
00915 
00916       // Check to see if this was forward referenced, if so fill in the temp.
00917       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
00918       if (Res) {
00919         Res->setName(TypeName);
00920         TypeList[NumRecords] = nullptr;
00921       } else  // Otherwise, create a new struct.
00922         Res = StructType::create(Context, TypeName);
00923       TypeName.clear();
00924 
00925       SmallVector<Type*, 8> EltTys;
00926       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
00927         if (Type *T = getTypeByID(Record[i]))
00928           EltTys.push_back(T);
00929         else
00930           break;
00931       }
00932       if (EltTys.size() != Record.size()-1)
00933         return Error(BitcodeError::InvalidRecord);
00934       Res->setBody(EltTys, Record[0]);
00935       ResultTy = Res;
00936       break;
00937     }
00938     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
00939       if (Record.size() != 1)
00940         return Error(BitcodeError::InvalidRecord);
00941 
00942       if (NumRecords >= TypeList.size())
00943         return Error(BitcodeError::InvalidTYPETable);
00944 
00945       // Check to see if this was forward referenced, if so fill in the temp.
00946       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
00947       if (Res) {
00948         Res->setName(TypeName);
00949         TypeList[NumRecords] = nullptr;
00950       } else  // Otherwise, create a new struct with no body.
00951         Res = StructType::create(Context, TypeName);
00952       TypeName.clear();
00953       ResultTy = Res;
00954       break;
00955     }
00956     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
00957       if (Record.size() < 2)
00958         return Error(BitcodeError::InvalidRecord);
00959       if ((ResultTy = getTypeByID(Record[1])))
00960         ResultTy = ArrayType::get(ResultTy, Record[0]);
00961       else
00962         return Error(BitcodeError::InvalidType);
00963       break;
00964     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
00965       if (Record.size() < 2)
00966         return Error(BitcodeError::InvalidRecord);
00967       if ((ResultTy = getTypeByID(Record[1])))
00968         ResultTy = VectorType::get(ResultTy, Record[0]);
00969       else
00970         return Error(BitcodeError::InvalidType);
00971       break;
00972     }
00973 
00974     if (NumRecords >= TypeList.size())
00975       return Error(BitcodeError::InvalidTYPETable);
00976     assert(ResultTy && "Didn't read a type?");
00977     assert(!TypeList[NumRecords] && "Already read type?");
00978     TypeList[NumRecords++] = ResultTy;
00979   }
00980 }
00981 
00982 std::error_code BitcodeReader::ParseValueSymbolTable() {
00983   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
00984     return Error(BitcodeError::InvalidRecord);
00985 
00986   SmallVector<uint64_t, 64> Record;
00987 
00988   // Read all the records for this value table.
00989   SmallString<128> ValueName;
00990   while (1) {
00991     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
00992 
00993     switch (Entry.Kind) {
00994     case BitstreamEntry::SubBlock: // Handled for us already.
00995     case BitstreamEntry::Error:
00996       return Error(BitcodeError::MalformedBlock);
00997     case BitstreamEntry::EndBlock:
00998       return std::error_code();
00999     case BitstreamEntry::Record:
01000       // The interesting case.
01001       break;
01002     }
01003 
01004     // Read a record.
01005     Record.clear();
01006     switch (Stream.readRecord(Entry.ID, Record)) {
01007     default:  // Default behavior: unknown type.
01008       break;
01009     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
01010       if (ConvertToString(Record, 1, ValueName))
01011         return Error(BitcodeError::InvalidRecord);
01012       unsigned ValueID = Record[0];
01013       if (ValueID >= ValueList.size() || !ValueList[ValueID])
01014         return Error(BitcodeError::InvalidRecord);
01015       Value *V = ValueList[ValueID];
01016 
01017       V->setName(StringRef(ValueName.data(), ValueName.size()));
01018       ValueName.clear();
01019       break;
01020     }
01021     case bitc::VST_CODE_BBENTRY: {
01022       if (ConvertToString(Record, 1, ValueName))
01023         return Error(BitcodeError::InvalidRecord);
01024       BasicBlock *BB = getBasicBlock(Record[0]);
01025       if (!BB)
01026         return Error(BitcodeError::InvalidRecord);
01027 
01028       BB->setName(StringRef(ValueName.data(), ValueName.size()));
01029       ValueName.clear();
01030       break;
01031     }
01032     }
01033   }
01034 }
01035 
01036 std::error_code BitcodeReader::ParseMetadata() {
01037   unsigned NextMDValueNo = MDValueList.size();
01038 
01039   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
01040     return Error(BitcodeError::InvalidRecord);
01041 
01042   SmallVector<uint64_t, 64> Record;
01043 
01044   // Read all the records.
01045   while (1) {
01046     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01047 
01048     switch (Entry.Kind) {
01049     case BitstreamEntry::SubBlock: // Handled for us already.
01050     case BitstreamEntry::Error:
01051       return Error(BitcodeError::MalformedBlock);
01052     case BitstreamEntry::EndBlock:
01053       return std::error_code();
01054     case BitstreamEntry::Record:
01055       // The interesting case.
01056       break;
01057     }
01058 
01059     bool IsFunctionLocal = false;
01060     // Read a record.
01061     Record.clear();
01062     unsigned Code = Stream.readRecord(Entry.ID, Record);
01063     switch (Code) {
01064     default:  // Default behavior: ignore.
01065       break;
01066     case bitc::METADATA_NAME: {
01067       // Read name of the named metadata.
01068       SmallString<8> Name(Record.begin(), Record.end());
01069       Record.clear();
01070       Code = Stream.ReadCode();
01071 
01072       // METADATA_NAME is always followed by METADATA_NAMED_NODE.
01073       unsigned NextBitCode = Stream.readRecord(Code, Record);
01074       assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
01075 
01076       // Read named metadata elements.
01077       unsigned Size = Record.size();
01078       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
01079       for (unsigned i = 0; i != Size; ++i) {
01080         MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
01081         if (!MD)
01082           return Error(BitcodeError::InvalidRecord);
01083         NMD->addOperand(MD);
01084       }
01085       break;
01086     }
01087     case bitc::METADATA_FN_NODE:
01088       IsFunctionLocal = true;
01089       // fall-through
01090     case bitc::METADATA_NODE: {
01091       if (Record.size() % 2 == 1)
01092         return Error(BitcodeError::InvalidRecord);
01093 
01094       unsigned Size = Record.size();
01095       SmallVector<Value*, 8> Elts;
01096       for (unsigned i = 0; i != Size; i += 2) {
01097         Type *Ty = getTypeByID(Record[i]);
01098         if (!Ty)
01099           return Error(BitcodeError::InvalidRecord);
01100         if (Ty->isMetadataTy())
01101           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
01102         else if (!Ty->isVoidTy())
01103           Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
01104         else
01105           Elts.push_back(nullptr);
01106       }
01107       Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
01108       IsFunctionLocal = false;
01109       MDValueList.AssignValue(V, NextMDValueNo++);
01110       break;
01111     }
01112     case bitc::METADATA_STRING: {
01113       std::string String(Record.begin(), Record.end());
01114       llvm::UpgradeMDStringConstant(String);
01115       Value *V = MDString::get(Context, String);
01116       MDValueList.AssignValue(V, NextMDValueNo++);
01117       break;
01118     }
01119     case bitc::METADATA_KIND: {
01120       if (Record.size() < 2)
01121         return Error(BitcodeError::InvalidRecord);
01122 
01123       unsigned Kind = Record[0];
01124       SmallString<8> Name(Record.begin()+1, Record.end());
01125 
01126       unsigned NewKind = TheModule->getMDKindID(Name.str());
01127       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
01128         return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
01129       break;
01130     }
01131     }
01132   }
01133 }
01134 
01135 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
01136 /// the LSB for dense VBR encoding.
01137 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
01138   if ((V & 1) == 0)
01139     return V >> 1;
01140   if (V != 1)
01141     return -(V >> 1);
01142   // There is no such thing as -0 with integers.  "-0" really means MININT.
01143   return 1ULL << 63;
01144 }
01145 
01146 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
01147 /// values and aliases that we can.
01148 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
01149   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
01150   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
01151   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
01152 
01153   GlobalInitWorklist.swap(GlobalInits);
01154   AliasInitWorklist.swap(AliasInits);
01155   FunctionPrefixWorklist.swap(FunctionPrefixes);
01156 
01157   while (!GlobalInitWorklist.empty()) {
01158     unsigned ValID = GlobalInitWorklist.back().second;
01159     if (ValID >= ValueList.size()) {
01160       // Not ready to resolve this yet, it requires something later in the file.
01161       GlobalInits.push_back(GlobalInitWorklist.back());
01162     } else {
01163       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
01164         GlobalInitWorklist.back().first->setInitializer(C);
01165       else
01166         return Error(BitcodeError::ExpectedConstant);
01167     }
01168     GlobalInitWorklist.pop_back();
01169   }
01170 
01171   while (!AliasInitWorklist.empty()) {
01172     unsigned ValID = AliasInitWorklist.back().second;
01173     if (ValID >= ValueList.size()) {
01174       AliasInits.push_back(AliasInitWorklist.back());
01175     } else {
01176       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
01177         AliasInitWorklist.back().first->setAliasee(C);
01178       else
01179         return Error(BitcodeError::ExpectedConstant);
01180     }
01181     AliasInitWorklist.pop_back();
01182   }
01183 
01184   while (!FunctionPrefixWorklist.empty()) {
01185     unsigned ValID = FunctionPrefixWorklist.back().second;
01186     if (ValID >= ValueList.size()) {
01187       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
01188     } else {
01189       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
01190         FunctionPrefixWorklist.back().first->setPrefixData(C);
01191       else
01192         return Error(BitcodeError::ExpectedConstant);
01193     }
01194     FunctionPrefixWorklist.pop_back();
01195   }
01196 
01197   return std::error_code();
01198 }
01199 
01200 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
01201   SmallVector<uint64_t, 8> Words(Vals.size());
01202   std::transform(Vals.begin(), Vals.end(), Words.begin(),
01203                  BitcodeReader::decodeSignRotatedValue);
01204 
01205   return APInt(TypeBits, Words);
01206 }
01207 
01208 std::error_code BitcodeReader::ParseConstants() {
01209   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
01210     return Error(BitcodeError::InvalidRecord);
01211 
01212   SmallVector<uint64_t, 64> Record;
01213 
01214   // Read all the records for this value table.
01215   Type *CurTy = Type::getInt32Ty(Context);
01216   unsigned NextCstNo = ValueList.size();
01217   while (1) {
01218     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01219 
01220     switch (Entry.Kind) {
01221     case BitstreamEntry::SubBlock: // Handled for us already.
01222     case BitstreamEntry::Error:
01223       return Error(BitcodeError::MalformedBlock);
01224     case BitstreamEntry::EndBlock:
01225       if (NextCstNo != ValueList.size())
01226         return Error(BitcodeError::InvalidConstantReference);
01227 
01228       // Once all the constants have been read, go through and resolve forward
01229       // references.
01230       ValueList.ResolveConstantForwardRefs();
01231       return std::error_code();
01232     case BitstreamEntry::Record:
01233       // The interesting case.
01234       break;
01235     }
01236 
01237     // Read a record.
01238     Record.clear();
01239     Value *V = nullptr;
01240     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
01241     switch (BitCode) {
01242     default:  // Default behavior: unknown constant
01243     case bitc::CST_CODE_UNDEF:     // UNDEF
01244       V = UndefValue::get(CurTy);
01245       break;
01246     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
01247       if (Record.empty())
01248         return Error(BitcodeError::InvalidRecord);
01249       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
01250         return Error(BitcodeError::InvalidRecord);
01251       CurTy = TypeList[Record[0]];
01252       continue;  // Skip the ValueList manipulation.
01253     case bitc::CST_CODE_NULL:      // NULL
01254       V = Constant::getNullValue(CurTy);
01255       break;
01256     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
01257       if (!CurTy->isIntegerTy() || Record.empty())
01258         return Error(BitcodeError::InvalidRecord);
01259       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
01260       break;
01261     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
01262       if (!CurTy->isIntegerTy() || Record.empty())
01263         return Error(BitcodeError::InvalidRecord);
01264 
01265       APInt VInt = ReadWideAPInt(Record,
01266                                  cast<IntegerType>(CurTy)->getBitWidth());
01267       V = ConstantInt::get(Context, VInt);
01268 
01269       break;
01270     }
01271     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
01272       if (Record.empty())
01273         return Error(BitcodeError::InvalidRecord);
01274       if (CurTy->isHalfTy())
01275         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
01276                                              APInt(16, (uint16_t)Record[0])));
01277       else if (CurTy->isFloatTy())
01278         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
01279                                              APInt(32, (uint32_t)Record[0])));
01280       else if (CurTy->isDoubleTy())
01281         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
01282                                              APInt(64, Record[0])));
01283       else if (CurTy->isX86_FP80Ty()) {
01284         // Bits are not stored the same way as a normal i80 APInt, compensate.
01285         uint64_t Rearrange[2];
01286         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
01287         Rearrange[1] = Record[0] >> 48;
01288         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
01289                                              APInt(80, Rearrange)));
01290       } else if (CurTy->isFP128Ty())
01291         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
01292                                              APInt(128, Record)));
01293       else if (CurTy->isPPC_FP128Ty())
01294         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
01295                                              APInt(128, Record)));
01296       else
01297         V = UndefValue::get(CurTy);
01298       break;
01299     }
01300 
01301     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
01302       if (Record.empty())
01303         return Error(BitcodeError::InvalidRecord);
01304 
01305       unsigned Size = Record.size();
01306       SmallVector<Constant*, 16> Elts;
01307 
01308       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
01309         for (unsigned i = 0; i != Size; ++i)
01310           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
01311                                                      STy->getElementType(i)));
01312         V = ConstantStruct::get(STy, Elts);
01313       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
01314         Type *EltTy = ATy->getElementType();
01315         for (unsigned i = 0; i != Size; ++i)
01316           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
01317         V = ConstantArray::get(ATy, Elts);
01318       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
01319         Type *EltTy = VTy->getElementType();
01320         for (unsigned i = 0; i != Size; ++i)
01321           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
01322         V = ConstantVector::get(Elts);
01323       } else {
01324         V = UndefValue::get(CurTy);
01325       }
01326       break;
01327     }
01328     case bitc::CST_CODE_STRING:    // STRING: [values]
01329     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
01330       if (Record.empty())
01331         return Error(BitcodeError::InvalidRecord);
01332 
01333       SmallString<16> Elts(Record.begin(), Record.end());
01334       V = ConstantDataArray::getString(Context, Elts,
01335                                        BitCode == bitc::CST_CODE_CSTRING);
01336       break;
01337     }
01338     case bitc::CST_CODE_DATA: {// DATA: [n x value]
01339       if (Record.empty())
01340         return Error(BitcodeError::InvalidRecord);
01341 
01342       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
01343       unsigned Size = Record.size();
01344 
01345       if (EltTy->isIntegerTy(8)) {
01346         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
01347         if (isa<VectorType>(CurTy))
01348           V = ConstantDataVector::get(Context, Elts);
01349         else
01350           V = ConstantDataArray::get(Context, Elts);
01351       } else if (EltTy->isIntegerTy(16)) {
01352         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
01353         if (isa<VectorType>(CurTy))
01354           V = ConstantDataVector::get(Context, Elts);
01355         else
01356           V = ConstantDataArray::get(Context, Elts);
01357       } else if (EltTy->isIntegerTy(32)) {
01358         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
01359         if (isa<VectorType>(CurTy))
01360           V = ConstantDataVector::get(Context, Elts);
01361         else
01362           V = ConstantDataArray::get(Context, Elts);
01363       } else if (EltTy->isIntegerTy(64)) {
01364         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
01365         if (isa<VectorType>(CurTy))
01366           V = ConstantDataVector::get(Context, Elts);
01367         else
01368           V = ConstantDataArray::get(Context, Elts);
01369       } else if (EltTy->isFloatTy()) {
01370         SmallVector<float, 16> Elts(Size);
01371         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
01372         if (isa<VectorType>(CurTy))
01373           V = ConstantDataVector::get(Context, Elts);
01374         else
01375           V = ConstantDataArray::get(Context, Elts);
01376       } else if (EltTy->isDoubleTy()) {
01377         SmallVector<double, 16> Elts(Size);
01378         std::transform(Record.begin(), Record.end(), Elts.begin(),
01379                        BitsToDouble);
01380         if (isa<VectorType>(CurTy))
01381           V = ConstantDataVector::get(Context, Elts);
01382         else
01383           V = ConstantDataArray::get(Context, Elts);
01384       } else {
01385         return Error(BitcodeError::InvalidTypeForValue);
01386       }
01387       break;
01388     }
01389 
01390     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
01391       if (Record.size() < 3)
01392         return Error(BitcodeError::InvalidRecord);
01393       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
01394       if (Opc < 0) {
01395         V = UndefValue::get(CurTy);  // Unknown binop.
01396       } else {
01397         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
01398         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
01399         unsigned Flags = 0;
01400         if (Record.size() >= 4) {
01401           if (Opc == Instruction::Add ||
01402               Opc == Instruction::Sub ||
01403               Opc == Instruction::Mul ||
01404               Opc == Instruction::Shl) {
01405             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
01406               Flags |= OverflowingBinaryOperator::NoSignedWrap;
01407             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
01408               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
01409           } else if (Opc == Instruction::SDiv ||
01410                      Opc == Instruction::UDiv ||
01411                      Opc == Instruction::LShr ||
01412                      Opc == Instruction::AShr) {
01413             if (Record[3] & (1 << bitc::PEO_EXACT))
01414               Flags |= SDivOperator::IsExact;
01415           }
01416         }
01417         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
01418       }
01419       break;
01420     }
01421     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
01422       if (Record.size() < 3)
01423         return Error(BitcodeError::InvalidRecord);
01424       int Opc = GetDecodedCastOpcode(Record[0]);
01425       if (Opc < 0) {
01426         V = UndefValue::get(CurTy);  // Unknown cast.
01427       } else {
01428         Type *OpTy = getTypeByID(Record[1]);
01429         if (!OpTy)
01430           return Error(BitcodeError::InvalidRecord);
01431         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
01432         V = UpgradeBitCastExpr(Opc, Op, CurTy);
01433         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
01434       }
01435       break;
01436     }
01437     case bitc::CST_CODE_CE_INBOUNDS_GEP:
01438     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
01439       if (Record.size() & 1)
01440         return Error(BitcodeError::InvalidRecord);
01441       SmallVector<Constant*, 16> Elts;
01442       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
01443         Type *ElTy = getTypeByID(Record[i]);
01444         if (!ElTy)
01445           return Error(BitcodeError::InvalidRecord);
01446         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
01447       }
01448       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
01449       V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
01450                                          BitCode ==
01451                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
01452       break;
01453     }
01454     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
01455       if (Record.size() < 3)
01456         return Error(BitcodeError::InvalidRecord);
01457 
01458       Type *SelectorTy = Type::getInt1Ty(Context);
01459 
01460       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
01461       // vector. Otherwise, it must be a single bit.
01462       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
01463         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
01464                                      VTy->getNumElements());
01465 
01466       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
01467                                                               SelectorTy),
01468                                   ValueList.getConstantFwdRef(Record[1],CurTy),
01469                                   ValueList.getConstantFwdRef(Record[2],CurTy));
01470       break;
01471     }
01472     case bitc::CST_CODE_CE_EXTRACTELT
01473         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
01474       if (Record.size() < 3)
01475         return Error(BitcodeError::InvalidRecord);
01476       VectorType *OpTy =
01477         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
01478       if (!OpTy)
01479         return Error(BitcodeError::InvalidRecord);
01480       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
01481       Constant *Op1 = nullptr;
01482       if (Record.size() == 4) {
01483         Type *IdxTy = getTypeByID(Record[2]);
01484         if (!IdxTy)
01485           return Error(BitcodeError::InvalidRecord);
01486         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
01487       } else // TODO: Remove with llvm 4.0
01488         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
01489       if (!Op1)
01490         return Error(BitcodeError::InvalidRecord);
01491       V = ConstantExpr::getExtractElement(Op0, Op1);
01492       break;
01493     }
01494     case bitc::CST_CODE_CE_INSERTELT
01495         : { // CE_INSERTELT: [opval, opval, opty, opval]
01496       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
01497       if (Record.size() < 3 || !OpTy)
01498         return Error(BitcodeError::InvalidRecord);
01499       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
01500       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
01501                                                   OpTy->getElementType());
01502       Constant *Op2 = nullptr;
01503       if (Record.size() == 4) {
01504         Type *IdxTy = getTypeByID(Record[2]);
01505         if (!IdxTy)
01506           return Error(BitcodeError::InvalidRecord);
01507         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
01508       } else // TODO: Remove with llvm 4.0
01509         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
01510       if (!Op2)
01511         return Error(BitcodeError::InvalidRecord);
01512       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
01513       break;
01514     }
01515     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
01516       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
01517       if (Record.size() < 3 || !OpTy)
01518         return Error(BitcodeError::InvalidRecord);
01519       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
01520       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
01521       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
01522                                                  OpTy->getNumElements());
01523       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
01524       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
01525       break;
01526     }
01527     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
01528       VectorType *RTy = dyn_cast<VectorType>(CurTy);
01529       VectorType *OpTy =
01530         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
01531       if (Record.size() < 4 || !RTy || !OpTy)
01532         return Error(BitcodeError::InvalidRecord);
01533       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
01534       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
01535       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
01536                                                  RTy->getNumElements());
01537       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
01538       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
01539       break;
01540     }
01541     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
01542       if (Record.size() < 4)
01543         return Error(BitcodeError::InvalidRecord);
01544       Type *OpTy = getTypeByID(Record[0]);
01545       if (!OpTy)
01546         return Error(BitcodeError::InvalidRecord);
01547       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
01548       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
01549 
01550       if (OpTy->isFPOrFPVectorTy())
01551         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
01552       else
01553         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
01554       break;
01555     }
01556     // This maintains backward compatibility, pre-asm dialect keywords.
01557     // FIXME: Remove with the 4.0 release.
01558     case bitc::CST_CODE_INLINEASM_OLD: {
01559       if (Record.size() < 2)
01560         return Error(BitcodeError::InvalidRecord);
01561       std::string AsmStr, ConstrStr;
01562       bool HasSideEffects = Record[0] & 1;
01563       bool IsAlignStack = Record[0] >> 1;
01564       unsigned AsmStrSize = Record[1];
01565       if (2+AsmStrSize >= Record.size())
01566         return Error(BitcodeError::InvalidRecord);
01567       unsigned ConstStrSize = Record[2+AsmStrSize];
01568       if (3+AsmStrSize+ConstStrSize > Record.size())
01569         return Error(BitcodeError::InvalidRecord);
01570 
01571       for (unsigned i = 0; i != AsmStrSize; ++i)
01572         AsmStr += (char)Record[2+i];
01573       for (unsigned i = 0; i != ConstStrSize; ++i)
01574         ConstrStr += (char)Record[3+AsmStrSize+i];
01575       PointerType *PTy = cast<PointerType>(CurTy);
01576       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
01577                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
01578       break;
01579     }
01580     // This version adds support for the asm dialect keywords (e.g.,
01581     // inteldialect).
01582     case bitc::CST_CODE_INLINEASM: {
01583       if (Record.size() < 2)
01584         return Error(BitcodeError::InvalidRecord);
01585       std::string AsmStr, ConstrStr;
01586       bool HasSideEffects = Record[0] & 1;
01587       bool IsAlignStack = (Record[0] >> 1) & 1;
01588       unsigned AsmDialect = Record[0] >> 2;
01589       unsigned AsmStrSize = Record[1];
01590       if (2+AsmStrSize >= Record.size())
01591         return Error(BitcodeError::InvalidRecord);
01592       unsigned ConstStrSize = Record[2+AsmStrSize];
01593       if (3+AsmStrSize+ConstStrSize > Record.size())
01594         return Error(BitcodeError::InvalidRecord);
01595 
01596       for (unsigned i = 0; i != AsmStrSize; ++i)
01597         AsmStr += (char)Record[2+i];
01598       for (unsigned i = 0; i != ConstStrSize; ++i)
01599         ConstrStr += (char)Record[3+AsmStrSize+i];
01600       PointerType *PTy = cast<PointerType>(CurTy);
01601       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
01602                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
01603                          InlineAsm::AsmDialect(AsmDialect));
01604       break;
01605     }
01606     case bitc::CST_CODE_BLOCKADDRESS:{
01607       if (Record.size() < 3)
01608         return Error(BitcodeError::InvalidRecord);
01609       Type *FnTy = getTypeByID(Record[0]);
01610       if (!FnTy)
01611         return Error(BitcodeError::InvalidRecord);
01612       Function *Fn =
01613         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
01614       if (!Fn)
01615         return Error(BitcodeError::InvalidRecord);
01616 
01617       // Don't let Fn get dematerialized.
01618       BlockAddressesTaken.insert(Fn);
01619 
01620       // If the function is already parsed we can insert the block address right
01621       // away.
01622       BasicBlock *BB;
01623       unsigned BBID = Record[2];
01624       if (!BBID)
01625         // Invalid reference to entry block.
01626         return Error(BitcodeError::InvalidID);
01627       if (!Fn->empty()) {
01628         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
01629         for (size_t I = 0, E = BBID; I != E; ++I) {
01630           if (BBI == BBE)
01631             return Error(BitcodeError::InvalidID);
01632           ++BBI;
01633         }
01634         BB = BBI;
01635       } else {
01636         // Otherwise insert a placeholder and remember it so it can be inserted
01637         // when the function is parsed.
01638         auto &FwdBBs = BasicBlockFwdRefs[Fn];
01639         if (FwdBBs.empty())
01640           BasicBlockFwdRefQueue.push_back(Fn);
01641         if (FwdBBs.size() < BBID + 1)
01642           FwdBBs.resize(BBID + 1);
01643         if (!FwdBBs[BBID])
01644           FwdBBs[BBID] = BasicBlock::Create(Context);
01645         BB = FwdBBs[BBID];
01646       }
01647       V = BlockAddress::get(Fn, BB);
01648       break;
01649     }
01650     }
01651 
01652     ValueList.AssignValue(V, NextCstNo);
01653     ++NextCstNo;
01654   }
01655 }
01656 
01657 std::error_code BitcodeReader::ParseUseLists() {
01658   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
01659     return Error(BitcodeError::InvalidRecord);
01660 
01661   // Read all the records.
01662   SmallVector<uint64_t, 64> Record;
01663   while (1) {
01664     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
01665 
01666     switch (Entry.Kind) {
01667     case BitstreamEntry::SubBlock: // Handled for us already.
01668     case BitstreamEntry::Error:
01669       return Error(BitcodeError::MalformedBlock);
01670     case BitstreamEntry::EndBlock:
01671       return std::error_code();
01672     case BitstreamEntry::Record:
01673       // The interesting case.
01674       break;
01675     }
01676 
01677     // Read a use list record.
01678     Record.clear();
01679     bool IsBB = false;
01680     switch (Stream.readRecord(Entry.ID, Record)) {
01681     default:  // Default behavior: unknown type.
01682       break;
01683     case bitc::USELIST_CODE_BB:
01684       IsBB = true;
01685       // fallthrough
01686     case bitc::USELIST_CODE_DEFAULT: {
01687       unsigned RecordLength = Record.size();
01688       if (RecordLength < 3)
01689         // Records should have at least an ID and two indexes.
01690         return Error(BitcodeError::InvalidRecord);
01691       unsigned ID = Record.back();
01692       Record.pop_back();
01693 
01694       Value *V;
01695       if (IsBB) {
01696         assert(ID < FunctionBBs.size() && "Basic block not found");
01697         V = FunctionBBs[ID];
01698       } else
01699         V = ValueList[ID];
01700       unsigned NumUses = 0;
01701       SmallDenseMap<const Use *, unsigned, 16> Order;
01702       for (const Use &U : V->uses()) {
01703         if (++NumUses > Record.size())
01704           break;
01705         Order[&U] = Record[NumUses - 1];
01706       }
01707       if (Order.size() != Record.size() || NumUses > Record.size())
01708         // Mismatches can happen if the functions are being materialized lazily
01709         // (out-of-order), or a value has been upgraded.
01710         break;
01711 
01712       V->sortUseList([&](const Use &L, const Use &R) {
01713         return Order.lookup(&L) < Order.lookup(&R);
01714       });
01715       break;
01716     }
01717     }
01718   }
01719 }
01720 
01721 /// RememberAndSkipFunctionBody - When we see the block for a function body,
01722 /// remember where it is and then skip it.  This lets us lazily deserialize the
01723 /// functions.
01724 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
01725   // Get the function we are talking about.
01726   if (FunctionsWithBodies.empty())
01727     return Error(BitcodeError::InsufficientFunctionProtos);
01728 
01729   Function *Fn = FunctionsWithBodies.back();
01730   FunctionsWithBodies.pop_back();
01731 
01732   // Save the current stream state.
01733   uint64_t CurBit = Stream.GetCurrentBitNo();
01734   DeferredFunctionInfo[Fn] = CurBit;
01735 
01736   // Skip over the function block for now.
01737   if (Stream.SkipBlock())
01738     return Error(BitcodeError::InvalidRecord);
01739   return std::error_code();
01740 }
01741 
01742 std::error_code BitcodeReader::GlobalCleanup() {
01743   // Patch the initializers for globals and aliases up.
01744   ResolveGlobalAndAliasInits();
01745   if (!GlobalInits.empty() || !AliasInits.empty())
01746     return Error(BitcodeError::MalformedGlobalInitializerSet);
01747 
01748   // Look for intrinsic functions which need to be upgraded at some point
01749   for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
01750        FI != FE; ++FI) {
01751     Function *NewFn;
01752     if (UpgradeIntrinsicFunction(FI, NewFn))
01753       UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
01754   }
01755 
01756   // Look for global variables which need to be renamed.
01757   for (Module::global_iterator
01758          GI = TheModule->global_begin(), GE = TheModule->global_end();
01759        GI != GE;) {
01760     GlobalVariable *GV = GI++;
01761     UpgradeGlobalVariable(GV);
01762   }
01763 
01764   // Force deallocation of memory for these vectors to favor the client that
01765   // want lazy deserialization.
01766   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
01767   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
01768   return std::error_code();
01769 }
01770 
01771 std::error_code BitcodeReader::ParseModule(bool Resume) {
01772   if (Resume)
01773     Stream.JumpToBit(NextUnreadBit);
01774   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
01775     return Error(BitcodeError::InvalidRecord);
01776 
01777   SmallVector<uint64_t, 64> Record;
01778   std::vector<std::string> SectionTable;
01779   std::vector<std::string> GCTable;
01780 
01781   // Read all the records for this module.
01782   while (1) {
01783     BitstreamEntry Entry = Stream.advance();
01784 
01785     switch (Entry.Kind) {
01786     case BitstreamEntry::Error:
01787       return Error(BitcodeError::MalformedBlock);
01788     case BitstreamEntry::EndBlock:
01789       return GlobalCleanup();
01790 
01791     case BitstreamEntry::SubBlock:
01792       switch (Entry.ID) {
01793       default:  // Skip unknown content.
01794         if (Stream.SkipBlock())
01795           return Error(BitcodeError::InvalidRecord);
01796         break;
01797       case bitc::BLOCKINFO_BLOCK_ID:
01798         if (Stream.ReadBlockInfoBlock())
01799           return Error(BitcodeError::MalformedBlock);
01800         break;
01801       case bitc::PARAMATTR_BLOCK_ID:
01802         if (std::error_code EC = ParseAttributeBlock())
01803           return EC;
01804         break;
01805       case bitc::PARAMATTR_GROUP_BLOCK_ID:
01806         if (std::error_code EC = ParseAttributeGroupBlock())
01807           return EC;
01808         break;
01809       case bitc::TYPE_BLOCK_ID_NEW:
01810         if (std::error_code EC = ParseTypeTable())
01811           return EC;
01812         break;
01813       case bitc::VALUE_SYMTAB_BLOCK_ID:
01814         if (std::error_code EC = ParseValueSymbolTable())
01815           return EC;
01816         SeenValueSymbolTable = true;
01817         break;
01818       case bitc::CONSTANTS_BLOCK_ID:
01819         if (std::error_code EC = ParseConstants())
01820           return EC;
01821         if (std::error_code EC = ResolveGlobalAndAliasInits())
01822           return EC;
01823         break;
01824       case bitc::METADATA_BLOCK_ID:
01825         if (std::error_code EC = ParseMetadata())
01826           return EC;
01827         break;
01828       case bitc::FUNCTION_BLOCK_ID:
01829         // If this is the first function body we've seen, reverse the
01830         // FunctionsWithBodies list.
01831         if (!SeenFirstFunctionBody) {
01832           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
01833           if (std::error_code EC = GlobalCleanup())
01834             return EC;
01835           SeenFirstFunctionBody = true;
01836         }
01837 
01838         if (std::error_code EC = RememberAndSkipFunctionBody())
01839           return EC;
01840         // For streaming bitcode, suspend parsing when we reach the function
01841         // bodies. Subsequent materialization calls will resume it when
01842         // necessary. For streaming, the function bodies must be at the end of
01843         // the bitcode. If the bitcode file is old, the symbol table will be
01844         // at the end instead and will not have been seen yet. In this case,
01845         // just finish the parse now.
01846         if (LazyStreamer && SeenValueSymbolTable) {
01847           NextUnreadBit = Stream.GetCurrentBitNo();
01848           return std::error_code();
01849         }
01850         break;
01851       case bitc::USELIST_BLOCK_ID:
01852         if (std::error_code EC = ParseUseLists())
01853           return EC;
01854         break;
01855       }
01856       continue;
01857 
01858     case BitstreamEntry::Record:
01859       // The interesting case.
01860       break;
01861     }
01862 
01863 
01864     // Read a record.
01865     switch (Stream.readRecord(Entry.ID, Record)) {
01866     default: break;  // Default behavior, ignore unknown content.
01867     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
01868       if (Record.size() < 1)
01869         return Error(BitcodeError::InvalidRecord);
01870       // Only version #0 and #1 are supported so far.
01871       unsigned module_version = Record[0];
01872       switch (module_version) {
01873         default:
01874           return Error(BitcodeError::InvalidValue);
01875         case 0:
01876           UseRelativeIDs = false;
01877           break;
01878         case 1:
01879           UseRelativeIDs = true;
01880           break;
01881       }
01882       break;
01883     }
01884     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
01885       std::string S;
01886       if (ConvertToString(Record, 0, S))
01887         return Error(BitcodeError::InvalidRecord);
01888       TheModule->setTargetTriple(S);
01889       break;
01890     }
01891     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
01892       std::string S;
01893       if (ConvertToString(Record, 0, S))
01894         return Error(BitcodeError::InvalidRecord);
01895       TheModule->setDataLayout(S);
01896       break;
01897     }
01898     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
01899       std::string S;
01900       if (ConvertToString(Record, 0, S))
01901         return Error(BitcodeError::InvalidRecord);
01902       TheModule->setModuleInlineAsm(S);
01903       break;
01904     }
01905     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
01906       // FIXME: Remove in 4.0.
01907       std::string S;
01908       if (ConvertToString(Record, 0, S))
01909         return Error(BitcodeError::InvalidRecord);
01910       // Ignore value.
01911       break;
01912     }
01913     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
01914       std::string S;
01915       if (ConvertToString(Record, 0, S))
01916         return Error(BitcodeError::InvalidRecord);
01917       SectionTable.push_back(S);
01918       break;
01919     }
01920     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
01921       std::string S;
01922       if (ConvertToString(Record, 0, S))
01923         return Error(BitcodeError::InvalidRecord);
01924       GCTable.push_back(S);
01925       break;
01926     }
01927     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
01928       if (Record.size() < 2)
01929         return Error(BitcodeError::InvalidRecord);
01930       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
01931       unsigned ComdatNameSize = Record[1];
01932       std::string ComdatName;
01933       ComdatName.reserve(ComdatNameSize);
01934       for (unsigned i = 0; i != ComdatNameSize; ++i)
01935         ComdatName += (char)Record[2 + i];
01936       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
01937       C->setSelectionKind(SK);
01938       ComdatList.push_back(C);
01939       break;
01940     }
01941     // GLOBALVAR: [pointer type, isconst, initid,
01942     //             linkage, alignment, section, visibility, threadlocal,
01943     //             unnamed_addr, dllstorageclass]
01944     case bitc::MODULE_CODE_GLOBALVAR: {
01945       if (Record.size() < 6)
01946         return Error(BitcodeError::InvalidRecord);
01947       Type *Ty = getTypeByID(Record[0]);
01948       if (!Ty)
01949         return Error(BitcodeError::InvalidRecord);
01950       if (!Ty->isPointerTy())
01951         return Error(BitcodeError::InvalidTypeForValue);
01952       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
01953       Ty = cast<PointerType>(Ty)->getElementType();
01954 
01955       bool isConstant = Record[1];
01956       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
01957       unsigned Alignment = (1 << Record[4]) >> 1;
01958       std::string Section;
01959       if (Record[5]) {
01960         if (Record[5]-1 >= SectionTable.size())
01961           return Error(BitcodeError::InvalidID);
01962         Section = SectionTable[Record[5]-1];
01963       }
01964       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
01965       // Local linkage must have default visibility.
01966       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
01967         // FIXME: Change to an error if non-default in 4.0.
01968         Visibility = GetDecodedVisibility(Record[6]);
01969 
01970       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
01971       if (Record.size() > 7)
01972         TLM = GetDecodedThreadLocalMode(Record[7]);
01973 
01974       bool UnnamedAddr = false;
01975       if (Record.size() > 8)
01976         UnnamedAddr = Record[8];
01977 
01978       bool ExternallyInitialized = false;
01979       if (Record.size() > 9)
01980         ExternallyInitialized = Record[9];
01981 
01982       GlobalVariable *NewGV =
01983         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
01984                            TLM, AddressSpace, ExternallyInitialized);
01985       NewGV->setAlignment(Alignment);
01986       if (!Section.empty())
01987         NewGV->setSection(Section);
01988       NewGV->setVisibility(Visibility);
01989       NewGV->setUnnamedAddr(UnnamedAddr);
01990 
01991       if (Record.size() > 10)
01992         NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10]));
01993       else
01994         UpgradeDLLImportExportLinkage(NewGV, Record[3]);
01995 
01996       ValueList.push_back(NewGV);
01997 
01998       // Remember which value to use for the global initializer.
01999       if (unsigned InitID = Record[2])
02000         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
02001 
02002       if (Record.size() > 11)
02003         if (unsigned ComdatID = Record[11]) {
02004           assert(ComdatID <= ComdatList.size());
02005           NewGV->setComdat(ComdatList[ComdatID - 1]);
02006         }
02007       break;
02008     }
02009     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
02010     //             alignment, section, visibility, gc, unnamed_addr,
02011     //             dllstorageclass]
02012     case bitc::MODULE_CODE_FUNCTION: {
02013       if (Record.size() < 8)
02014         return Error(BitcodeError::InvalidRecord);
02015       Type *Ty = getTypeByID(Record[0]);
02016       if (!Ty)
02017         return Error(BitcodeError::InvalidRecord);
02018       if (!Ty->isPointerTy())
02019         return Error(BitcodeError::InvalidTypeForValue);
02020       FunctionType *FTy =
02021         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
02022       if (!FTy)
02023         return Error(BitcodeError::InvalidTypeForValue);
02024 
02025       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
02026                                         "", TheModule);
02027 
02028       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
02029       bool isProto = Record[2];
02030       Func->setLinkage(GetDecodedLinkage(Record[3]));
02031       Func->setAttributes(getAttributes(Record[4]));
02032 
02033       Func->setAlignment((1 << Record[5]) >> 1);
02034       if (Record[6]) {
02035         if (Record[6]-1 >= SectionTable.size())
02036           return Error(BitcodeError::InvalidID);
02037         Func->setSection(SectionTable[Record[6]-1]);
02038       }
02039       // Local linkage must have default visibility.
02040       if (!Func->hasLocalLinkage())
02041         // FIXME: Change to an error if non-default in 4.0.
02042         Func->setVisibility(GetDecodedVisibility(Record[7]));
02043       if (Record.size() > 8 && Record[8]) {
02044         if (Record[8]-1 > GCTable.size())
02045           return Error(BitcodeError::InvalidID);
02046         Func->setGC(GCTable[Record[8]-1].c_str());
02047       }
02048       bool UnnamedAddr = false;
02049       if (Record.size() > 9)
02050         UnnamedAddr = Record[9];
02051       Func->setUnnamedAddr(UnnamedAddr);
02052       if (Record.size() > 10 && Record[10] != 0)
02053         FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
02054 
02055       if (Record.size() > 11)
02056         Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11]));
02057       else
02058         UpgradeDLLImportExportLinkage(Func, Record[3]);
02059 
02060       if (Record.size() > 12)
02061         if (unsigned ComdatID = Record[12]) {
02062           assert(ComdatID <= ComdatList.size());
02063           Func->setComdat(ComdatList[ComdatID - 1]);
02064         }
02065 
02066       ValueList.push_back(Func);
02067 
02068       // If this is a function with a body, remember the prototype we are
02069       // creating now, so that we can match up the body with them later.
02070       if (!isProto) {
02071         FunctionsWithBodies.push_back(Func);
02072         if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
02073       }
02074       break;
02075     }
02076     // ALIAS: [alias type, aliasee val#, linkage]
02077     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
02078     case bitc::MODULE_CODE_ALIAS: {
02079       if (Record.size() < 3)
02080         return Error(BitcodeError::InvalidRecord);
02081       Type *Ty = getTypeByID(Record[0]);
02082       if (!Ty)
02083         return Error(BitcodeError::InvalidRecord);
02084       auto *PTy = dyn_cast<PointerType>(Ty);
02085       if (!PTy)
02086         return Error(BitcodeError::InvalidTypeForValue);
02087 
02088       auto *NewGA =
02089           GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
02090                               GetDecodedLinkage(Record[2]), "", TheModule);
02091       // Old bitcode files didn't have visibility field.
02092       // Local linkage must have default visibility.
02093       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
02094         // FIXME: Change to an error if non-default in 4.0.
02095         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
02096       if (Record.size() > 4)
02097         NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
02098       else
02099         UpgradeDLLImportExportLinkage(NewGA, Record[2]);
02100       if (Record.size() > 5)
02101   NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
02102       if (Record.size() > 6)
02103   NewGA->setUnnamedAddr(Record[6]);
02104       ValueList.push_back(NewGA);
02105       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
02106       break;
02107     }
02108     /// MODULE_CODE_PURGEVALS: [numvals]
02109     case bitc::MODULE_CODE_PURGEVALS:
02110       // Trim down the value list to the specified size.
02111       if (Record.size() < 1 || Record[0] > ValueList.size())
02112         return Error(BitcodeError::InvalidRecord);
02113       ValueList.shrinkTo(Record[0]);
02114       break;
02115     }
02116     Record.clear();
02117   }
02118 }
02119 
02120 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
02121   TheModule = nullptr;
02122 
02123   if (std::error_code EC = InitStream())
02124     return EC;
02125 
02126   // Sniff for the signature.
02127   if (Stream.Read(8) != 'B' ||
02128       Stream.Read(8) != 'C' ||
02129       Stream.Read(4) != 0x0 ||
02130       Stream.Read(4) != 0xC ||
02131       Stream.Read(4) != 0xE ||
02132       Stream.Read(4) != 0xD)
02133     return Error(BitcodeError::InvalidBitcodeSignature);
02134 
02135   // We expect a number of well-defined blocks, though we don't necessarily
02136   // need to understand them all.
02137   while (1) {
02138     if (Stream.AtEndOfStream())
02139       return std::error_code();
02140 
02141     BitstreamEntry Entry =
02142       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
02143 
02144     switch (Entry.Kind) {
02145     case BitstreamEntry::Error:
02146       return Error(BitcodeError::MalformedBlock);
02147     case BitstreamEntry::EndBlock:
02148       return std::error_code();
02149 
02150     case BitstreamEntry::SubBlock:
02151       switch (Entry.ID) {
02152       case bitc::BLOCKINFO_BLOCK_ID:
02153         if (Stream.ReadBlockInfoBlock())
02154           return Error(BitcodeError::MalformedBlock);
02155         break;
02156       case bitc::MODULE_BLOCK_ID:
02157         // Reject multiple MODULE_BLOCK's in a single bitstream.
02158         if (TheModule)
02159           return Error(BitcodeError::InvalidMultipleBlocks);
02160         TheModule = M;
02161         if (std::error_code EC = ParseModule(false))
02162           return EC;
02163         if (LazyStreamer)
02164           return std::error_code();
02165         break;
02166       default:
02167         if (Stream.SkipBlock())
02168           return Error(BitcodeError::InvalidRecord);
02169         break;
02170       }
02171       continue;
02172     case BitstreamEntry::Record:
02173       // There should be no records in the top-level of blocks.
02174 
02175       // The ranlib in Xcode 4 will align archive members by appending newlines
02176       // to the end of them. If this file size is a multiple of 4 but not 8, we
02177       // have to read and ignore these final 4 bytes :-(
02178       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
02179           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
02180           Stream.AtEndOfStream())
02181         return std::error_code();
02182 
02183       return Error(BitcodeError::InvalidRecord);
02184     }
02185   }
02186 }
02187 
02188 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
02189   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
02190     return Error(BitcodeError::InvalidRecord);
02191 
02192   SmallVector<uint64_t, 64> Record;
02193 
02194   std::string Triple;
02195   // Read all the records for this module.
02196   while (1) {
02197     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
02198 
02199     switch (Entry.Kind) {
02200     case BitstreamEntry::SubBlock: // Handled for us already.
02201     case BitstreamEntry::Error:
02202       return Error(BitcodeError::MalformedBlock);
02203     case BitstreamEntry::EndBlock:
02204       return Triple;
02205     case BitstreamEntry::Record:
02206       // The interesting case.
02207       break;
02208     }
02209 
02210     // Read a record.
02211     switch (Stream.readRecord(Entry.ID, Record)) {
02212     default: break;  // Default behavior, ignore unknown content.
02213     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
02214       std::string S;
02215       if (ConvertToString(Record, 0, S))
02216         return Error(BitcodeError::InvalidRecord);
02217       Triple = S;
02218       break;
02219     }
02220     }
02221     Record.clear();
02222   }
02223   llvm_unreachable("Exit infinite loop");
02224 }
02225 
02226 ErrorOr<std::string> BitcodeReader::parseTriple() {
02227   if (std::error_code EC = InitStream())
02228     return EC;
02229 
02230   // Sniff for the signature.
02231   if (Stream.Read(8) != 'B' ||
02232       Stream.Read(8) != 'C' ||
02233       Stream.Read(4) != 0x0 ||
02234       Stream.Read(4) != 0xC ||
02235       Stream.Read(4) != 0xE ||
02236       Stream.Read(4) != 0xD)
02237     return Error(BitcodeError::InvalidBitcodeSignature);
02238 
02239   // We expect a number of well-defined blocks, though we don't necessarily
02240   // need to understand them all.
02241   while (1) {
02242     BitstreamEntry Entry = Stream.advance();
02243 
02244     switch (Entry.Kind) {
02245     case BitstreamEntry::Error:
02246       return Error(BitcodeError::MalformedBlock);
02247     case BitstreamEntry::EndBlock:
02248       return std::error_code();
02249 
02250     case BitstreamEntry::SubBlock:
02251       if (Entry.ID == bitc::MODULE_BLOCK_ID)
02252         return parseModuleTriple();
02253 
02254       // Ignore other sub-blocks.
02255       if (Stream.SkipBlock())
02256         return Error(BitcodeError::MalformedBlock);
02257       continue;
02258 
02259     case BitstreamEntry::Record:
02260       Stream.skipRecord(Entry.ID);
02261       continue;
02262     }
02263   }
02264 }
02265 
02266 /// ParseMetadataAttachment - Parse metadata attachments.
02267 std::error_code BitcodeReader::ParseMetadataAttachment() {
02268   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
02269     return Error(BitcodeError::InvalidRecord);
02270 
02271   SmallVector<uint64_t, 64> Record;
02272   while (1) {
02273     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
02274 
02275     switch (Entry.Kind) {
02276     case BitstreamEntry::SubBlock: // Handled for us already.
02277     case BitstreamEntry::Error:
02278       return Error(BitcodeError::MalformedBlock);
02279     case BitstreamEntry::EndBlock:
02280       return std::error_code();
02281     case BitstreamEntry::Record:
02282       // The interesting case.
02283       break;
02284     }
02285 
02286     // Read a metadata attachment record.
02287     Record.clear();
02288     switch (Stream.readRecord(Entry.ID, Record)) {
02289     default:  // Default behavior: ignore.
02290       break;
02291     case bitc::METADATA_ATTACHMENT: {
02292       unsigned RecordLength = Record.size();
02293       if (Record.empty() || (RecordLength - 1) % 2 == 1)
02294         return Error(BitcodeError::InvalidRecord);
02295       Instruction *Inst = InstructionList[Record[0]];
02296       for (unsigned i = 1; i != RecordLength; i = i+2) {
02297         unsigned Kind = Record[i];
02298         DenseMap<unsigned, unsigned>::iterator I =
02299           MDKindMap.find(Kind);
02300         if (I == MDKindMap.end())
02301           return Error(BitcodeError::InvalidID);
02302         Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
02303         Inst->setMetadata(I->second, cast<MDNode>(Node));
02304         if (I->second == LLVMContext::MD_tbaa)
02305           InstsWithTBAATag.push_back(Inst);
02306       }
02307       break;
02308     }
02309     }
02310   }
02311 }
02312 
02313 /// ParseFunctionBody - Lazily parse the specified function body block.
02314 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
02315   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
02316     return Error(BitcodeError::InvalidRecord);
02317 
02318   InstructionList.clear();
02319   unsigned ModuleValueListSize = ValueList.size();
02320   unsigned ModuleMDValueListSize = MDValueList.size();
02321 
02322   // Add all the function arguments to the value table.
02323   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
02324     ValueList.push_back(I);
02325 
02326   unsigned NextValueNo = ValueList.size();
02327   BasicBlock *CurBB = nullptr;
02328   unsigned CurBBNo = 0;
02329 
02330   DebugLoc LastLoc;
02331 
02332   // Read all the records.
02333   SmallVector<uint64_t, 64> Record;
02334   while (1) {
02335     BitstreamEntry Entry = Stream.advance();
02336 
02337     switch (Entry.Kind) {
02338     case BitstreamEntry::Error:
02339       return Error(BitcodeError::MalformedBlock);
02340     case BitstreamEntry::EndBlock:
02341       goto OutOfRecordLoop;
02342 
02343     case BitstreamEntry::SubBlock:
02344       switch (Entry.ID) {
02345       default:  // Skip unknown content.
02346         if (Stream.SkipBlock())
02347           return Error(BitcodeError::InvalidRecord);
02348         break;
02349       case bitc::CONSTANTS_BLOCK_ID:
02350         if (std::error_code EC = ParseConstants())
02351           return EC;
02352         NextValueNo = ValueList.size();
02353         break;
02354       case bitc::VALUE_SYMTAB_BLOCK_ID:
02355         if (std::error_code EC = ParseValueSymbolTable())
02356           return EC;
02357         break;
02358       case bitc::METADATA_ATTACHMENT_ID:
02359         if (std::error_code EC = ParseMetadataAttachment())
02360           return EC;
02361         break;
02362       case bitc::METADATA_BLOCK_ID:
02363         if (std::error_code EC = ParseMetadata())
02364           return EC;
02365         break;
02366       case bitc::USELIST_BLOCK_ID:
02367         if (std::error_code EC = ParseUseLists())
02368           return EC;
02369         break;
02370       }
02371       continue;
02372 
02373     case BitstreamEntry::Record:
02374       // The interesting case.
02375       break;
02376     }
02377 
02378     // Read a record.
02379     Record.clear();
02380     Instruction *I = nullptr;
02381     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
02382     switch (BitCode) {
02383     default: // Default behavior: reject
02384       return Error(BitcodeError::InvalidValue);
02385     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
02386       if (Record.size() < 1 || Record[0] == 0)
02387         return Error(BitcodeError::InvalidRecord);
02388       // Create all the basic blocks for the function.
02389       FunctionBBs.resize(Record[0]);
02390 
02391       // See if anything took the address of blocks in this function.
02392       auto BBFRI = BasicBlockFwdRefs.find(F);
02393       if (BBFRI == BasicBlockFwdRefs.end()) {
02394         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
02395           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
02396       } else {
02397         auto &BBRefs = BBFRI->second;
02398         // Check for invalid basic block references.
02399         if (BBRefs.size() > FunctionBBs.size())
02400           return Error(BitcodeError::InvalidID);
02401         assert(!BBRefs.empty() && "Unexpected empty array");
02402         assert(!BBRefs.front() && "Invalid reference to entry block");
02403         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
02404              ++I)
02405           if (I < RE && BBRefs[I]) {
02406             BBRefs[I]->insertInto(F);
02407             FunctionBBs[I] = BBRefs[I];
02408           } else {
02409             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
02410           }
02411 
02412         // Erase from the table.
02413         BasicBlockFwdRefs.erase(BBFRI);
02414       }
02415 
02416       CurBB = FunctionBBs[0];
02417       continue;
02418     }
02419 
02420     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
02421       // This record indicates that the last instruction is at the same
02422       // location as the previous instruction with a location.
02423       I = nullptr;
02424 
02425       // Get the last instruction emitted.
02426       if (CurBB && !CurBB->empty())
02427         I = &CurBB->back();
02428       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
02429                !FunctionBBs[CurBBNo-1]->empty())
02430         I = &FunctionBBs[CurBBNo-1]->back();
02431 
02432       if (!I)
02433         return Error(BitcodeError::InvalidRecord);
02434       I->setDebugLoc(LastLoc);
02435       I = nullptr;
02436       continue;
02437 
02438     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
02439       I = nullptr;     // Get the last instruction emitted.
02440       if (CurBB && !CurBB->empty())
02441         I = &CurBB->back();
02442       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
02443                !FunctionBBs[CurBBNo-1]->empty())
02444         I = &FunctionBBs[CurBBNo-1]->back();
02445       if (!I || Record.size() < 4)
02446         return Error(BitcodeError::InvalidRecord);
02447 
02448       unsigned Line = Record[0], Col = Record[1];
02449       unsigned ScopeID = Record[2], IAID = Record[3];
02450 
02451       MDNode *Scope = nullptr, *IA = nullptr;
02452       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
02453       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
02454       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
02455       I->setDebugLoc(LastLoc);
02456       I = nullptr;
02457       continue;
02458     }
02459 
02460     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
02461       unsigned OpNum = 0;
02462       Value *LHS, *RHS;
02463       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
02464           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
02465           OpNum+1 > Record.size())
02466         return Error(BitcodeError::InvalidRecord);
02467 
02468       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
02469       if (Opc == -1)
02470         return Error(BitcodeError::InvalidRecord);
02471       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
02472       InstructionList.push_back(I);
02473       if (OpNum < Record.size()) {
02474         if (Opc == Instruction::Add ||
02475             Opc == Instruction::Sub ||
02476             Opc == Instruction::Mul ||
02477             Opc == Instruction::Shl) {
02478           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
02479             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
02480           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
02481             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
02482         } else if (Opc == Instruction::SDiv ||
02483                    Opc == Instruction::UDiv ||
02484                    Opc == Instruction::LShr ||
02485                    Opc == Instruction::AShr) {
02486           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
02487             cast<BinaryOperator>(I)->setIsExact(true);
02488         } else if (isa<FPMathOperator>(I)) {
02489           FastMathFlags FMF;
02490           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
02491             FMF.setUnsafeAlgebra();
02492           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
02493             FMF.setNoNaNs();
02494           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
02495             FMF.setNoInfs();
02496           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
02497             FMF.setNoSignedZeros();
02498           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
02499             FMF.setAllowReciprocal();
02500           if (FMF.any())
02501             I->setFastMathFlags(FMF);
02502         }
02503 
02504       }
02505       break;
02506     }
02507     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
02508       unsigned OpNum = 0;
02509       Value *Op;
02510       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
02511           OpNum+2 != Record.size())
02512         return Error(BitcodeError::InvalidRecord);
02513 
02514       Type *ResTy = getTypeByID(Record[OpNum]);
02515       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
02516       if (Opc == -1 || !ResTy)
02517         return Error(BitcodeError::InvalidRecord);
02518       Instruction *Temp = nullptr;
02519       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
02520         if (Temp) {
02521           InstructionList.push_back(Temp);
02522           CurBB->getInstList().push_back(Temp);
02523         }
02524       } else {
02525         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
02526       }
02527       InstructionList.push_back(I);
02528       break;
02529     }
02530     case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
02531     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
02532       unsigned OpNum = 0;
02533       Value *BasePtr;
02534       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
02535         return Error(BitcodeError::InvalidRecord);
02536 
02537       SmallVector<Value*, 16> GEPIdx;
02538       while (OpNum != Record.size()) {
02539         Value *Op;
02540         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
02541           return Error(BitcodeError::InvalidRecord);
02542         GEPIdx.push_back(Op);
02543       }
02544 
02545       I = GetElementPtrInst::Create(BasePtr, GEPIdx);
02546       InstructionList.push_back(I);
02547       if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
02548         cast<GetElementPtrInst>(I)->setIsInBounds(true);
02549       break;
02550     }
02551 
02552     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
02553                                        // EXTRACTVAL: [opty, opval, n x indices]
02554       unsigned OpNum = 0;
02555       Value *Agg;
02556       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
02557         return Error(BitcodeError::InvalidRecord);
02558 
02559       SmallVector<unsigned, 4> EXTRACTVALIdx;
02560       for (unsigned RecSize = Record.size();
02561            OpNum != RecSize; ++OpNum) {
02562         uint64_t Index = Record[OpNum];
02563         if ((unsigned)Index != Index)
02564           return Error(BitcodeError::InvalidValue);
02565         EXTRACTVALIdx.push_back((unsigned)Index);
02566       }
02567 
02568       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
02569       InstructionList.push_back(I);
02570       break;
02571     }
02572 
02573     case bitc::FUNC_CODE_INST_INSERTVAL: {
02574                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
02575       unsigned OpNum = 0;
02576       Value *Agg;
02577       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
02578         return Error(BitcodeError::InvalidRecord);
02579       Value *Val;
02580       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
02581         return Error(BitcodeError::InvalidRecord);
02582 
02583       SmallVector<unsigned, 4> INSERTVALIdx;
02584       for (unsigned RecSize = Record.size();
02585            OpNum != RecSize; ++OpNum) {
02586         uint64_t Index = Record[OpNum];
02587         if ((unsigned)Index != Index)
02588           return Error(BitcodeError::InvalidValue);
02589         INSERTVALIdx.push_back((unsigned)Index);
02590       }
02591 
02592       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
02593       InstructionList.push_back(I);
02594       break;
02595     }
02596 
02597     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
02598       // obsolete form of select
02599       // handles select i1 ... in old bitcode
02600       unsigned OpNum = 0;
02601       Value *TrueVal, *FalseVal, *Cond;
02602       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
02603           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
02604           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
02605         return Error(BitcodeError::InvalidRecord);
02606 
02607       I = SelectInst::Create(Cond, TrueVal, FalseVal);
02608       InstructionList.push_back(I);
02609       break;
02610     }
02611 
02612     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
02613       // new form of select
02614       // handles select i1 or select [N x i1]
02615       unsigned OpNum = 0;
02616       Value *TrueVal, *FalseVal, *Cond;
02617       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
02618           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
02619           getValueTypePair(Record, OpNum, NextValueNo, Cond))
02620         return Error(BitcodeError::InvalidRecord);
02621 
02622       // select condition can be either i1 or [N x i1]
02623       if (VectorType* vector_type =
02624           dyn_cast<VectorType>(Cond->getType())) {
02625         // expect <n x i1>
02626         if (vector_type->getElementType() != Type::getInt1Ty(Context))
02627           return Error(BitcodeError::InvalidTypeForValue);
02628       } else {
02629         // expect i1
02630         if (Cond->getType() != Type::getInt1Ty(Context))
02631           return Error(BitcodeError::InvalidTypeForValue);
02632       }
02633 
02634       I = SelectInst::Create(Cond, TrueVal, FalseVal);
02635       InstructionList.push_back(I);
02636       break;
02637     }
02638 
02639     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
02640       unsigned OpNum = 0;
02641       Value *Vec, *Idx;
02642       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
02643           getValueTypePair(Record, OpNum, NextValueNo, Idx))
02644         return Error(BitcodeError::InvalidRecord);
02645       I = ExtractElementInst::Create(Vec, Idx);
02646       InstructionList.push_back(I);
02647       break;
02648     }
02649 
02650     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
02651       unsigned OpNum = 0;
02652       Value *Vec, *Elt, *Idx;
02653       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
02654           popValue(Record, OpNum, NextValueNo,
02655                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
02656           getValueTypePair(Record, OpNum, NextValueNo, Idx))
02657         return Error(BitcodeError::InvalidRecord);
02658       I = InsertElementInst::Create(Vec, Elt, Idx);
02659       InstructionList.push_back(I);
02660       break;
02661     }
02662 
02663     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
02664       unsigned OpNum = 0;
02665       Value *Vec1, *Vec2, *Mask;
02666       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
02667           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
02668         return Error(BitcodeError::InvalidRecord);
02669 
02670       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
02671         return Error(BitcodeError::InvalidRecord);
02672       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
02673       InstructionList.push_back(I);
02674       break;
02675     }
02676 
02677     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
02678       // Old form of ICmp/FCmp returning bool
02679       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
02680       // both legal on vectors but had different behaviour.
02681     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
02682       // FCmp/ICmp returning bool or vector of bool
02683 
02684       unsigned OpNum = 0;
02685       Value *LHS, *RHS;
02686       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
02687           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
02688           OpNum+1 != Record.size())
02689         return Error(BitcodeError::InvalidRecord);
02690 
02691       if (LHS->getType()->isFPOrFPVectorTy())
02692         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
02693       else
02694         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
02695       InstructionList.push_back(I);
02696       break;
02697     }
02698 
02699     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
02700       {
02701         unsigned Size = Record.size();
02702         if (Size == 0) {
02703           I = ReturnInst::Create(Context);
02704           InstructionList.push_back(I);
02705           break;
02706         }
02707 
02708         unsigned OpNum = 0;
02709         Value *Op = nullptr;
02710         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
02711           return Error(BitcodeError::InvalidRecord);
02712         if (OpNum != Record.size())
02713           return Error(BitcodeError::InvalidRecord);
02714 
02715         I = ReturnInst::Create(Context, Op);
02716         InstructionList.push_back(I);
02717         break;
02718       }
02719     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
02720       if (Record.size() != 1 && Record.size() != 3)
02721         return Error(BitcodeError::InvalidRecord);
02722       BasicBlock *TrueDest = getBasicBlock(Record[0]);
02723       if (!TrueDest)
02724         return Error(BitcodeError::InvalidRecord);
02725 
02726       if (Record.size() == 1) {
02727         I = BranchInst::Create(TrueDest);
02728         InstructionList.push_back(I);
02729       }
02730       else {
02731         BasicBlock *FalseDest = getBasicBlock(Record[1]);
02732         Value *Cond = getValue(Record, 2, NextValueNo,
02733                                Type::getInt1Ty(Context));
02734         if (!FalseDest || !Cond)
02735           return Error(BitcodeError::InvalidRecord);
02736         I = BranchInst::Create(TrueDest, FalseDest, Cond);
02737         InstructionList.push_back(I);
02738       }
02739       break;
02740     }
02741     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
02742       // Check magic
02743       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
02744         // "New" SwitchInst format with case ranges. The changes to write this
02745         // format were reverted but we still recognize bitcode that uses it.
02746         // Hopefully someday we will have support for case ranges and can use
02747         // this format again.
02748 
02749         Type *OpTy = getTypeByID(Record[1]);
02750         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
02751 
02752         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
02753         BasicBlock *Default = getBasicBlock(Record[3]);
02754         if (!OpTy || !Cond || !Default)
02755           return Error(BitcodeError::InvalidRecord);
02756 
02757         unsigned NumCases = Record[4];
02758 
02759         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
02760         InstructionList.push_back(SI);
02761 
02762         unsigned CurIdx = 5;
02763         for (unsigned i = 0; i != NumCases; ++i) {
02764           SmallVector<ConstantInt*, 1> CaseVals;
02765           unsigned NumItems = Record[CurIdx++];
02766           for (unsigned ci = 0; ci != NumItems; ++ci) {
02767             bool isSingleNumber = Record[CurIdx++];
02768 
02769             APInt Low;
02770             unsigned ActiveWords = 1;
02771             if (ValueBitWidth > 64)
02772               ActiveWords = Record[CurIdx++];
02773             Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
02774                                 ValueBitWidth);
02775             CurIdx += ActiveWords;
02776 
02777             if (!isSingleNumber) {
02778               ActiveWords = 1;
02779               if (ValueBitWidth > 64)
02780                 ActiveWords = Record[CurIdx++];
02781               APInt High =
02782                   ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
02783                                 ValueBitWidth);
02784               CurIdx += ActiveWords;
02785 
02786               // FIXME: It is not clear whether values in the range should be
02787               // compared as signed or unsigned values. The partially
02788               // implemented changes that used this format in the past used
02789               // unsigned comparisons.
02790               for ( ; Low.ule(High); ++Low)
02791                 CaseVals.push_back(ConstantInt::get(Context, Low));
02792             } else
02793               CaseVals.push_back(ConstantInt::get(Context, Low));
02794           }
02795           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
02796           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
02797                  cve = CaseVals.end(); cvi != cve; ++cvi)
02798             SI->addCase(*cvi, DestBB);
02799         }
02800         I = SI;
02801         break;
02802       }
02803 
02804       // Old SwitchInst format without case ranges.
02805 
02806       if (Record.size() < 3 || (Record.size() & 1) == 0)
02807         return Error(BitcodeError::InvalidRecord);
02808       Type *OpTy = getTypeByID(Record[0]);
02809       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
02810       BasicBlock *Default = getBasicBlock(Record[2]);
02811       if (!OpTy || !Cond || !Default)
02812         return Error(BitcodeError::InvalidRecord);
02813       unsigned NumCases = (Record.size()-3)/2;
02814       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
02815       InstructionList.push_back(SI);
02816       for (unsigned i = 0, e = NumCases; i != e; ++i) {
02817         ConstantInt *CaseVal =
02818           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
02819         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
02820         if (!CaseVal || !DestBB) {
02821           delete SI;
02822           return Error(BitcodeError::InvalidRecord);
02823         }
02824         SI->addCase(CaseVal, DestBB);
02825       }
02826       I = SI;
02827       break;
02828     }
02829     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
02830       if (Record.size() < 2)
02831         return Error(BitcodeError::InvalidRecord);
02832       Type *OpTy = getTypeByID(Record[0]);
02833       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
02834       if (!OpTy || !Address)
02835         return Error(BitcodeError::InvalidRecord);
02836       unsigned NumDests = Record.size()-2;
02837       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
02838       InstructionList.push_back(IBI);
02839       for (unsigned i = 0, e = NumDests; i != e; ++i) {
02840         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
02841           IBI->addDestination(DestBB);
02842         } else {
02843           delete IBI;
02844           return Error(BitcodeError::InvalidRecord);
02845         }
02846       }
02847       I = IBI;
02848       break;
02849     }
02850 
02851     case bitc::FUNC_CODE_INST_INVOKE: {
02852       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
02853       if (Record.size() < 4)
02854         return Error(BitcodeError::InvalidRecord);
02855       AttributeSet PAL = getAttributes(Record[0]);
02856       unsigned CCInfo = Record[1];
02857       BasicBlock *NormalBB = getBasicBlock(Record[2]);
02858       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
02859 
02860       unsigned OpNum = 4;
02861       Value *Callee;
02862       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
02863         return Error(BitcodeError::InvalidRecord);
02864 
02865       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
02866       FunctionType *FTy = !CalleeTy ? nullptr :
02867         dyn_cast<FunctionType>(CalleeTy->getElementType());
02868 
02869       // Check that the right number of fixed parameters are here.
02870       if (!FTy || !NormalBB || !UnwindBB ||
02871           Record.size() < OpNum+FTy->getNumParams())
02872         return Error(BitcodeError::InvalidRecord);
02873 
02874       SmallVector<Value*, 16> Ops;
02875       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
02876         Ops.push_back(getValue(Record, OpNum, NextValueNo,
02877                                FTy->getParamType(i)));
02878         if (!Ops.back())
02879           return Error(BitcodeError::InvalidRecord);
02880       }
02881 
02882       if (!FTy->isVarArg()) {
02883         if (Record.size() != OpNum)
02884           return Error(BitcodeError::InvalidRecord);
02885       } else {
02886         // Read type/value pairs for varargs params.
02887         while (OpNum != Record.size()) {
02888           Value *Op;
02889           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
02890             return Error(BitcodeError::InvalidRecord);
02891           Ops.push_back(Op);
02892         }
02893       }
02894 
02895       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
02896       InstructionList.push_back(I);
02897       cast<InvokeInst>(I)->setCallingConv(
02898         static_cast<CallingConv::ID>(CCInfo));
02899       cast<InvokeInst>(I)->setAttributes(PAL);
02900       break;
02901     }
02902     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
02903       unsigned Idx = 0;
02904       Value *Val = nullptr;
02905       if (getValueTypePair(Record, Idx, NextValueNo, Val))
02906         return Error(BitcodeError::InvalidRecord);
02907       I = ResumeInst::Create(Val);
02908       InstructionList.push_back(I);
02909       break;
02910     }
02911     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
02912       I = new UnreachableInst(Context);
02913       InstructionList.push_back(I);
02914       break;
02915     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
02916       if (Record.size() < 1 || ((Record.size()-1)&1))
02917         return Error(BitcodeError::InvalidRecord);
02918       Type *Ty = getTypeByID(Record[0]);
02919       if (!Ty)
02920         return Error(BitcodeError::InvalidRecord);
02921 
02922       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
02923       InstructionList.push_back(PN);
02924 
02925       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
02926         Value *V;
02927         // With the new function encoding, it is possible that operands have
02928         // negative IDs (for forward references).  Use a signed VBR
02929         // representation to keep the encoding small.
02930         if (UseRelativeIDs)
02931           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
02932         else
02933           V = getValue(Record, 1+i, NextValueNo, Ty);
02934         BasicBlock *BB = getBasicBlock(Record[2+i]);
02935         if (!V || !BB)
02936           return Error(BitcodeError::InvalidRecord);
02937         PN->addIncoming(V, BB);
02938       }
02939       I = PN;
02940       break;
02941     }
02942 
02943     case bitc::FUNC_CODE_INST_LANDINGPAD: {
02944       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
02945       unsigned Idx = 0;
02946       if (Record.size() < 4)
02947         return Error(BitcodeError::InvalidRecord);
02948       Type *Ty = getTypeByID(Record[Idx++]);
02949       if (!Ty)
02950         return Error(BitcodeError::InvalidRecord);
02951       Value *PersFn = nullptr;
02952       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
02953         return Error(BitcodeError::InvalidRecord);
02954 
02955       bool IsCleanup = !!Record[Idx++];
02956       unsigned NumClauses = Record[Idx++];
02957       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
02958       LP->setCleanup(IsCleanup);
02959       for (unsigned J = 0; J != NumClauses; ++J) {
02960         LandingPadInst::ClauseType CT =
02961           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
02962         Value *Val;
02963 
02964         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
02965           delete LP;
02966           return Error(BitcodeError::InvalidRecord);
02967         }
02968 
02969         assert((CT != LandingPadInst::Catch ||
02970                 !isa<ArrayType>(Val->getType())) &&
02971                "Catch clause has a invalid type!");
02972         assert((CT != LandingPadInst::Filter ||
02973                 isa<ArrayType>(Val->getType())) &&
02974                "Filter clause has invalid type!");
02975         LP->addClause(cast<Constant>(Val));
02976       }
02977 
02978       I = LP;
02979       InstructionList.push_back(I);
02980       break;
02981     }
02982 
02983     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
02984       if (Record.size() != 4)
02985         return Error(BitcodeError::InvalidRecord);
02986       PointerType *Ty =
02987         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
02988       Type *OpTy = getTypeByID(Record[1]);
02989       Value *Size = getFnValueByID(Record[2], OpTy);
02990       unsigned AlignRecord = Record[3];
02991       bool InAlloca = AlignRecord & (1 << 5);
02992       unsigned Align = AlignRecord & ((1 << 5) - 1);
02993       if (!Ty || !Size)
02994         return Error(BitcodeError::InvalidRecord);
02995       AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
02996       AI->setUsedWithInAlloca(InAlloca);
02997       I = AI;
02998       InstructionList.push_back(I);
02999       break;
03000     }
03001     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
03002       unsigned OpNum = 0;
03003       Value *Op;
03004       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
03005           OpNum+2 != Record.size())
03006         return Error(BitcodeError::InvalidRecord);
03007 
03008       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
03009       InstructionList.push_back(I);
03010       break;
03011     }
03012     case bitc::FUNC_CODE_INST_LOADATOMIC: {
03013        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
03014       unsigned OpNum = 0;
03015       Value *Op;
03016       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
03017           OpNum+4 != Record.size())
03018         return Error(BitcodeError::InvalidRecord);
03019 
03020       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
03021       if (Ordering == NotAtomic || Ordering == Release ||
03022           Ordering == AcquireRelease)
03023         return Error(BitcodeError::InvalidRecord);
03024       if (Ordering != NotAtomic && Record[OpNum] == 0)
03025         return Error(BitcodeError::InvalidRecord);
03026       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
03027 
03028       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
03029                        Ordering, SynchScope);
03030       InstructionList.push_back(I);
03031       break;
03032     }
03033     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
03034       unsigned OpNum = 0;
03035       Value *Val, *Ptr;
03036       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03037           popValue(Record, OpNum, NextValueNo,
03038                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
03039           OpNum+2 != Record.size())
03040         return Error(BitcodeError::InvalidRecord);
03041 
03042       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
03043       InstructionList.push_back(I);
03044       break;
03045     }
03046     case bitc::FUNC_CODE_INST_STOREATOMIC: {
03047       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
03048       unsigned OpNum = 0;
03049       Value *Val, *Ptr;
03050       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03051           popValue(Record, OpNum, NextValueNo,
03052                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
03053           OpNum+4 != Record.size())
03054         return Error(BitcodeError::InvalidRecord);
03055 
03056       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
03057       if (Ordering == NotAtomic || Ordering == Acquire ||
03058           Ordering == AcquireRelease)
03059         return Error(BitcodeError::InvalidRecord);
03060       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
03061       if (Ordering != NotAtomic && Record[OpNum] == 0)
03062         return Error(BitcodeError::InvalidRecord);
03063 
03064       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
03065                         Ordering, SynchScope);
03066       InstructionList.push_back(I);
03067       break;
03068     }
03069     case bitc::FUNC_CODE_INST_CMPXCHG: {
03070       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
03071       //          failureordering?, isweak?]
03072       unsigned OpNum = 0;
03073       Value *Ptr, *Cmp, *New;
03074       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03075           popValue(Record, OpNum, NextValueNo,
03076                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
03077           popValue(Record, OpNum, NextValueNo,
03078                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
03079           (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
03080         return Error(BitcodeError::InvalidRecord);
03081       AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
03082       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
03083         return Error(BitcodeError::InvalidRecord);
03084       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
03085 
03086       AtomicOrdering FailureOrdering;
03087       if (Record.size() < 7)
03088         FailureOrdering =
03089             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
03090       else
03091         FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
03092 
03093       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
03094                                 SynchScope);
03095       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
03096 
03097       if (Record.size() < 8) {
03098         // Before weak cmpxchgs existed, the instruction simply returned the
03099         // value loaded from memory, so bitcode files from that era will be
03100         // expecting the first component of a modern cmpxchg.
03101         CurBB->getInstList().push_back(I);
03102         I = ExtractValueInst::Create(I, 0);
03103       } else {
03104         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
03105       }
03106 
03107       InstructionList.push_back(I);
03108       break;
03109     }
03110     case bitc::FUNC_CODE_INST_ATOMICRMW: {
03111       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
03112       unsigned OpNum = 0;
03113       Value *Ptr, *Val;
03114       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03115           popValue(Record, OpNum, NextValueNo,
03116                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
03117           OpNum+4 != Record.size())
03118         return Error(BitcodeError::InvalidRecord);
03119       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
03120       if (Operation < AtomicRMWInst::FIRST_BINOP ||
03121           Operation > AtomicRMWInst::LAST_BINOP)
03122         return Error(BitcodeError::InvalidRecord);
03123       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
03124       if (Ordering == NotAtomic || Ordering == Unordered)
03125         return Error(BitcodeError::InvalidRecord);
03126       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
03127       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
03128       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
03129       InstructionList.push_back(I);
03130       break;
03131     }
03132     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
03133       if (2 != Record.size())
03134         return Error(BitcodeError::InvalidRecord);
03135       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
03136       if (Ordering == NotAtomic || Ordering == Unordered ||
03137           Ordering == Monotonic)
03138         return Error(BitcodeError::InvalidRecord);
03139       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
03140       I = new FenceInst(Context, Ordering, SynchScope);
03141       InstructionList.push_back(I);
03142       break;
03143     }
03144     case bitc::FUNC_CODE_INST_CALL: {
03145       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
03146       if (Record.size() < 3)
03147         return Error(BitcodeError::InvalidRecord);
03148 
03149       AttributeSet PAL = getAttributes(Record[0]);
03150       unsigned CCInfo = Record[1];
03151 
03152       unsigned OpNum = 2;
03153       Value *Callee;
03154       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
03155         return Error(BitcodeError::InvalidRecord);
03156 
03157       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
03158       FunctionType *FTy = nullptr;
03159       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
03160       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
03161         return Error(BitcodeError::InvalidRecord);
03162 
03163       SmallVector<Value*, 16> Args;
03164       // Read the fixed params.
03165       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
03166         if (FTy->getParamType(i)->isLabelTy())
03167           Args.push_back(getBasicBlock(Record[OpNum]));
03168         else
03169           Args.push_back(getValue(Record, OpNum, NextValueNo,
03170                                   FTy->getParamType(i)));
03171         if (!Args.back())
03172           return Error(BitcodeError::InvalidRecord);
03173       }
03174 
03175       // Read type/value pairs for varargs params.
03176       if (!FTy->isVarArg()) {
03177         if (OpNum != Record.size())
03178           return Error(BitcodeError::InvalidRecord);
03179       } else {
03180         while (OpNum != Record.size()) {
03181           Value *Op;
03182           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
03183             return Error(BitcodeError::InvalidRecord);
03184           Args.push_back(Op);
03185         }
03186       }
03187 
03188       I = CallInst::Create(Callee, Args);
03189       InstructionList.push_back(I);
03190       cast<CallInst>(I)->setCallingConv(
03191           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
03192       CallInst::TailCallKind TCK = CallInst::TCK_None;
03193       if (CCInfo & 1)
03194         TCK = CallInst::TCK_Tail;
03195       if (CCInfo & (1 << 14))
03196         TCK = CallInst::TCK_MustTail;
03197       cast<CallInst>(I)->setTailCallKind(TCK);
03198       cast<CallInst>(I)->setAttributes(PAL);
03199       break;
03200     }
03201     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
03202       if (Record.size() < 3)
03203         return Error(BitcodeError::InvalidRecord);
03204       Type *OpTy = getTypeByID(Record[0]);
03205       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
03206       Type *ResTy = getTypeByID(Record[2]);
03207       if (!OpTy || !Op || !ResTy)
03208         return Error(BitcodeError::InvalidRecord);
03209       I = new VAArgInst(Op, ResTy);
03210       InstructionList.push_back(I);
03211       break;
03212     }
03213     }
03214 
03215     // Add instruction to end of current BB.  If there is no current BB, reject
03216     // this file.
03217     if (!CurBB) {
03218       delete I;
03219       return Error(BitcodeError::InvalidInstructionWithNoBB);
03220     }
03221     CurBB->getInstList().push_back(I);
03222 
03223     // If this was a terminator instruction, move to the next block.
03224     if (isa<TerminatorInst>(I)) {
03225       ++CurBBNo;
03226       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
03227     }
03228 
03229     // Non-void values get registered in the value table for future use.
03230     if (I && !I->getType()->isVoidTy())
03231       ValueList.AssignValue(I, NextValueNo++);
03232   }
03233 
03234 OutOfRecordLoop:
03235 
03236   // Check the function list for unresolved values.
03237   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
03238     if (!A->getParent()) {
03239       // We found at least one unresolved value.  Nuke them all to avoid leaks.
03240       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
03241         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
03242           A->replaceAllUsesWith(UndefValue::get(A->getType()));
03243           delete A;
03244         }
03245       }
03246       return Error(BitcodeError::NeverResolvedValueFoundInFunction);
03247     }
03248   }
03249 
03250   // FIXME: Check for unresolved forward-declared metadata references
03251   // and clean up leaks.
03252 
03253   // Trim the value list down to the size it was before we parsed this function.
03254   ValueList.shrinkTo(ModuleValueListSize);
03255   MDValueList.shrinkTo(ModuleMDValueListSize);
03256   std::vector<BasicBlock*>().swap(FunctionBBs);
03257   return std::error_code();
03258 }
03259 
03260 /// Find the function body in the bitcode stream
03261 std::error_code BitcodeReader::FindFunctionInStream(
03262     Function *F,
03263     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
03264   while (DeferredFunctionInfoIterator->second == 0) {
03265     if (Stream.AtEndOfStream())
03266       return Error(BitcodeError::CouldNotFindFunctionInStream);
03267     // ParseModule will parse the next body in the stream and set its
03268     // position in the DeferredFunctionInfo map.
03269     if (std::error_code EC = ParseModule(true))
03270       return EC;
03271   }
03272   return std::error_code();
03273 }
03274 
03275 //===----------------------------------------------------------------------===//
03276 // GVMaterializer implementation
03277 //===----------------------------------------------------------------------===//
03278 
03279 void BitcodeReader::releaseBuffer() { Buffer.release(); }
03280 
03281 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
03282   if (const Function *F = dyn_cast<Function>(GV)) {
03283     return F->isDeclaration() &&
03284       DeferredFunctionInfo.count(const_cast<Function*>(F));
03285   }
03286   return false;
03287 }
03288 
03289 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
03290   Function *F = dyn_cast<Function>(GV);
03291   // If it's not a function or is already material, ignore the request.
03292   if (!F || !F->isMaterializable())
03293     return std::error_code();
03294 
03295   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
03296   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
03297   // If its position is recorded as 0, its body is somewhere in the stream
03298   // but we haven't seen it yet.
03299   if (DFII->second == 0 && LazyStreamer)
03300     if (std::error_code EC = FindFunctionInStream(F, DFII))
03301       return EC;
03302 
03303   // Move the bit stream to the saved position of the deferred function body.
03304   Stream.JumpToBit(DFII->second);
03305 
03306   if (std::error_code EC = ParseFunctionBody(F))
03307     return EC;
03308 
03309   // Upgrade any old intrinsic calls in the function.
03310   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
03311        E = UpgradedIntrinsics.end(); I != E; ++I) {
03312     if (I->first != I->second) {
03313       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
03314            UI != UE;) {
03315         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
03316           UpgradeIntrinsicCall(CI, I->second);
03317       }
03318     }
03319   }
03320 
03321   // Bring in any functions that this function forward-referenced via
03322   // blockaddresses.
03323   return materializeForwardReferencedFunctions();
03324 }
03325 
03326 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
03327   const Function *F = dyn_cast<Function>(GV);
03328   if (!F || F->isDeclaration())
03329     return false;
03330 
03331   // Dematerializing F would leave dangling references that wouldn't be
03332   // reconnected on re-materialization.
03333   if (BlockAddressesTaken.count(F))
03334     return false;
03335 
03336   return DeferredFunctionInfo.count(const_cast<Function*>(F));
03337 }
03338 
03339 void BitcodeReader::Dematerialize(GlobalValue *GV) {
03340   Function *F = dyn_cast<Function>(GV);
03341   // If this function isn't dematerializable, this is a noop.
03342   if (!F || !isDematerializable(F))
03343     return;
03344 
03345   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
03346 
03347   // Just forget the function body, we can remat it later.
03348   F->deleteBody();
03349 }
03350 
03351 std::error_code BitcodeReader::MaterializeModule(Module *M) {
03352   assert(M == TheModule &&
03353          "Can only Materialize the Module this BitcodeReader is attached to.");
03354 
03355   // Promise to materialize all forward references.
03356   WillMaterializeAllForwardRefs = true;
03357 
03358   // Iterate over the module, deserializing any functions that are still on
03359   // disk.
03360   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
03361        F != E; ++F) {
03362     if (F->isMaterializable()) {
03363       if (std::error_code EC = Materialize(F))
03364         return EC;
03365     }
03366   }
03367   // At this point, if there are any function bodies, the current bit is
03368   // pointing to the END_BLOCK record after them. Now make sure the rest
03369   // of the bits in the module have been read.
03370   if (NextUnreadBit)
03371     ParseModule(true);
03372 
03373   // Check that all block address forward references got resolved (as we
03374   // promised above).
03375   if (!BasicBlockFwdRefs.empty())
03376     return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
03377 
03378   // Upgrade any intrinsic calls that slipped through (should not happen!) and
03379   // delete the old functions to clean up. We can't do this unless the entire
03380   // module is materialized because there could always be another function body
03381   // with calls to the old function.
03382   for (std::vector<std::pair<Function*, Function*> >::iterator I =
03383        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
03384     if (I->first != I->second) {
03385       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
03386            UI != UE;) {
03387         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
03388           UpgradeIntrinsicCall(CI, I->second);
03389       }
03390       if (!I->first->use_empty())
03391         I->first->replaceAllUsesWith(I->second);
03392       I->first->eraseFromParent();
03393     }
03394   }
03395   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
03396 
03397   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
03398     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
03399 
03400   UpgradeDebugInfo(*M);
03401   return std::error_code();
03402 }
03403 
03404 std::error_code BitcodeReader::InitStream() {
03405   if (LazyStreamer)
03406     return InitLazyStream();
03407   return InitStreamFromBuffer();
03408 }
03409 
03410 std::error_code BitcodeReader::InitStreamFromBuffer() {
03411   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
03412   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
03413 
03414   if (Buffer->getBufferSize() & 3)
03415     return Error(BitcodeError::InvalidBitcodeSignature);
03416 
03417   // If we have a wrapper header, parse it and ignore the non-bc file contents.
03418   // The magic number is 0x0B17C0DE stored in little endian.
03419   if (isBitcodeWrapper(BufPtr, BufEnd))
03420     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
03421       return Error(BitcodeError::InvalidBitcodeWrapperHeader);
03422 
03423   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
03424   Stream.init(*StreamFile);
03425 
03426   return std::error_code();
03427 }
03428 
03429 std::error_code BitcodeReader::InitLazyStream() {
03430   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
03431   // see it.
03432   StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
03433   StreamFile.reset(new BitstreamReader(Bytes));
03434   Stream.init(*StreamFile);
03435 
03436   unsigned char buf[16];
03437   if (Bytes->readBytes(0, 16, buf) == -1)
03438     return Error(BitcodeError::InvalidBitcodeSignature);
03439 
03440   if (!isBitcode(buf, buf + 16))
03441     return Error(BitcodeError::InvalidBitcodeSignature);
03442 
03443   if (isBitcodeWrapper(buf, buf + 4)) {
03444     const unsigned char *bitcodeStart = buf;
03445     const unsigned char *bitcodeEnd = buf + 16;
03446     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
03447     Bytes->dropLeadingBytes(bitcodeStart - buf);
03448     Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
03449   }
03450   return std::error_code();
03451 }
03452 
03453 namespace {
03454 class BitcodeErrorCategoryType : public std::error_category {
03455   const char *name() const LLVM_NOEXCEPT override {
03456     return "llvm.bitcode";
03457   }
03458   std::string message(int IE) const override {
03459     BitcodeError E = static_cast<BitcodeError>(IE);
03460     switch (E) {
03461     case BitcodeError::ConflictingMETADATA_KINDRecords:
03462       return "Conflicting METADATA_KIND records";
03463     case BitcodeError::CouldNotFindFunctionInStream:
03464       return "Could not find function in stream";
03465     case BitcodeError::ExpectedConstant:
03466       return "Expected a constant";
03467     case BitcodeError::InsufficientFunctionProtos:
03468       return "Insufficient function protos";
03469     case BitcodeError::InvalidBitcodeSignature:
03470       return "Invalid bitcode signature";
03471     case BitcodeError::InvalidBitcodeWrapperHeader:
03472       return "Invalid bitcode wrapper header";
03473     case BitcodeError::InvalidConstantReference:
03474       return "Invalid ronstant reference";
03475     case BitcodeError::InvalidID:
03476       return "Invalid ID";
03477     case BitcodeError::InvalidInstructionWithNoBB:
03478       return "Invalid instruction with no BB";
03479     case BitcodeError::InvalidRecord:
03480       return "Invalid record";
03481     case BitcodeError::InvalidTypeForValue:
03482       return "Invalid type for value";
03483     case BitcodeError::InvalidTYPETable:
03484       return "Invalid TYPE table";
03485     case BitcodeError::InvalidType:
03486       return "Invalid type";
03487     case BitcodeError::MalformedBlock:
03488       return "Malformed block";
03489     case BitcodeError::MalformedGlobalInitializerSet:
03490       return "Malformed global initializer set";
03491     case BitcodeError::InvalidMultipleBlocks:
03492       return "Invalid multiple blocks";
03493     case BitcodeError::NeverResolvedValueFoundInFunction:
03494       return "Never resolved value found in function";
03495     case BitcodeError::NeverResolvedFunctionFromBlockAddress:
03496       return "Never resolved function from blockaddress";
03497     case BitcodeError::InvalidValue:
03498       return "Invalid value";
03499     }
03500     llvm_unreachable("Unknown error type!");
03501   }
03502 };
03503 }
03504 
03505 const std::error_category &llvm::BitcodeErrorCategory() {
03506   static BitcodeErrorCategoryType O;
03507   return O;
03508 }
03509 
03510 //===----------------------------------------------------------------------===//
03511 // External interface
03512 //===----------------------------------------------------------------------===//
03513 
03514 /// \brief Get a lazy one-at-time loading module from bitcode.
03515 ///
03516 /// This isn't always used in a lazy context.  In particular, it's also used by
03517 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
03518 /// in forward-referenced functions from block address references.
03519 ///
03520 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
03521 /// materialize everything -- in particular, if this isn't truly lazy.
03522 static ErrorOr<Module *>
03523 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
03524                          LLVMContext &Context, bool WillMaterializeAll) {
03525   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
03526   BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
03527   M->setMaterializer(R);
03528 
03529   auto cleanupOnError = [&](std::error_code EC) {
03530     R->releaseBuffer(); // Never take ownership on error.
03531     delete M;  // Also deletes R.
03532     return EC;
03533   };
03534 
03535   if (std::error_code EC = R->ParseBitcodeInto(M))
03536     return cleanupOnError(EC);
03537 
03538   if (!WillMaterializeAll)
03539     // Resolve forward references from blockaddresses.
03540     if (std::error_code EC = R->materializeForwardReferencedFunctions())
03541       return cleanupOnError(EC);
03542 
03543   Buffer.release(); // The BitcodeReader owns it now.
03544   return M;
03545 }
03546 
03547 ErrorOr<Module *>
03548 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
03549                            LLVMContext &Context) {
03550   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
03551 }
03552 
03553 Module *llvm::getStreamedBitcodeModule(const std::string &name,
03554                                        DataStreamer *streamer,
03555                                        LLVMContext &Context,
03556                                        std::string *ErrMsg) {
03557   Module *M = new Module(name, Context);
03558   BitcodeReader *R = new BitcodeReader(streamer, Context);
03559   M->setMaterializer(R);
03560   if (std::error_code EC = R->ParseBitcodeInto(M)) {
03561     if (ErrMsg)
03562       *ErrMsg = EC.message();
03563     delete M;  // Also deletes R.
03564     return nullptr;
03565   }
03566   return M;
03567 }
03568 
03569 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
03570                                          LLVMContext &Context) {
03571   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
03572   ErrorOr<Module *> ModuleOrErr =
03573       getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
03574   if (!ModuleOrErr)
03575     return ModuleOrErr;
03576   Module *M = ModuleOrErr.get();
03577   // Read in the entire module, and destroy the BitcodeReader.
03578   if (std::error_code EC = M->materializeAllPermanently()) {
03579     delete M;
03580     return EC;
03581   }
03582 
03583   // TODO: Restore the use-lists to the in-memory state when the bitcode was
03584   // written.  We must defer until the Module has been fully materialized.
03585 
03586   return M;
03587 }
03588 
03589 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
03590                                          LLVMContext &Context) {
03591   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
03592   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
03593   ErrorOr<std::string> Triple = R->parseTriple();
03594   if (Triple.getError())
03595     return "";
03596   return Triple.get();
03597 }