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