LLVM API Documentation

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