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