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         FunctionsWithBodies.push_back(Func);
02074         if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
02075       }
02076       break;
02077     }
02078     // ALIAS: [alias type, aliasee val#, linkage]
02079     // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
02080     case bitc::MODULE_CODE_ALIAS: {
02081       if (Record.size() < 3)
02082         return Error(BitcodeError::InvalidRecord);
02083       Type *Ty = getTypeByID(Record[0]);
02084       if (!Ty)
02085         return Error(BitcodeError::InvalidRecord);
02086       auto *PTy = dyn_cast<PointerType>(Ty);
02087       if (!PTy)
02088         return Error(BitcodeError::InvalidTypeForValue);
02089 
02090       auto *NewGA =
02091           GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
02092                               GetDecodedLinkage(Record[2]), "", TheModule);
02093       // Old bitcode files didn't have visibility field.
02094       // Local linkage must have default visibility.
02095       if (Record.size() > 3 && !NewGA->hasLocalLinkage())
02096         // FIXME: Change to an error if non-default in 4.0.
02097         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
02098       if (Record.size() > 4)
02099         NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4]));
02100       else
02101         UpgradeDLLImportExportLinkage(NewGA, Record[2]);
02102       if (Record.size() > 5)
02103   NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5]));
02104       if (Record.size() > 6)
02105   NewGA->setUnnamedAddr(Record[6]);
02106       ValueList.push_back(NewGA);
02107       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
02108       break;
02109     }
02110     /// MODULE_CODE_PURGEVALS: [numvals]
02111     case bitc::MODULE_CODE_PURGEVALS:
02112       // Trim down the value list to the specified size.
02113       if (Record.size() < 1 || Record[0] > ValueList.size())
02114         return Error(BitcodeError::InvalidRecord);
02115       ValueList.shrinkTo(Record[0]);
02116       break;
02117     }
02118     Record.clear();
02119   }
02120 }
02121 
02122 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
02123   TheModule = nullptr;
02124 
02125   if (std::error_code EC = InitStream())
02126     return EC;
02127 
02128   // Sniff for the signature.
02129   if (Stream.Read(8) != 'B' ||
02130       Stream.Read(8) != 'C' ||
02131       Stream.Read(4) != 0x0 ||
02132       Stream.Read(4) != 0xC ||
02133       Stream.Read(4) != 0xE ||
02134       Stream.Read(4) != 0xD)
02135     return Error(BitcodeError::InvalidBitcodeSignature);
02136 
02137   // We expect a number of well-defined blocks, though we don't necessarily
02138   // need to understand them all.
02139   while (1) {
02140     if (Stream.AtEndOfStream())
02141       return std::error_code();
02142 
02143     BitstreamEntry Entry =
02144       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
02145 
02146     switch (Entry.Kind) {
02147     case BitstreamEntry::Error:
02148       return Error(BitcodeError::MalformedBlock);
02149     case BitstreamEntry::EndBlock:
02150       return std::error_code();
02151 
02152     case BitstreamEntry::SubBlock:
02153       switch (Entry.ID) {
02154       case bitc::BLOCKINFO_BLOCK_ID:
02155         if (Stream.ReadBlockInfoBlock())
02156           return Error(BitcodeError::MalformedBlock);
02157         break;
02158       case bitc::MODULE_BLOCK_ID:
02159         // Reject multiple MODULE_BLOCK's in a single bitstream.
02160         if (TheModule)
02161           return Error(BitcodeError::InvalidMultipleBlocks);
02162         TheModule = M;
02163         if (std::error_code EC = ParseModule(false))
02164           return EC;
02165         if (LazyStreamer)
02166           return std::error_code();
02167         break;
02168       default:
02169         if (Stream.SkipBlock())
02170           return Error(BitcodeError::InvalidRecord);
02171         break;
02172       }
02173       continue;
02174     case BitstreamEntry::Record:
02175       // There should be no records in the top-level of blocks.
02176 
02177       // The ranlib in Xcode 4 will align archive members by appending newlines
02178       // to the end of them. If this file size is a multiple of 4 but not 8, we
02179       // have to read and ignore these final 4 bytes :-(
02180       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
02181           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
02182           Stream.AtEndOfStream())
02183         return std::error_code();
02184 
02185       return Error(BitcodeError::InvalidRecord);
02186     }
02187   }
02188 }
02189 
02190 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
02191   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
02192     return Error(BitcodeError::InvalidRecord);
02193 
02194   SmallVector<uint64_t, 64> Record;
02195 
02196   std::string Triple;
02197   // Read all the records for this module.
02198   while (1) {
02199     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
02200 
02201     switch (Entry.Kind) {
02202     case BitstreamEntry::SubBlock: // Handled for us already.
02203     case BitstreamEntry::Error:
02204       return Error(BitcodeError::MalformedBlock);
02205     case BitstreamEntry::EndBlock:
02206       return Triple;
02207     case BitstreamEntry::Record:
02208       // The interesting case.
02209       break;
02210     }
02211 
02212     // Read a record.
02213     switch (Stream.readRecord(Entry.ID, Record)) {
02214     default: break;  // Default behavior, ignore unknown content.
02215     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
02216       std::string S;
02217       if (ConvertToString(Record, 0, S))
02218         return Error(BitcodeError::InvalidRecord);
02219       Triple = S;
02220       break;
02221     }
02222     }
02223     Record.clear();
02224   }
02225   llvm_unreachable("Exit infinite loop");
02226 }
02227 
02228 ErrorOr<std::string> BitcodeReader::parseTriple() {
02229   if (std::error_code EC = InitStream())
02230     return EC;
02231 
02232   // Sniff for the signature.
02233   if (Stream.Read(8) != 'B' ||
02234       Stream.Read(8) != 'C' ||
02235       Stream.Read(4) != 0x0 ||
02236       Stream.Read(4) != 0xC ||
02237       Stream.Read(4) != 0xE ||
02238       Stream.Read(4) != 0xD)
02239     return Error(BitcodeError::InvalidBitcodeSignature);
02240 
02241   // We expect a number of well-defined blocks, though we don't necessarily
02242   // need to understand them all.
02243   while (1) {
02244     BitstreamEntry Entry = Stream.advance();
02245 
02246     switch (Entry.Kind) {
02247     case BitstreamEntry::Error:
02248       return Error(BitcodeError::MalformedBlock);
02249     case BitstreamEntry::EndBlock:
02250       return std::error_code();
02251 
02252     case BitstreamEntry::SubBlock:
02253       if (Entry.ID == bitc::MODULE_BLOCK_ID)
02254         return parseModuleTriple();
02255 
02256       // Ignore other sub-blocks.
02257       if (Stream.SkipBlock())
02258         return Error(BitcodeError::MalformedBlock);
02259       continue;
02260 
02261     case BitstreamEntry::Record:
02262       Stream.skipRecord(Entry.ID);
02263       continue;
02264     }
02265   }
02266 }
02267 
02268 /// ParseMetadataAttachment - Parse metadata attachments.
02269 std::error_code BitcodeReader::ParseMetadataAttachment() {
02270   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
02271     return Error(BitcodeError::InvalidRecord);
02272 
02273   SmallVector<uint64_t, 64> Record;
02274   while (1) {
02275     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
02276 
02277     switch (Entry.Kind) {
02278     case BitstreamEntry::SubBlock: // Handled for us already.
02279     case BitstreamEntry::Error:
02280       return Error(BitcodeError::MalformedBlock);
02281     case BitstreamEntry::EndBlock:
02282       return std::error_code();
02283     case BitstreamEntry::Record:
02284       // The interesting case.
02285       break;
02286     }
02287 
02288     // Read a metadata attachment record.
02289     Record.clear();
02290     switch (Stream.readRecord(Entry.ID, Record)) {
02291     default:  // Default behavior: ignore.
02292       break;
02293     case bitc::METADATA_ATTACHMENT: {
02294       unsigned RecordLength = Record.size();
02295       if (Record.empty() || (RecordLength - 1) % 2 == 1)
02296         return Error(BitcodeError::InvalidRecord);
02297       Instruction *Inst = InstructionList[Record[0]];
02298       for (unsigned i = 1; i != RecordLength; i = i+2) {
02299         unsigned Kind = Record[i];
02300         DenseMap<unsigned, unsigned>::iterator I =
02301           MDKindMap.find(Kind);
02302         if (I == MDKindMap.end())
02303           return Error(BitcodeError::InvalidID);
02304         Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
02305         Inst->setMetadata(I->second, cast<MDNode>(Node));
02306         if (I->second == LLVMContext::MD_tbaa)
02307           InstsWithTBAATag.push_back(Inst);
02308       }
02309       break;
02310     }
02311     }
02312   }
02313 }
02314 
02315 /// ParseFunctionBody - Lazily parse the specified function body block.
02316 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
02317   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
02318     return Error(BitcodeError::InvalidRecord);
02319 
02320   InstructionList.clear();
02321   unsigned ModuleValueListSize = ValueList.size();
02322   unsigned ModuleMDValueListSize = MDValueList.size();
02323 
02324   // Add all the function arguments to the value table.
02325   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
02326     ValueList.push_back(I);
02327 
02328   unsigned NextValueNo = ValueList.size();
02329   BasicBlock *CurBB = nullptr;
02330   unsigned CurBBNo = 0;
02331 
02332   DebugLoc LastLoc;
02333 
02334   // Read all the records.
02335   SmallVector<uint64_t, 64> Record;
02336   while (1) {
02337     BitstreamEntry Entry = Stream.advance();
02338 
02339     switch (Entry.Kind) {
02340     case BitstreamEntry::Error:
02341       return Error(BitcodeError::MalformedBlock);
02342     case BitstreamEntry::EndBlock:
02343       goto OutOfRecordLoop;
02344 
02345     case BitstreamEntry::SubBlock:
02346       switch (Entry.ID) {
02347       default:  // Skip unknown content.
02348         if (Stream.SkipBlock())
02349           return Error(BitcodeError::InvalidRecord);
02350         break;
02351       case bitc::CONSTANTS_BLOCK_ID:
02352         if (std::error_code EC = ParseConstants())
02353           return EC;
02354         NextValueNo = ValueList.size();
02355         break;
02356       case bitc::VALUE_SYMTAB_BLOCK_ID:
02357         if (std::error_code EC = ParseValueSymbolTable())
02358           return EC;
02359         break;
02360       case bitc::METADATA_ATTACHMENT_ID:
02361         if (std::error_code EC = ParseMetadataAttachment())
02362           return EC;
02363         break;
02364       case bitc::METADATA_BLOCK_ID:
02365         if (std::error_code EC = ParseMetadata())
02366           return EC;
02367         break;
02368       case bitc::USELIST_BLOCK_ID:
02369         if (std::error_code EC = ParseUseLists())
02370           return EC;
02371         break;
02372       }
02373       continue;
02374 
02375     case BitstreamEntry::Record:
02376       // The interesting case.
02377       break;
02378     }
02379 
02380     // Read a record.
02381     Record.clear();
02382     Instruction *I = nullptr;
02383     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
02384     switch (BitCode) {
02385     default: // Default behavior: reject
02386       return Error(BitcodeError::InvalidValue);
02387     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
02388       if (Record.size() < 1 || Record[0] == 0)
02389         return Error(BitcodeError::InvalidRecord);
02390       // Create all the basic blocks for the function.
02391       FunctionBBs.resize(Record[0]);
02392 
02393       // See if anything took the address of blocks in this function.
02394       auto BBFRI = BasicBlockFwdRefs.find(F);
02395       if (BBFRI == BasicBlockFwdRefs.end()) {
02396         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
02397           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
02398       } else {
02399         auto &BBRefs = BBFRI->second;
02400         // Check for invalid basic block references.
02401         if (BBRefs.size() > FunctionBBs.size())
02402           return Error(BitcodeError::InvalidID);
02403         assert(!BBRefs.empty() && "Unexpected empty array");
02404         assert(!BBRefs.front() && "Invalid reference to entry block");
02405         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
02406              ++I)
02407           if (I < RE && BBRefs[I]) {
02408             BBRefs[I]->insertInto(F);
02409             FunctionBBs[I] = BBRefs[I];
02410           } else {
02411             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
02412           }
02413 
02414         // Erase from the table.
02415         BasicBlockFwdRefs.erase(BBFRI);
02416       }
02417 
02418       CurBB = FunctionBBs[0];
02419       continue;
02420     }
02421 
02422     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
02423       // This record indicates that the last instruction is at the same
02424       // location as the previous instruction with a location.
02425       I = nullptr;
02426 
02427       // Get the last instruction emitted.
02428       if (CurBB && !CurBB->empty())
02429         I = &CurBB->back();
02430       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
02431                !FunctionBBs[CurBBNo-1]->empty())
02432         I = &FunctionBBs[CurBBNo-1]->back();
02433 
02434       if (!I)
02435         return Error(BitcodeError::InvalidRecord);
02436       I->setDebugLoc(LastLoc);
02437       I = nullptr;
02438       continue;
02439 
02440     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
02441       I = nullptr;     // Get the last instruction emitted.
02442       if (CurBB && !CurBB->empty())
02443         I = &CurBB->back();
02444       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
02445                !FunctionBBs[CurBBNo-1]->empty())
02446         I = &FunctionBBs[CurBBNo-1]->back();
02447       if (!I || Record.size() < 4)
02448         return Error(BitcodeError::InvalidRecord);
02449 
02450       unsigned Line = Record[0], Col = Record[1];
02451       unsigned ScopeID = Record[2], IAID = Record[3];
02452 
02453       MDNode *Scope = nullptr, *IA = nullptr;
02454       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
02455       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
02456       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
02457       I->setDebugLoc(LastLoc);
02458       I = nullptr;
02459       continue;
02460     }
02461 
02462     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
02463       unsigned OpNum = 0;
02464       Value *LHS, *RHS;
02465       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
02466           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
02467           OpNum+1 > Record.size())
02468         return Error(BitcodeError::InvalidRecord);
02469 
02470       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
02471       if (Opc == -1)
02472         return Error(BitcodeError::InvalidRecord);
02473       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
02474       InstructionList.push_back(I);
02475       if (OpNum < Record.size()) {
02476         if (Opc == Instruction::Add ||
02477             Opc == Instruction::Sub ||
02478             Opc == Instruction::Mul ||
02479             Opc == Instruction::Shl) {
02480           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
02481             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
02482           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
02483             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
02484         } else if (Opc == Instruction::SDiv ||
02485                    Opc == Instruction::UDiv ||
02486                    Opc == Instruction::LShr ||
02487                    Opc == Instruction::AShr) {
02488           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
02489             cast<BinaryOperator>(I)->setIsExact(true);
02490         } else if (isa<FPMathOperator>(I)) {
02491           FastMathFlags FMF;
02492           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
02493             FMF.setUnsafeAlgebra();
02494           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
02495             FMF.setNoNaNs();
02496           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
02497             FMF.setNoInfs();
02498           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
02499             FMF.setNoSignedZeros();
02500           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
02501             FMF.setAllowReciprocal();
02502           if (FMF.any())
02503             I->setFastMathFlags(FMF);
02504         }
02505 
02506       }
02507       break;
02508     }
02509     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
02510       unsigned OpNum = 0;
02511       Value *Op;
02512       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
02513           OpNum+2 != Record.size())
02514         return Error(BitcodeError::InvalidRecord);
02515 
02516       Type *ResTy = getTypeByID(Record[OpNum]);
02517       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
02518       if (Opc == -1 || !ResTy)
02519         return Error(BitcodeError::InvalidRecord);
02520       Instruction *Temp = nullptr;
02521       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
02522         if (Temp) {
02523           InstructionList.push_back(Temp);
02524           CurBB->getInstList().push_back(Temp);
02525         }
02526       } else {
02527         I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
02528       }
02529       InstructionList.push_back(I);
02530       break;
02531     }
02532     case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
02533     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
02534       unsigned OpNum = 0;
02535       Value *BasePtr;
02536       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
02537         return Error(BitcodeError::InvalidRecord);
02538 
02539       SmallVector<Value*, 16> GEPIdx;
02540       while (OpNum != Record.size()) {
02541         Value *Op;
02542         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
02543           return Error(BitcodeError::InvalidRecord);
02544         GEPIdx.push_back(Op);
02545       }
02546 
02547       I = GetElementPtrInst::Create(BasePtr, GEPIdx);
02548       InstructionList.push_back(I);
02549       if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
02550         cast<GetElementPtrInst>(I)->setIsInBounds(true);
02551       break;
02552     }
02553 
02554     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
02555                                        // EXTRACTVAL: [opty, opval, n x indices]
02556       unsigned OpNum = 0;
02557       Value *Agg;
02558       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
02559         return Error(BitcodeError::InvalidRecord);
02560 
02561       SmallVector<unsigned, 4> EXTRACTVALIdx;
02562       for (unsigned RecSize = Record.size();
02563            OpNum != RecSize; ++OpNum) {
02564         uint64_t Index = Record[OpNum];
02565         if ((unsigned)Index != Index)
02566           return Error(BitcodeError::InvalidValue);
02567         EXTRACTVALIdx.push_back((unsigned)Index);
02568       }
02569 
02570       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
02571       InstructionList.push_back(I);
02572       break;
02573     }
02574 
02575     case bitc::FUNC_CODE_INST_INSERTVAL: {
02576                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
02577       unsigned OpNum = 0;
02578       Value *Agg;
02579       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
02580         return Error(BitcodeError::InvalidRecord);
02581       Value *Val;
02582       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
02583         return Error(BitcodeError::InvalidRecord);
02584 
02585       SmallVector<unsigned, 4> INSERTVALIdx;
02586       for (unsigned RecSize = Record.size();
02587            OpNum != RecSize; ++OpNum) {
02588         uint64_t Index = Record[OpNum];
02589         if ((unsigned)Index != Index)
02590           return Error(BitcodeError::InvalidValue);
02591         INSERTVALIdx.push_back((unsigned)Index);
02592       }
02593 
02594       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
02595       InstructionList.push_back(I);
02596       break;
02597     }
02598 
02599     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
02600       // obsolete form of select
02601       // handles select i1 ... in old bitcode
02602       unsigned OpNum = 0;
02603       Value *TrueVal, *FalseVal, *Cond;
02604       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
02605           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
02606           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
02607         return Error(BitcodeError::InvalidRecord);
02608 
02609       I = SelectInst::Create(Cond, TrueVal, FalseVal);
02610       InstructionList.push_back(I);
02611       break;
02612     }
02613 
02614     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
02615       // new form of select
02616       // handles select i1 or select [N x i1]
02617       unsigned OpNum = 0;
02618       Value *TrueVal, *FalseVal, *Cond;
02619       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
02620           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
02621           getValueTypePair(Record, OpNum, NextValueNo, Cond))
02622         return Error(BitcodeError::InvalidRecord);
02623 
02624       // select condition can be either i1 or [N x i1]
02625       if (VectorType* vector_type =
02626           dyn_cast<VectorType>(Cond->getType())) {
02627         // expect <n x i1>
02628         if (vector_type->getElementType() != Type::getInt1Ty(Context))
02629           return Error(BitcodeError::InvalidTypeForValue);
02630       } else {
02631         // expect i1
02632         if (Cond->getType() != Type::getInt1Ty(Context))
02633           return Error(BitcodeError::InvalidTypeForValue);
02634       }
02635 
02636       I = SelectInst::Create(Cond, TrueVal, FalseVal);
02637       InstructionList.push_back(I);
02638       break;
02639     }
02640 
02641     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
02642       unsigned OpNum = 0;
02643       Value *Vec, *Idx;
02644       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
02645           getValueTypePair(Record, OpNum, NextValueNo, Idx))
02646         return Error(BitcodeError::InvalidRecord);
02647       I = ExtractElementInst::Create(Vec, Idx);
02648       InstructionList.push_back(I);
02649       break;
02650     }
02651 
02652     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
02653       unsigned OpNum = 0;
02654       Value *Vec, *Elt, *Idx;
02655       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
02656           popValue(Record, OpNum, NextValueNo,
02657                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
02658           getValueTypePair(Record, OpNum, NextValueNo, Idx))
02659         return Error(BitcodeError::InvalidRecord);
02660       I = InsertElementInst::Create(Vec, Elt, Idx);
02661       InstructionList.push_back(I);
02662       break;
02663     }
02664 
02665     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
02666       unsigned OpNum = 0;
02667       Value *Vec1, *Vec2, *Mask;
02668       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
02669           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
02670         return Error(BitcodeError::InvalidRecord);
02671 
02672       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
02673         return Error(BitcodeError::InvalidRecord);
02674       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
02675       InstructionList.push_back(I);
02676       break;
02677     }
02678 
02679     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
02680       // Old form of ICmp/FCmp returning bool
02681       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
02682       // both legal on vectors but had different behaviour.
02683     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
02684       // FCmp/ICmp returning bool or vector of bool
02685 
02686       unsigned OpNum = 0;
02687       Value *LHS, *RHS;
02688       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
02689           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
02690           OpNum+1 != Record.size())
02691         return Error(BitcodeError::InvalidRecord);
02692 
02693       if (LHS->getType()->isFPOrFPVectorTy())
02694         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
02695       else
02696         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
02697       InstructionList.push_back(I);
02698       break;
02699     }
02700 
02701     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
02702       {
02703         unsigned Size = Record.size();
02704         if (Size == 0) {
02705           I = ReturnInst::Create(Context);
02706           InstructionList.push_back(I);
02707           break;
02708         }
02709 
02710         unsigned OpNum = 0;
02711         Value *Op = nullptr;
02712         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
02713           return Error(BitcodeError::InvalidRecord);
02714         if (OpNum != Record.size())
02715           return Error(BitcodeError::InvalidRecord);
02716 
02717         I = ReturnInst::Create(Context, Op);
02718         InstructionList.push_back(I);
02719         break;
02720       }
02721     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
02722       if (Record.size() != 1 && Record.size() != 3)
02723         return Error(BitcodeError::InvalidRecord);
02724       BasicBlock *TrueDest = getBasicBlock(Record[0]);
02725       if (!TrueDest)
02726         return Error(BitcodeError::InvalidRecord);
02727 
02728       if (Record.size() == 1) {
02729         I = BranchInst::Create(TrueDest);
02730         InstructionList.push_back(I);
02731       }
02732       else {
02733         BasicBlock *FalseDest = getBasicBlock(Record[1]);
02734         Value *Cond = getValue(Record, 2, NextValueNo,
02735                                Type::getInt1Ty(Context));
02736         if (!FalseDest || !Cond)
02737           return Error(BitcodeError::InvalidRecord);
02738         I = BranchInst::Create(TrueDest, FalseDest, Cond);
02739         InstructionList.push_back(I);
02740       }
02741       break;
02742     }
02743     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
02744       // Check magic
02745       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
02746         // "New" SwitchInst format with case ranges. The changes to write this
02747         // format were reverted but we still recognize bitcode that uses it.
02748         // Hopefully someday we will have support for case ranges and can use
02749         // this format again.
02750 
02751         Type *OpTy = getTypeByID(Record[1]);
02752         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
02753 
02754         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
02755         BasicBlock *Default = getBasicBlock(Record[3]);
02756         if (!OpTy || !Cond || !Default)
02757           return Error(BitcodeError::InvalidRecord);
02758 
02759         unsigned NumCases = Record[4];
02760 
02761         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
02762         InstructionList.push_back(SI);
02763 
02764         unsigned CurIdx = 5;
02765         for (unsigned i = 0; i != NumCases; ++i) {
02766           SmallVector<ConstantInt*, 1> CaseVals;
02767           unsigned NumItems = Record[CurIdx++];
02768           for (unsigned ci = 0; ci != NumItems; ++ci) {
02769             bool isSingleNumber = Record[CurIdx++];
02770 
02771             APInt Low;
02772             unsigned ActiveWords = 1;
02773             if (ValueBitWidth > 64)
02774               ActiveWords = Record[CurIdx++];
02775             Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
02776                                 ValueBitWidth);
02777             CurIdx += ActiveWords;
02778 
02779             if (!isSingleNumber) {
02780               ActiveWords = 1;
02781               if (ValueBitWidth > 64)
02782                 ActiveWords = Record[CurIdx++];
02783               APInt High =
02784                   ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
02785                                 ValueBitWidth);
02786               CurIdx += ActiveWords;
02787 
02788               // FIXME: It is not clear whether values in the range should be
02789               // compared as signed or unsigned values. The partially
02790               // implemented changes that used this format in the past used
02791               // unsigned comparisons.
02792               for ( ; Low.ule(High); ++Low)
02793                 CaseVals.push_back(ConstantInt::get(Context, Low));
02794             } else
02795               CaseVals.push_back(ConstantInt::get(Context, Low));
02796           }
02797           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
02798           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
02799                  cve = CaseVals.end(); cvi != cve; ++cvi)
02800             SI->addCase(*cvi, DestBB);
02801         }
02802         I = SI;
02803         break;
02804       }
02805 
02806       // Old SwitchInst format without case ranges.
02807 
02808       if (Record.size() < 3 || (Record.size() & 1) == 0)
02809         return Error(BitcodeError::InvalidRecord);
02810       Type *OpTy = getTypeByID(Record[0]);
02811       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
02812       BasicBlock *Default = getBasicBlock(Record[2]);
02813       if (!OpTy || !Cond || !Default)
02814         return Error(BitcodeError::InvalidRecord);
02815       unsigned NumCases = (Record.size()-3)/2;
02816       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
02817       InstructionList.push_back(SI);
02818       for (unsigned i = 0, e = NumCases; i != e; ++i) {
02819         ConstantInt *CaseVal =
02820           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
02821         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
02822         if (!CaseVal || !DestBB) {
02823           delete SI;
02824           return Error(BitcodeError::InvalidRecord);
02825         }
02826         SI->addCase(CaseVal, DestBB);
02827       }
02828       I = SI;
02829       break;
02830     }
02831     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
02832       if (Record.size() < 2)
02833         return Error(BitcodeError::InvalidRecord);
02834       Type *OpTy = getTypeByID(Record[0]);
02835       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
02836       if (!OpTy || !Address)
02837         return Error(BitcodeError::InvalidRecord);
02838       unsigned NumDests = Record.size()-2;
02839       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
02840       InstructionList.push_back(IBI);
02841       for (unsigned i = 0, e = NumDests; i != e; ++i) {
02842         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
02843           IBI->addDestination(DestBB);
02844         } else {
02845           delete IBI;
02846           return Error(BitcodeError::InvalidRecord);
02847         }
02848       }
02849       I = IBI;
02850       break;
02851     }
02852 
02853     case bitc::FUNC_CODE_INST_INVOKE: {
02854       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
02855       if (Record.size() < 4)
02856         return Error(BitcodeError::InvalidRecord);
02857       AttributeSet PAL = getAttributes(Record[0]);
02858       unsigned CCInfo = Record[1];
02859       BasicBlock *NormalBB = getBasicBlock(Record[2]);
02860       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
02861 
02862       unsigned OpNum = 4;
02863       Value *Callee;
02864       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
02865         return Error(BitcodeError::InvalidRecord);
02866 
02867       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
02868       FunctionType *FTy = !CalleeTy ? nullptr :
02869         dyn_cast<FunctionType>(CalleeTy->getElementType());
02870 
02871       // Check that the right number of fixed parameters are here.
02872       if (!FTy || !NormalBB || !UnwindBB ||
02873           Record.size() < OpNum+FTy->getNumParams())
02874         return Error(BitcodeError::InvalidRecord);
02875 
02876       SmallVector<Value*, 16> Ops;
02877       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
02878         Ops.push_back(getValue(Record, OpNum, NextValueNo,
02879                                FTy->getParamType(i)));
02880         if (!Ops.back())
02881           return Error(BitcodeError::InvalidRecord);
02882       }
02883 
02884       if (!FTy->isVarArg()) {
02885         if (Record.size() != OpNum)
02886           return Error(BitcodeError::InvalidRecord);
02887       } else {
02888         // Read type/value pairs for varargs params.
02889         while (OpNum != Record.size()) {
02890           Value *Op;
02891           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
02892             return Error(BitcodeError::InvalidRecord);
02893           Ops.push_back(Op);
02894         }
02895       }
02896 
02897       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
02898       InstructionList.push_back(I);
02899       cast<InvokeInst>(I)->setCallingConv(
02900         static_cast<CallingConv::ID>(CCInfo));
02901       cast<InvokeInst>(I)->setAttributes(PAL);
02902       break;
02903     }
02904     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
02905       unsigned Idx = 0;
02906       Value *Val = nullptr;
02907       if (getValueTypePair(Record, Idx, NextValueNo, Val))
02908         return Error(BitcodeError::InvalidRecord);
02909       I = ResumeInst::Create(Val);
02910       InstructionList.push_back(I);
02911       break;
02912     }
02913     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
02914       I = new UnreachableInst(Context);
02915       InstructionList.push_back(I);
02916       break;
02917     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
02918       if (Record.size() < 1 || ((Record.size()-1)&1))
02919         return Error(BitcodeError::InvalidRecord);
02920       Type *Ty = getTypeByID(Record[0]);
02921       if (!Ty)
02922         return Error(BitcodeError::InvalidRecord);
02923 
02924       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
02925       InstructionList.push_back(PN);
02926 
02927       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
02928         Value *V;
02929         // With the new function encoding, it is possible that operands have
02930         // negative IDs (for forward references).  Use a signed VBR
02931         // representation to keep the encoding small.
02932         if (UseRelativeIDs)
02933           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
02934         else
02935           V = getValue(Record, 1+i, NextValueNo, Ty);
02936         BasicBlock *BB = getBasicBlock(Record[2+i]);
02937         if (!V || !BB)
02938           return Error(BitcodeError::InvalidRecord);
02939         PN->addIncoming(V, BB);
02940       }
02941       I = PN;
02942       break;
02943     }
02944 
02945     case bitc::FUNC_CODE_INST_LANDINGPAD: {
02946       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
02947       unsigned Idx = 0;
02948       if (Record.size() < 4)
02949         return Error(BitcodeError::InvalidRecord);
02950       Type *Ty = getTypeByID(Record[Idx++]);
02951       if (!Ty)
02952         return Error(BitcodeError::InvalidRecord);
02953       Value *PersFn = nullptr;
02954       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
02955         return Error(BitcodeError::InvalidRecord);
02956 
02957       bool IsCleanup = !!Record[Idx++];
02958       unsigned NumClauses = Record[Idx++];
02959       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
02960       LP->setCleanup(IsCleanup);
02961       for (unsigned J = 0; J != NumClauses; ++J) {
02962         LandingPadInst::ClauseType CT =
02963           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
02964         Value *Val;
02965 
02966         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
02967           delete LP;
02968           return Error(BitcodeError::InvalidRecord);
02969         }
02970 
02971         assert((CT != LandingPadInst::Catch ||
02972                 !isa<ArrayType>(Val->getType())) &&
02973                "Catch clause has a invalid type!");
02974         assert((CT != LandingPadInst::Filter ||
02975                 isa<ArrayType>(Val->getType())) &&
02976                "Filter clause has invalid type!");
02977         LP->addClause(cast<Constant>(Val));
02978       }
02979 
02980       I = LP;
02981       InstructionList.push_back(I);
02982       break;
02983     }
02984 
02985     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
02986       if (Record.size() != 4)
02987         return Error(BitcodeError::InvalidRecord);
02988       PointerType *Ty =
02989         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
02990       Type *OpTy = getTypeByID(Record[1]);
02991       Value *Size = getFnValueByID(Record[2], OpTy);
02992       unsigned AlignRecord = Record[3];
02993       bool InAlloca = AlignRecord & (1 << 5);
02994       unsigned Align = AlignRecord & ((1 << 5) - 1);
02995       if (!Ty || !Size)
02996         return Error(BitcodeError::InvalidRecord);
02997       AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
02998       AI->setUsedWithInAlloca(InAlloca);
02999       I = AI;
03000       InstructionList.push_back(I);
03001       break;
03002     }
03003     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
03004       unsigned OpNum = 0;
03005       Value *Op;
03006       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
03007           OpNum+2 != Record.size())
03008         return Error(BitcodeError::InvalidRecord);
03009 
03010       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
03011       InstructionList.push_back(I);
03012       break;
03013     }
03014     case bitc::FUNC_CODE_INST_LOADATOMIC: {
03015        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
03016       unsigned OpNum = 0;
03017       Value *Op;
03018       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
03019           OpNum+4 != Record.size())
03020         return Error(BitcodeError::InvalidRecord);
03021 
03022       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
03023       if (Ordering == NotAtomic || Ordering == Release ||
03024           Ordering == AcquireRelease)
03025         return Error(BitcodeError::InvalidRecord);
03026       if (Ordering != NotAtomic && Record[OpNum] == 0)
03027         return Error(BitcodeError::InvalidRecord);
03028       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
03029 
03030       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
03031                        Ordering, SynchScope);
03032       InstructionList.push_back(I);
03033       break;
03034     }
03035     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
03036       unsigned OpNum = 0;
03037       Value *Val, *Ptr;
03038       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03039           popValue(Record, OpNum, NextValueNo,
03040                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
03041           OpNum+2 != Record.size())
03042         return Error(BitcodeError::InvalidRecord);
03043 
03044       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
03045       InstructionList.push_back(I);
03046       break;
03047     }
03048     case bitc::FUNC_CODE_INST_STOREATOMIC: {
03049       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
03050       unsigned OpNum = 0;
03051       Value *Val, *Ptr;
03052       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03053           popValue(Record, OpNum, NextValueNo,
03054                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
03055           OpNum+4 != Record.size())
03056         return Error(BitcodeError::InvalidRecord);
03057 
03058       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
03059       if (Ordering == NotAtomic || Ordering == Acquire ||
03060           Ordering == AcquireRelease)
03061         return Error(BitcodeError::InvalidRecord);
03062       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
03063       if (Ordering != NotAtomic && Record[OpNum] == 0)
03064         return Error(BitcodeError::InvalidRecord);
03065 
03066       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
03067                         Ordering, SynchScope);
03068       InstructionList.push_back(I);
03069       break;
03070     }
03071     case bitc::FUNC_CODE_INST_CMPXCHG: {
03072       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
03073       //          failureordering?, isweak?]
03074       unsigned OpNum = 0;
03075       Value *Ptr, *Cmp, *New;
03076       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03077           popValue(Record, OpNum, NextValueNo,
03078                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
03079           popValue(Record, OpNum, NextValueNo,
03080                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
03081           (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
03082         return Error(BitcodeError::InvalidRecord);
03083       AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
03084       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
03085         return Error(BitcodeError::InvalidRecord);
03086       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
03087 
03088       AtomicOrdering FailureOrdering;
03089       if (Record.size() < 7)
03090         FailureOrdering =
03091             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
03092       else
03093         FailureOrdering = GetDecodedOrdering(Record[OpNum+3]);
03094 
03095       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
03096                                 SynchScope);
03097       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
03098 
03099       if (Record.size() < 8) {
03100         // Before weak cmpxchgs existed, the instruction simply returned the
03101         // value loaded from memory, so bitcode files from that era will be
03102         // expecting the first component of a modern cmpxchg.
03103         CurBB->getInstList().push_back(I);
03104         I = ExtractValueInst::Create(I, 0);
03105       } else {
03106         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
03107       }
03108 
03109       InstructionList.push_back(I);
03110       break;
03111     }
03112     case bitc::FUNC_CODE_INST_ATOMICRMW: {
03113       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
03114       unsigned OpNum = 0;
03115       Value *Ptr, *Val;
03116       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
03117           popValue(Record, OpNum, NextValueNo,
03118                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
03119           OpNum+4 != Record.size())
03120         return Error(BitcodeError::InvalidRecord);
03121       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
03122       if (Operation < AtomicRMWInst::FIRST_BINOP ||
03123           Operation > AtomicRMWInst::LAST_BINOP)
03124         return Error(BitcodeError::InvalidRecord);
03125       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
03126       if (Ordering == NotAtomic || Ordering == Unordered)
03127         return Error(BitcodeError::InvalidRecord);
03128       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
03129       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
03130       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
03131       InstructionList.push_back(I);
03132       break;
03133     }
03134     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
03135       if (2 != Record.size())
03136         return Error(BitcodeError::InvalidRecord);
03137       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
03138       if (Ordering == NotAtomic || Ordering == Unordered ||
03139           Ordering == Monotonic)
03140         return Error(BitcodeError::InvalidRecord);
03141       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
03142       I = new FenceInst(Context, Ordering, SynchScope);
03143       InstructionList.push_back(I);
03144       break;
03145     }
03146     case bitc::FUNC_CODE_INST_CALL: {
03147       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
03148       if (Record.size() < 3)
03149         return Error(BitcodeError::InvalidRecord);
03150 
03151       AttributeSet PAL = getAttributes(Record[0]);
03152       unsigned CCInfo = Record[1];
03153 
03154       unsigned OpNum = 2;
03155       Value *Callee;
03156       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
03157         return Error(BitcodeError::InvalidRecord);
03158 
03159       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
03160       FunctionType *FTy = nullptr;
03161       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
03162       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
03163         return Error(BitcodeError::InvalidRecord);
03164 
03165       SmallVector<Value*, 16> Args;
03166       // Read the fixed params.
03167       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
03168         if (FTy->getParamType(i)->isLabelTy())
03169           Args.push_back(getBasicBlock(Record[OpNum]));
03170         else
03171           Args.push_back(getValue(Record, OpNum, NextValueNo,
03172                                   FTy->getParamType(i)));
03173         if (!Args.back())
03174           return Error(BitcodeError::InvalidRecord);
03175       }
03176 
03177       // Read type/value pairs for varargs params.
03178       if (!FTy->isVarArg()) {
03179         if (OpNum != Record.size())
03180           return Error(BitcodeError::InvalidRecord);
03181       } else {
03182         while (OpNum != Record.size()) {
03183           Value *Op;
03184           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
03185             return Error(BitcodeError::InvalidRecord);
03186           Args.push_back(Op);
03187         }
03188       }
03189 
03190       I = CallInst::Create(Callee, Args);
03191       InstructionList.push_back(I);
03192       cast<CallInst>(I)->setCallingConv(
03193           static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
03194       CallInst::TailCallKind TCK = CallInst::TCK_None;
03195       if (CCInfo & 1)
03196         TCK = CallInst::TCK_Tail;
03197       if (CCInfo & (1 << 14))
03198         TCK = CallInst::TCK_MustTail;
03199       cast<CallInst>(I)->setTailCallKind(TCK);
03200       cast<CallInst>(I)->setAttributes(PAL);
03201       break;
03202     }
03203     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
03204       if (Record.size() < 3)
03205         return Error(BitcodeError::InvalidRecord);
03206       Type *OpTy = getTypeByID(Record[0]);
03207       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
03208       Type *ResTy = getTypeByID(Record[2]);
03209       if (!OpTy || !Op || !ResTy)
03210         return Error(BitcodeError::InvalidRecord);
03211       I = new VAArgInst(Op, ResTy);
03212       InstructionList.push_back(I);
03213       break;
03214     }
03215     }
03216 
03217     // Add instruction to end of current BB.  If there is no current BB, reject
03218     // this file.
03219     if (!CurBB) {
03220       delete I;
03221       return Error(BitcodeError::InvalidInstructionWithNoBB);
03222     }
03223     CurBB->getInstList().push_back(I);
03224 
03225     // If this was a terminator instruction, move to the next block.
03226     if (isa<TerminatorInst>(I)) {
03227       ++CurBBNo;
03228       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
03229     }
03230 
03231     // Non-void values get registered in the value table for future use.
03232     if (I && !I->getType()->isVoidTy())
03233       ValueList.AssignValue(I, NextValueNo++);
03234   }
03235 
03236 OutOfRecordLoop:
03237 
03238   // Check the function list for unresolved values.
03239   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
03240     if (!A->getParent()) {
03241       // We found at least one unresolved value.  Nuke them all to avoid leaks.
03242       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
03243         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
03244           A->replaceAllUsesWith(UndefValue::get(A->getType()));
03245           delete A;
03246         }
03247       }
03248       return Error(BitcodeError::NeverResolvedValueFoundInFunction);
03249     }
03250   }
03251 
03252   // FIXME: Check for unresolved forward-declared metadata references
03253   // and clean up leaks.
03254 
03255   // Trim the value list down to the size it was before we parsed this function.
03256   ValueList.shrinkTo(ModuleValueListSize);
03257   MDValueList.shrinkTo(ModuleMDValueListSize);
03258   std::vector<BasicBlock*>().swap(FunctionBBs);
03259   return std::error_code();
03260 }
03261 
03262 /// Find the function body in the bitcode stream
03263 std::error_code BitcodeReader::FindFunctionInStream(
03264     Function *F,
03265     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
03266   while (DeferredFunctionInfoIterator->second == 0) {
03267     if (Stream.AtEndOfStream())
03268       return Error(BitcodeError::CouldNotFindFunctionInStream);
03269     // ParseModule will parse the next body in the stream and set its
03270     // position in the DeferredFunctionInfo map.
03271     if (std::error_code EC = ParseModule(true))
03272       return EC;
03273   }
03274   return std::error_code();
03275 }
03276 
03277 //===----------------------------------------------------------------------===//
03278 // GVMaterializer implementation
03279 //===----------------------------------------------------------------------===//
03280 
03281 void BitcodeReader::releaseBuffer() { Buffer.release(); }
03282 
03283 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
03284   if (const Function *F = dyn_cast<Function>(GV)) {
03285     return F->isDeclaration() &&
03286       DeferredFunctionInfo.count(const_cast<Function*>(F));
03287   }
03288   return false;
03289 }
03290 
03291 std::error_code BitcodeReader::Materialize(GlobalValue *GV) {
03292   Function *F = dyn_cast<Function>(GV);
03293   // If it's not a function or is already material, ignore the request.
03294   if (!F || !F->isMaterializable())
03295     return std::error_code();
03296 
03297   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
03298   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
03299   // If its position is recorded as 0, its body is somewhere in the stream
03300   // but we haven't seen it yet.
03301   if (DFII->second == 0 && LazyStreamer)
03302     if (std::error_code EC = FindFunctionInStream(F, DFII))
03303       return EC;
03304 
03305   // Move the bit stream to the saved position of the deferred function body.
03306   Stream.JumpToBit(DFII->second);
03307 
03308   if (std::error_code EC = ParseFunctionBody(F))
03309     return EC;
03310 
03311   // Upgrade any old intrinsic calls in the function.
03312   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
03313        E = UpgradedIntrinsics.end(); I != E; ++I) {
03314     if (I->first != I->second) {
03315       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
03316            UI != UE;) {
03317         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
03318           UpgradeIntrinsicCall(CI, I->second);
03319       }
03320     }
03321   }
03322 
03323   // Bring in any functions that this function forward-referenced via
03324   // blockaddresses.
03325   return materializeForwardReferencedFunctions();
03326 }
03327 
03328 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
03329   const Function *F = dyn_cast<Function>(GV);
03330   if (!F || F->isDeclaration())
03331     return false;
03332 
03333   // Dematerializing F would leave dangling references that wouldn't be
03334   // reconnected on re-materialization.
03335   if (BlockAddressesTaken.count(F))
03336     return false;
03337 
03338   return DeferredFunctionInfo.count(const_cast<Function*>(F));
03339 }
03340 
03341 void BitcodeReader::Dematerialize(GlobalValue *GV) {
03342   Function *F = dyn_cast<Function>(GV);
03343   // If this function isn't dematerializable, this is a noop.
03344   if (!F || !isDematerializable(F))
03345     return;
03346 
03347   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
03348 
03349   // Just forget the function body, we can remat it later.
03350   F->dropAllReferences();
03351 }
03352 
03353 std::error_code BitcodeReader::MaterializeModule(Module *M) {
03354   assert(M == TheModule &&
03355          "Can only Materialize the Module this BitcodeReader is attached to.");
03356 
03357   // Promise to materialize all forward references.
03358   WillMaterializeAllForwardRefs = true;
03359 
03360   // Iterate over the module, deserializing any functions that are still on
03361   // disk.
03362   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
03363        F != E; ++F) {
03364     if (F->isMaterializable()) {
03365       if (std::error_code EC = Materialize(F))
03366         return EC;
03367     }
03368   }
03369   // At this point, if there are any function bodies, the current bit is
03370   // pointing to the END_BLOCK record after them. Now make sure the rest
03371   // of the bits in the module have been read.
03372   if (NextUnreadBit)
03373     ParseModule(true);
03374 
03375   // Check that all block address forward references got resolved (as we
03376   // promised above).
03377   if (!BasicBlockFwdRefs.empty())
03378     return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
03379 
03380   // Upgrade any intrinsic calls that slipped through (should not happen!) and
03381   // delete the old functions to clean up. We can't do this unless the entire
03382   // module is materialized because there could always be another function body
03383   // with calls to the old function.
03384   for (std::vector<std::pair<Function*, Function*> >::iterator I =
03385        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
03386     if (I->first != I->second) {
03387       for (auto UI = I->first->user_begin(), UE = I->first->user_end();
03388            UI != UE;) {
03389         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
03390           UpgradeIntrinsicCall(CI, I->second);
03391       }
03392       if (!I->first->use_empty())
03393         I->first->replaceAllUsesWith(I->second);
03394       I->first->eraseFromParent();
03395     }
03396   }
03397   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
03398 
03399   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
03400     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
03401 
03402   UpgradeDebugInfo(*M);
03403   return std::error_code();
03404 }
03405 
03406 std::error_code BitcodeReader::InitStream() {
03407   if (LazyStreamer)
03408     return InitLazyStream();
03409   return InitStreamFromBuffer();
03410 }
03411 
03412 std::error_code BitcodeReader::InitStreamFromBuffer() {
03413   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
03414   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
03415 
03416   if (Buffer->getBufferSize() & 3)
03417     return Error(BitcodeError::InvalidBitcodeSignature);
03418 
03419   // If we have a wrapper header, parse it and ignore the non-bc file contents.
03420   // The magic number is 0x0B17C0DE stored in little endian.
03421   if (isBitcodeWrapper(BufPtr, BufEnd))
03422     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
03423       return Error(BitcodeError::InvalidBitcodeWrapperHeader);
03424 
03425   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
03426   Stream.init(*StreamFile);
03427 
03428   return std::error_code();
03429 }
03430 
03431 std::error_code BitcodeReader::InitLazyStream() {
03432   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
03433   // see it.
03434   StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
03435   StreamFile.reset(new BitstreamReader(Bytes));
03436   Stream.init(*StreamFile);
03437 
03438   unsigned char buf[16];
03439   if (Bytes->readBytes(0, 16, buf) == -1)
03440     return Error(BitcodeError::InvalidBitcodeSignature);
03441 
03442   if (!isBitcode(buf, buf + 16))
03443     return Error(BitcodeError::InvalidBitcodeSignature);
03444 
03445   if (isBitcodeWrapper(buf, buf + 4)) {
03446     const unsigned char *bitcodeStart = buf;
03447     const unsigned char *bitcodeEnd = buf + 16;
03448     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
03449     Bytes->dropLeadingBytes(bitcodeStart - buf);
03450     Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
03451   }
03452   return std::error_code();
03453 }
03454 
03455 namespace {
03456 class BitcodeErrorCategoryType : public std::error_category {
03457   const char *name() const LLVM_NOEXCEPT override {
03458     return "llvm.bitcode";
03459   }
03460   std::string message(int IE) const override {
03461     BitcodeError E = static_cast<BitcodeError>(IE);
03462     switch (E) {
03463     case BitcodeError::ConflictingMETADATA_KINDRecords:
03464       return "Conflicting METADATA_KIND records";
03465     case BitcodeError::CouldNotFindFunctionInStream:
03466       return "Could not find function in stream";
03467     case BitcodeError::ExpectedConstant:
03468       return "Expected a constant";
03469     case BitcodeError::InsufficientFunctionProtos:
03470       return "Insufficient function protos";
03471     case BitcodeError::InvalidBitcodeSignature:
03472       return "Invalid bitcode signature";
03473     case BitcodeError::InvalidBitcodeWrapperHeader:
03474       return "Invalid bitcode wrapper header";
03475     case BitcodeError::InvalidConstantReference:
03476       return "Invalid ronstant reference";
03477     case BitcodeError::InvalidID:
03478       return "Invalid ID";
03479     case BitcodeError::InvalidInstructionWithNoBB:
03480       return "Invalid instruction with no BB";
03481     case BitcodeError::InvalidRecord:
03482       return "Invalid record";
03483     case BitcodeError::InvalidTypeForValue:
03484       return "Invalid type for value";
03485     case BitcodeError::InvalidTYPETable:
03486       return "Invalid TYPE table";
03487     case BitcodeError::InvalidType:
03488       return "Invalid type";
03489     case BitcodeError::MalformedBlock:
03490       return "Malformed block";
03491     case BitcodeError::MalformedGlobalInitializerSet:
03492       return "Malformed global initializer set";
03493     case BitcodeError::InvalidMultipleBlocks:
03494       return "Invalid multiple blocks";
03495     case BitcodeError::NeverResolvedValueFoundInFunction:
03496       return "Never resolved value found in function";
03497     case BitcodeError::NeverResolvedFunctionFromBlockAddress:
03498       return "Never resolved function from blockaddress";
03499     case BitcodeError::InvalidValue:
03500       return "Invalid value";
03501     }
03502     llvm_unreachable("Unknown error type!");
03503   }
03504 };
03505 }
03506 
03507 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
03508 
03509 const std::error_category &llvm::BitcodeErrorCategory() {
03510   return *ErrorCategory;
03511 }
03512 
03513 //===----------------------------------------------------------------------===//
03514 // External interface
03515 //===----------------------------------------------------------------------===//
03516 
03517 /// \brief Get a lazy one-at-time loading module from bitcode.
03518 ///
03519 /// This isn't always used in a lazy context.  In particular, it's also used by
03520 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
03521 /// in forward-referenced functions from block address references.
03522 ///
03523 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to
03524 /// materialize everything -- in particular, if this isn't truly lazy.
03525 static ErrorOr<Module *>
03526 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
03527                          LLVMContext &Context, bool WillMaterializeAll) {
03528   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
03529   BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
03530   M->setMaterializer(R);
03531 
03532   auto cleanupOnError = [&](std::error_code EC) {
03533     R->releaseBuffer(); // Never take ownership on error.
03534     delete M;  // Also deletes R.
03535     return EC;
03536   };
03537 
03538   if (std::error_code EC = R->ParseBitcodeInto(M))
03539     return cleanupOnError(EC);
03540 
03541   if (!WillMaterializeAll)
03542     // Resolve forward references from blockaddresses.
03543     if (std::error_code EC = R->materializeForwardReferencedFunctions())
03544       return cleanupOnError(EC);
03545 
03546   Buffer.release(); // The BitcodeReader owns it now.
03547   return M;
03548 }
03549 
03550 ErrorOr<Module *>
03551 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
03552                            LLVMContext &Context) {
03553   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
03554 }
03555 
03556 Module *llvm::getStreamedBitcodeModule(const std::string &name,
03557                                        DataStreamer *streamer,
03558                                        LLVMContext &Context,
03559                                        std::string *ErrMsg) {
03560   Module *M = new Module(name, Context);
03561   BitcodeReader *R = new BitcodeReader(streamer, Context);
03562   M->setMaterializer(R);
03563   if (std::error_code EC = R->ParseBitcodeInto(M)) {
03564     if (ErrMsg)
03565       *ErrMsg = EC.message();
03566     delete M;  // Also deletes R.
03567     return nullptr;
03568   }
03569   return M;
03570 }
03571 
03572 ErrorOr<Module *> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
03573                                          LLVMContext &Context) {
03574   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
03575   ErrorOr<Module *> ModuleOrErr =
03576       getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
03577   if (!ModuleOrErr)
03578     return ModuleOrErr;
03579   Module *M = ModuleOrErr.get();
03580   // Read in the entire module, and destroy the BitcodeReader.
03581   if (std::error_code EC = M->materializeAllPermanently()) {
03582     delete M;
03583     return EC;
03584   }
03585 
03586   // TODO: Restore the use-lists to the in-memory state when the bitcode was
03587   // written.  We must defer until the Module has been fully materialized.
03588 
03589   return M;
03590 }
03591 
03592 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
03593                                          LLVMContext &Context) {
03594   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
03595   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
03596   ErrorOr<std::string> Triple = R->parseTriple();
03597   if (Triple.getError())
03598     return "";
03599   return Triple.get();
03600 }