1193323Sed//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2193323Sed// 3193323Sed// The LLVM Compiler Infrastructure 4193323Sed// 5193323Sed// This file is distributed under the University of Illinois Open Source 6193323Sed// License. See LICENSE.TXT for details. 7193323Sed// 8193323Sed//===----------------------------------------------------------------------===// 9193323Sed 10193323Sed#include "llvm/Bitcode/ReaderWriter.h" 11193323Sed#include "BitcodeReader.h" 12193323Sed#include "llvm/ADT/SmallString.h" 13193323Sed#include "llvm/ADT/SmallVector.h" 14249423Sdim#include "llvm/AutoUpgrade.h" 15249423Sdim#include "llvm/IR/Constants.h" 16249423Sdim#include "llvm/IR/DerivedTypes.h" 17249423Sdim#include "llvm/IR/InlineAsm.h" 18249423Sdim#include "llvm/IR/IntrinsicInst.h" 19249423Sdim#include "llvm/IR/Module.h" 20249423Sdim#include "llvm/IR/OperandTraits.h" 21249423Sdim#include "llvm/IR/Operator.h" 22234353Sdim#include "llvm/Support/DataStream.h" 23193323Sed#include "llvm/Support/MathExtras.h" 24193323Sed#include "llvm/Support/MemoryBuffer.h" 25193323Sedusing namespace llvm; 26193323Sed 27239462Sdimenum { 28239462Sdim SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 29239462Sdim}; 30239462Sdim 31234353Sdimvoid BitcodeReader::materializeForwardReferencedFunctions() { 32234353Sdim while (!BlockAddrFwdRefs.empty()) { 33234353Sdim Function *F = BlockAddrFwdRefs.begin()->first; 34234353Sdim F->Materialize(); 35234353Sdim } 36234353Sdim} 37234353Sdim 38193323Sedvoid BitcodeReader::FreeState() { 39203954Srdivacky if (BufferOwned) 40203954Srdivacky delete Buffer; 41193323Sed Buffer = 0; 42224145Sdim std::vector<Type*>().swap(TypeList); 43193323Sed ValueList.clear(); 44198090Srdivacky MDValueList.clear(); 45198090Srdivacky 46249423Sdim std::vector<AttributeSet>().swap(MAttributes); 47193323Sed std::vector<BasicBlock*>().swap(FunctionBBs); 48193323Sed std::vector<Function*>().swap(FunctionsWithBodies); 49193323Sed DeferredFunctionInfo.clear(); 50212904Sdim MDKindMap.clear(); 51243830Sdim 52243830Sdim assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references"); 53193323Sed} 54193323Sed 55193323Sed//===----------------------------------------------------------------------===// 56193323Sed// Helper functions to implement forward reference resolution, etc. 57193323Sed//===----------------------------------------------------------------------===// 58193323Sed 59193323Sed/// ConvertToString - Convert a string from a record into an std::string, return 60193323Sed/// true on failure. 61193323Sedtemplate<typename StrTy> 62239462Sdimstatic bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx, 63193323Sed StrTy &Result) { 64193323Sed if (Idx > Record.size()) 65193323Sed return true; 66198090Srdivacky 67193323Sed for (unsigned i = Idx, e = Record.size(); i != e; ++i) 68193323Sed Result += (char)Record[i]; 69193323Sed return false; 70193323Sed} 71193323Sed 72193323Sedstatic GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) { 73193323Sed switch (Val) { 74193323Sed default: // Map unknown/new linkages to external 75198090Srdivacky case 0: return GlobalValue::ExternalLinkage; 76198090Srdivacky case 1: return GlobalValue::WeakAnyLinkage; 77198090Srdivacky case 2: return GlobalValue::AppendingLinkage; 78198090Srdivacky case 3: return GlobalValue::InternalLinkage; 79198090Srdivacky case 4: return GlobalValue::LinkOnceAnyLinkage; 80198090Srdivacky case 5: return GlobalValue::DLLImportLinkage; 81198090Srdivacky case 6: return GlobalValue::DLLExportLinkage; 82198090Srdivacky case 7: return GlobalValue::ExternalWeakLinkage; 83198090Srdivacky case 8: return GlobalValue::CommonLinkage; 84198090Srdivacky case 9: return GlobalValue::PrivateLinkage; 85193323Sed case 10: return GlobalValue::WeakODRLinkage; 86193323Sed case 11: return GlobalValue::LinkOnceODRLinkage; 87193323Sed case 12: return GlobalValue::AvailableExternallyLinkage; 88198090Srdivacky case 13: return GlobalValue::LinkerPrivateLinkage; 89210299Sed case 14: return GlobalValue::LinkerPrivateWeakLinkage; 90243830Sdim case 15: return GlobalValue::LinkOnceODRAutoHideLinkage; 91193323Sed } 92193323Sed} 93193323Sed 94193323Sedstatic GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 95193323Sed switch (Val) { 96193323Sed default: // Map unknown visibilities to default. 97193323Sed case 0: return GlobalValue::DefaultVisibility; 98193323Sed case 1: return GlobalValue::HiddenVisibility; 99193323Sed case 2: return GlobalValue::ProtectedVisibility; 100193323Sed } 101193323Sed} 102193323Sed 103239462Sdimstatic GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) { 104239462Sdim switch (Val) { 105239462Sdim case 0: return GlobalVariable::NotThreadLocal; 106239462Sdim default: // Map unknown non-zero value to general dynamic. 107239462Sdim case 1: return GlobalVariable::GeneralDynamicTLSModel; 108239462Sdim case 2: return GlobalVariable::LocalDynamicTLSModel; 109239462Sdim case 3: return GlobalVariable::InitialExecTLSModel; 110239462Sdim case 4: return GlobalVariable::LocalExecTLSModel; 111239462Sdim } 112239462Sdim} 113239462Sdim 114193323Sedstatic int GetDecodedCastOpcode(unsigned Val) { 115193323Sed switch (Val) { 116193323Sed default: return -1; 117193323Sed case bitc::CAST_TRUNC : return Instruction::Trunc; 118193323Sed case bitc::CAST_ZEXT : return Instruction::ZExt; 119193323Sed case bitc::CAST_SEXT : return Instruction::SExt; 120193323Sed case bitc::CAST_FPTOUI : return Instruction::FPToUI; 121193323Sed case bitc::CAST_FPTOSI : return Instruction::FPToSI; 122193323Sed case bitc::CAST_UITOFP : return Instruction::UIToFP; 123193323Sed case bitc::CAST_SITOFP : return Instruction::SIToFP; 124193323Sed case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 125193323Sed case bitc::CAST_FPEXT : return Instruction::FPExt; 126193323Sed case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 127193323Sed case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 128193323Sed case bitc::CAST_BITCAST : return Instruction::BitCast; 129193323Sed } 130193323Sed} 131226633Sdimstatic int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) { 132193323Sed switch (Val) { 133193323Sed default: return -1; 134193574Sed case bitc::BINOP_ADD: 135203954Srdivacky return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add; 136193574Sed case bitc::BINOP_SUB: 137203954Srdivacky return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub; 138193574Sed case bitc::BINOP_MUL: 139203954Srdivacky return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul; 140193323Sed case bitc::BINOP_UDIV: return Instruction::UDiv; 141193323Sed case bitc::BINOP_SDIV: 142203954Srdivacky return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv; 143193323Sed case bitc::BINOP_UREM: return Instruction::URem; 144193323Sed case bitc::BINOP_SREM: 145203954Srdivacky return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem; 146193323Sed case bitc::BINOP_SHL: return Instruction::Shl; 147193323Sed case bitc::BINOP_LSHR: return Instruction::LShr; 148193323Sed case bitc::BINOP_ASHR: return Instruction::AShr; 149193323Sed case bitc::BINOP_AND: return Instruction::And; 150193323Sed case bitc::BINOP_OR: return Instruction::Or; 151193323Sed case bitc::BINOP_XOR: return Instruction::Xor; 152193323Sed } 153193323Sed} 154193323Sed 155226633Sdimstatic AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) { 156226633Sdim switch (Val) { 157226633Sdim default: return AtomicRMWInst::BAD_BINOP; 158226633Sdim case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 159226633Sdim case bitc::RMW_ADD: return AtomicRMWInst::Add; 160226633Sdim case bitc::RMW_SUB: return AtomicRMWInst::Sub; 161226633Sdim case bitc::RMW_AND: return AtomicRMWInst::And; 162226633Sdim case bitc::RMW_NAND: return AtomicRMWInst::Nand; 163226633Sdim case bitc::RMW_OR: return AtomicRMWInst::Or; 164226633Sdim case bitc::RMW_XOR: return AtomicRMWInst::Xor; 165226633Sdim case bitc::RMW_MAX: return AtomicRMWInst::Max; 166226633Sdim case bitc::RMW_MIN: return AtomicRMWInst::Min; 167226633Sdim case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 168226633Sdim case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 169226633Sdim } 170226633Sdim} 171226633Sdim 172226633Sdimstatic AtomicOrdering GetDecodedOrdering(unsigned Val) { 173226633Sdim switch (Val) { 174226633Sdim case bitc::ORDERING_NOTATOMIC: return NotAtomic; 175226633Sdim case bitc::ORDERING_UNORDERED: return Unordered; 176226633Sdim case bitc::ORDERING_MONOTONIC: return Monotonic; 177226633Sdim case bitc::ORDERING_ACQUIRE: return Acquire; 178226633Sdim case bitc::ORDERING_RELEASE: return Release; 179226633Sdim case bitc::ORDERING_ACQREL: return AcquireRelease; 180226633Sdim default: // Map unknown orderings to sequentially-consistent. 181226633Sdim case bitc::ORDERING_SEQCST: return SequentiallyConsistent; 182226633Sdim } 183226633Sdim} 184226633Sdim 185226633Sdimstatic SynchronizationScope GetDecodedSynchScope(unsigned Val) { 186226633Sdim switch (Val) { 187226633Sdim case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread; 188226633Sdim default: // Map unknown scopes to cross-thread. 189226633Sdim case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread; 190226633Sdim } 191226633Sdim} 192226633Sdim 193193323Sednamespace llvm { 194193323Sednamespace { 195193323Sed /// @brief A class for maintaining the slot number definition 196193323Sed /// as a placeholder for the actual definition for forward constants defs. 197193323Sed class ConstantPlaceHolder : public ConstantExpr { 198243830Sdim void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION; 199193323Sed public: 200193323Sed // allocate space for exactly one operand 201193323Sed void *operator new(size_t s) { 202193323Sed return User::operator new(s, 1); 203193323Sed } 204226633Sdim explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context) 205193323Sed : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 206198090Srdivacky Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 207193323Sed } 208198090Srdivacky 209193323Sed /// @brief Methods to support type inquiry through isa, cast, and dyn_cast. 210193323Sed static bool classof(const Value *V) { 211198090Srdivacky return isa<ConstantExpr>(V) && 212193323Sed cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 213193323Sed } 214198090Srdivacky 215198090Srdivacky 216193323Sed /// Provide fast operand accessors 217193323Sed //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 218193323Sed }; 219193323Sed} 220193323Sed 221193323Sed// FIXME: can we inherit this from ConstantExpr? 222193323Sedtemplate <> 223218893Sdimstruct OperandTraits<ConstantPlaceHolder> : 224218893Sdim public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 225193323Sed}; 226193323Sed} 227193323Sed 228193323Sed 229193323Sedvoid BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { 230193323Sed if (Idx == size()) { 231193323Sed push_back(V); 232193323Sed return; 233193323Sed } 234198090Srdivacky 235193323Sed if (Idx >= size()) 236193323Sed resize(Idx+1); 237198090Srdivacky 238193323Sed WeakVH &OldV = ValuePtrs[Idx]; 239193323Sed if (OldV == 0) { 240193323Sed OldV = V; 241193323Sed return; 242193323Sed } 243198090Srdivacky 244193323Sed // Handle constants and non-constants (e.g. instrs) differently for 245193323Sed // efficiency. 246193323Sed if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 247193323Sed ResolveConstants.push_back(std::make_pair(PHC, Idx)); 248193323Sed OldV = V; 249193323Sed } else { 250193323Sed // If there was a forward reference to this value, replace it. 251193323Sed Value *PrevVal = OldV; 252193323Sed OldV->replaceAllUsesWith(V); 253193323Sed delete PrevVal; 254193323Sed } 255193323Sed} 256193323Sed 257198090Srdivacky 258193323SedConstant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 259226633Sdim Type *Ty) { 260193323Sed if (Idx >= size()) 261193323Sed resize(Idx + 1); 262193323Sed 263193323Sed if (Value *V = ValuePtrs[Idx]) { 264193323Sed assert(Ty == V->getType() && "Type mismatch in constant table!"); 265193323Sed return cast<Constant>(V); 266193323Sed } 267193323Sed 268193323Sed // Create and return a placeholder, which will later be RAUW'd. 269198090Srdivacky Constant *C = new ConstantPlaceHolder(Ty, Context); 270193323Sed ValuePtrs[Idx] = C; 271193323Sed return C; 272193323Sed} 273193323Sed 274226633SdimValue *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 275193323Sed if (Idx >= size()) 276193323Sed resize(Idx + 1); 277198090Srdivacky 278193323Sed if (Value *V = ValuePtrs[Idx]) { 279193323Sed assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!"); 280193323Sed return V; 281193323Sed } 282198090Srdivacky 283193323Sed // No type specified, must be invalid reference. 284193323Sed if (Ty == 0) return 0; 285198090Srdivacky 286193323Sed // Create and return a placeholder, which will later be RAUW'd. 287193323Sed Value *V = new Argument(Ty); 288193323Sed ValuePtrs[Idx] = V; 289193323Sed return V; 290193323Sed} 291193323Sed 292193323Sed/// ResolveConstantForwardRefs - Once all constants are read, this method bulk 293193323Sed/// resolves any forward references. The idea behind this is that we sometimes 294193323Sed/// get constants (such as large arrays) which reference *many* forward ref 295193323Sed/// constants. Replacing each of these causes a lot of thrashing when 296193323Sed/// building/reuniquing the constant. Instead of doing this, we look at all the 297193323Sed/// uses and rewrite all the place holders at once for any constant that uses 298193323Sed/// a placeholder. 299193323Sedvoid BitcodeReaderValueList::ResolveConstantForwardRefs() { 300198090Srdivacky // Sort the values by-pointer so that they are efficient to look up with a 301193323Sed // binary search. 302193323Sed std::sort(ResolveConstants.begin(), ResolveConstants.end()); 303198090Srdivacky 304193323Sed SmallVector<Constant*, 64> NewOps; 305198090Srdivacky 306193323Sed while (!ResolveConstants.empty()) { 307193323Sed Value *RealVal = operator[](ResolveConstants.back().second); 308193323Sed Constant *Placeholder = ResolveConstants.back().first; 309193323Sed ResolveConstants.pop_back(); 310198090Srdivacky 311193323Sed // Loop over all users of the placeholder, updating them to reference the 312193323Sed // new value. If they reference more than one placeholder, update them all 313193323Sed // at once. 314193323Sed while (!Placeholder->use_empty()) { 315193323Sed Value::use_iterator UI = Placeholder->use_begin(); 316210299Sed User *U = *UI; 317198090Srdivacky 318193323Sed // If the using object isn't uniqued, just update the operands. This 319193323Sed // handles instructions and initializers for global variables. 320210299Sed if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 321193323Sed UI.getUse().set(RealVal); 322193323Sed continue; 323193323Sed } 324198090Srdivacky 325193323Sed // Otherwise, we have a constant that uses the placeholder. Replace that 326193323Sed // constant with a new constant that has *all* placeholder uses updated. 327210299Sed Constant *UserC = cast<Constant>(U); 328193323Sed for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 329193323Sed I != E; ++I) { 330193323Sed Value *NewOp; 331193323Sed if (!isa<ConstantPlaceHolder>(*I)) { 332193323Sed // Not a placeholder reference. 333193323Sed NewOp = *I; 334193323Sed } else if (*I == Placeholder) { 335193323Sed // Common case is that it just references this one placeholder. 336193323Sed NewOp = RealVal; 337193323Sed } else { 338193323Sed // Otherwise, look up the placeholder in ResolveConstants. 339198090Srdivacky ResolveConstantsTy::iterator It = 340198090Srdivacky std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 341193323Sed std::pair<Constant*, unsigned>(cast<Constant>(*I), 342193323Sed 0)); 343193323Sed assert(It != ResolveConstants.end() && It->first == *I); 344193323Sed NewOp = operator[](It->second); 345193323Sed } 346193323Sed 347193323Sed NewOps.push_back(cast<Constant>(NewOp)); 348193323Sed } 349193323Sed 350193323Sed // Make the new constant. 351193323Sed Constant *NewC; 352193323Sed if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 353224145Sdim NewC = ConstantArray::get(UserCA->getType(), NewOps); 354193323Sed } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 355224145Sdim NewC = ConstantStruct::get(UserCS->getType(), NewOps); 356193323Sed } else if (isa<ConstantVector>(UserC)) { 357218893Sdim NewC = ConstantVector::get(NewOps); 358193323Sed } else { 359193323Sed assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 360221345Sdim NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 361193323Sed } 362198090Srdivacky 363193323Sed UserC->replaceAllUsesWith(NewC); 364193323Sed UserC->destroyConstant(); 365193323Sed NewOps.clear(); 366193323Sed } 367198090Srdivacky 368193323Sed // Update all ValueHandles, they should be the only users at this point. 369193323Sed Placeholder->replaceAllUsesWith(RealVal); 370193323Sed delete Placeholder; 371193323Sed } 372193323Sed} 373193323Sed 374198090Srdivackyvoid BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) { 375198090Srdivacky if (Idx == size()) { 376198090Srdivacky push_back(V); 377198090Srdivacky return; 378198090Srdivacky } 379193323Sed 380198090Srdivacky if (Idx >= size()) 381198090Srdivacky resize(Idx+1); 382198090Srdivacky 383198090Srdivacky WeakVH &OldV = MDValuePtrs[Idx]; 384198090Srdivacky if (OldV == 0) { 385198090Srdivacky OldV = V; 386198090Srdivacky return; 387198090Srdivacky } 388198090Srdivacky 389198090Srdivacky // If there was a forward reference to this value, replace it. 390212904Sdim MDNode *PrevVal = cast<MDNode>(OldV); 391198090Srdivacky OldV->replaceAllUsesWith(V); 392212904Sdim MDNode::deleteTemporary(PrevVal); 393198090Srdivacky // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new 394198090Srdivacky // value for Idx. 395198090Srdivacky MDValuePtrs[Idx] = V; 396198090Srdivacky} 397198090Srdivacky 398198090SrdivackyValue *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) { 399198090Srdivacky if (Idx >= size()) 400198090Srdivacky resize(Idx + 1); 401198090Srdivacky 402198090Srdivacky if (Value *V = MDValuePtrs[Idx]) { 403198090Srdivacky assert(V->getType()->isMetadataTy() && "Type mismatch in value table!"); 404198090Srdivacky return V; 405198090Srdivacky } 406198090Srdivacky 407198090Srdivacky // Create and return a placeholder, which will later be RAUW'd. 408251662Sdim Value *V = MDNode::getTemporary(Context, None); 409198090Srdivacky MDValuePtrs[Idx] = V; 410198090Srdivacky return V; 411198090Srdivacky} 412198090Srdivacky 413224145SdimType *BitcodeReader::getTypeByID(unsigned ID) { 414224145Sdim // The type table size is always specified correctly. 415224145Sdim if (ID >= TypeList.size()) 416224145Sdim return 0; 417234353Sdim 418224145Sdim if (Type *Ty = TypeList[ID]) 419224145Sdim return Ty; 420198090Srdivacky 421224145Sdim // If we have a forward reference, the only possible case is when it is to a 422224145Sdim // named struct. Just create a placeholder for now. 423226633Sdim return TypeList[ID] = StructType::create(Context); 424193323Sed} 425193323Sed 426224145Sdim 427193323Sed//===----------------------------------------------------------------------===// 428193323Sed// Functions for parsing blocks from the bitcode file 429193323Sed//===----------------------------------------------------------------------===// 430193323Sed 431249423Sdim 432249423Sdim/// \brief This fills an AttrBuilder object with the LLVM attributes that have 433249423Sdim/// been decoded from the given integer. This function must stay in sync with 434249423Sdim/// 'encodeLLVMAttributesForBitcode'. 435249423Sdimstatic void decodeLLVMAttributesForBitcode(AttrBuilder &B, 436249423Sdim uint64_t EncodedAttrs) { 437249423Sdim // FIXME: Remove in 4.0. 438249423Sdim 439249423Sdim // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 440249423Sdim // the bits above 31 down by 11 bits. 441249423Sdim unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 442249423Sdim assert((!Alignment || isPowerOf2_32(Alignment)) && 443249423Sdim "Alignment must be a power of two."); 444249423Sdim 445249423Sdim if (Alignment) 446249423Sdim B.addAlignmentAttr(Alignment); 447249423Sdim B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 448249423Sdim (EncodedAttrs & 0xffff)); 449249423Sdim} 450249423Sdim 451193323Sedbool BitcodeReader::ParseAttributeBlock() { 452193323Sed if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 453193323Sed return Error("Malformed block record"); 454198090Srdivacky 455193323Sed if (!MAttributes.empty()) 456193323Sed return Error("Multiple PARAMATTR blocks found!"); 457198090Srdivacky 458193323Sed SmallVector<uint64_t, 64> Record; 459198090Srdivacky 460249423Sdim SmallVector<AttributeSet, 8> Attrs; 461198090Srdivacky 462193323Sed // Read all the records. 463193323Sed while (1) { 464249423Sdim BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 465249423Sdim 466249423Sdim switch (Entry.Kind) { 467249423Sdim case BitstreamEntry::SubBlock: // Handled for us already. 468249423Sdim case BitstreamEntry::Error: 469249423Sdim return Error("Error at end of PARAMATTR block"); 470249423Sdim case BitstreamEntry::EndBlock: 471193323Sed return false; 472249423Sdim case BitstreamEntry::Record: 473249423Sdim // The interesting case. 474249423Sdim break; 475193323Sed } 476198090Srdivacky 477249423Sdim // Read a record. 478249423Sdim Record.clear(); 479249423Sdim switch (Stream.readRecord(Entry.ID, Record)) { 480249423Sdim default: // Default behavior: ignore. 481249423Sdim break; 482249423Sdim case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 483249423Sdim // FIXME: Remove in 4.0. 484249423Sdim if (Record.size() & 1) 485249423Sdim return Error("Invalid ENTRY record"); 486249423Sdim 487249423Sdim for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 488249423Sdim AttrBuilder B; 489249423Sdim decodeLLVMAttributesForBitcode(B, Record[i+1]); 490249423Sdim Attrs.push_back(AttributeSet::get(Context, Record[i], B)); 491249423Sdim } 492249423Sdim 493249423Sdim MAttributes.push_back(AttributeSet::get(Context, Attrs)); 494249423Sdim Attrs.clear(); 495249423Sdim break; 496193323Sed } 497249423Sdim case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 498249423Sdim for (unsigned i = 0, e = Record.size(); i != e; ++i) 499249423Sdim Attrs.push_back(MAttributeGroups[Record[i]]); 500198090Srdivacky 501249423Sdim MAttributes.push_back(AttributeSet::get(Context, Attrs)); 502249423Sdim Attrs.clear(); 503249423Sdim break; 504193323Sed } 505249423Sdim } 506249423Sdim } 507249423Sdim} 508198090Srdivacky 509249423Sdimbool BitcodeReader::ParseAttributeGroupBlock() { 510249423Sdim if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 511249423Sdim return Error("Malformed block record"); 512249423Sdim 513249423Sdim if (!MAttributeGroups.empty()) 514249423Sdim return Error("Multiple PARAMATTR_GROUP blocks found!"); 515249423Sdim 516249423Sdim SmallVector<uint64_t, 64> Record; 517249423Sdim 518249423Sdim // Read all the records. 519249423Sdim while (1) { 520249423Sdim BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 521249423Sdim 522249423Sdim switch (Entry.Kind) { 523249423Sdim case BitstreamEntry::SubBlock: // Handled for us already. 524249423Sdim case BitstreamEntry::Error: 525249423Sdim return Error("Error at end of PARAMATTR_GROUP block"); 526249423Sdim case BitstreamEntry::EndBlock: 527249423Sdim return false; 528249423Sdim case BitstreamEntry::Record: 529249423Sdim // The interesting case. 530249423Sdim break; 531249423Sdim } 532249423Sdim 533193323Sed // Read a record. 534193323Sed Record.clear(); 535249423Sdim switch (Stream.readRecord(Entry.ID, Record)) { 536193323Sed default: // Default behavior: ignore. 537193323Sed break; 538249423Sdim case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 539249423Sdim if (Record.size() < 3) 540193323Sed return Error("Invalid ENTRY record"); 541193323Sed 542249423Sdim uint64_t GrpID = Record[0]; 543249423Sdim uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 544193323Sed 545249423Sdim AttrBuilder B; 546249423Sdim for (unsigned i = 2, e = Record.size(); i != e; ++i) { 547249423Sdim if (Record[i] == 0) { // Enum attribute 548249423Sdim B.addAttribute(Attribute::AttrKind(Record[++i])); 549249423Sdim } else if (Record[i] == 1) { // Align attribute 550249423Sdim if (Attribute::AttrKind(Record[++i]) == Attribute::Alignment) 551249423Sdim B.addAlignmentAttr(Record[++i]); 552249423Sdim else 553249423Sdim B.addStackAlignmentAttr(Record[++i]); 554249423Sdim } else { // String attribute 555249423Sdim assert((Record[i] == 3 || Record[i] == 4) && 556249423Sdim "Invalid attribute group entry"); 557249423Sdim bool HasValue = (Record[i++] == 4); 558249423Sdim SmallString<64> KindStr; 559249423Sdim SmallString<64> ValStr; 560249423Sdim 561249423Sdim while (Record[i] != 0 && i != e) 562249423Sdim KindStr += Record[i++]; 563249423Sdim assert(Record[i] == 0 && "Kind string not null terminated"); 564249423Sdim 565249423Sdim if (HasValue) { 566249423Sdim // Has a value associated with it. 567249423Sdim ++i; // Skip the '0' that terminates the "kind" string. 568249423Sdim while (Record[i] != 0 && i != e) 569249423Sdim ValStr += Record[i++]; 570249423Sdim assert(Record[i] == 0 && "Value string not null terminated"); 571249423Sdim } 572249423Sdim 573249423Sdim B.addAttribute(KindStr.str(), ValStr.str()); 574249423Sdim } 575193323Sed } 576193323Sed 577249423Sdim MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B); 578193323Sed break; 579193323Sed } 580193323Sed } 581193323Sed } 582193323Sed} 583193323Sed 584193323Sedbool BitcodeReader::ParseTypeTable() { 585224145Sdim if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 586193323Sed return Error("Malformed block record"); 587234353Sdim 588224145Sdim return ParseTypeTableBody(); 589224145Sdim} 590198090Srdivacky 591224145Sdimbool BitcodeReader::ParseTypeTableBody() { 592193323Sed if (!TypeList.empty()) 593193323Sed return Error("Multiple TYPE_BLOCKs found!"); 594193323Sed 595193323Sed SmallVector<uint64_t, 64> Record; 596193323Sed unsigned NumRecords = 0; 597193323Sed 598224145Sdim SmallString<64> TypeName; 599234353Sdim 600193323Sed // Read all the records for this type table. 601193323Sed while (1) { 602249423Sdim BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 603249423Sdim 604249423Sdim switch (Entry.Kind) { 605249423Sdim case BitstreamEntry::SubBlock: // Handled for us already. 606249423Sdim case BitstreamEntry::Error: 607249423Sdim Error("Error in the type table block"); 608249423Sdim return true; 609249423Sdim case BitstreamEntry::EndBlock: 610193323Sed if (NumRecords != TypeList.size()) 611193323Sed return Error("Invalid type forward reference in TYPE_BLOCK"); 612193323Sed return false; 613249423Sdim case BitstreamEntry::Record: 614249423Sdim // The interesting case. 615249423Sdim break; 616193323Sed } 617198090Srdivacky 618193323Sed // Read a record. 619193323Sed Record.clear(); 620224145Sdim Type *ResultTy = 0; 621249423Sdim switch (Stream.readRecord(Entry.ID, Record)) { 622224145Sdim default: return Error("unknown type in type table"); 623193323Sed case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 624193323Sed // TYPE_CODE_NUMENTRY contains a count of the number of types in the 625193323Sed // type list. This allows us to reserve space. 626193323Sed if (Record.size() < 1) 627193323Sed return Error("Invalid TYPE_CODE_NUMENTRY record"); 628224145Sdim TypeList.resize(Record[0]); 629193323Sed continue; 630193323Sed case bitc::TYPE_CODE_VOID: // VOID 631198090Srdivacky ResultTy = Type::getVoidTy(Context); 632193323Sed break; 633234353Sdim case bitc::TYPE_CODE_HALF: // HALF 634234353Sdim ResultTy = Type::getHalfTy(Context); 635234353Sdim break; 636193323Sed case bitc::TYPE_CODE_FLOAT: // FLOAT 637198090Srdivacky ResultTy = Type::getFloatTy(Context); 638193323Sed break; 639193323Sed case bitc::TYPE_CODE_DOUBLE: // DOUBLE 640198090Srdivacky ResultTy = Type::getDoubleTy(Context); 641193323Sed break; 642193323Sed case bitc::TYPE_CODE_X86_FP80: // X86_FP80 643198090Srdivacky ResultTy = Type::getX86_FP80Ty(Context); 644193323Sed break; 645193323Sed case bitc::TYPE_CODE_FP128: // FP128 646198090Srdivacky ResultTy = Type::getFP128Ty(Context); 647193323Sed break; 648193323Sed case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 649198090Srdivacky ResultTy = Type::getPPC_FP128Ty(Context); 650193323Sed break; 651193323Sed case bitc::TYPE_CODE_LABEL: // LABEL 652198090Srdivacky ResultTy = Type::getLabelTy(Context); 653193323Sed break; 654193323Sed case bitc::TYPE_CODE_METADATA: // METADATA 655198090Srdivacky ResultTy = Type::getMetadataTy(Context); 656193323Sed break; 657218893Sdim case bitc::TYPE_CODE_X86_MMX: // X86_MMX 658218893Sdim ResultTy = Type::getX86_MMXTy(Context); 659218893Sdim break; 660193323Sed case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 661193323Sed if (Record.size() < 1) 662193323Sed return Error("Invalid Integer type record"); 663198090Srdivacky 664198090Srdivacky ResultTy = IntegerType::get(Context, Record[0]); 665193323Sed break; 666198090Srdivacky case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 667193323Sed // [pointee type, address space] 668193323Sed if (Record.size() < 1) 669193323Sed return Error("Invalid POINTER type record"); 670193323Sed unsigned AddressSpace = 0; 671193323Sed if (Record.size() == 2) 672193323Sed AddressSpace = Record[1]; 673224145Sdim ResultTy = getTypeByID(Record[0]); 674224145Sdim if (ResultTy == 0) return Error("invalid element type in pointer type"); 675224145Sdim ResultTy = PointerType::get(ResultTy, AddressSpace); 676193323Sed break; 677193323Sed } 678234353Sdim case bitc::TYPE_CODE_FUNCTION_OLD: { 679239462Sdim // FIXME: attrid is dead, remove it in LLVM 4.0 680193323Sed // FUNCTION: [vararg, attrid, retty, paramty x N] 681193323Sed if (Record.size() < 3) 682193323Sed return Error("Invalid FUNCTION type record"); 683234353Sdim SmallVector<Type*, 8> ArgTys; 684224145Sdim for (unsigned i = 3, e = Record.size(); i != e; ++i) { 685224145Sdim if (Type *T = getTypeByID(Record[i])) 686224145Sdim ArgTys.push_back(T); 687224145Sdim else 688224145Sdim break; 689224145Sdim } 690249423Sdim 691224145Sdim ResultTy = getTypeByID(Record[2]); 692224145Sdim if (ResultTy == 0 || ArgTys.size() < Record.size()-3) 693224145Sdim return Error("invalid type in function type"); 694198090Srdivacky 695224145Sdim ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 696193323Sed break; 697193323Sed } 698234353Sdim case bitc::TYPE_CODE_FUNCTION: { 699234353Sdim // FUNCTION: [vararg, retty, paramty x N] 700234353Sdim if (Record.size() < 2) 701234353Sdim return Error("Invalid FUNCTION type record"); 702234353Sdim SmallVector<Type*, 8> ArgTys; 703234353Sdim for (unsigned i = 2, e = Record.size(); i != e; ++i) { 704234353Sdim if (Type *T = getTypeByID(Record[i])) 705234353Sdim ArgTys.push_back(T); 706234353Sdim else 707234353Sdim break; 708234353Sdim } 709249423Sdim 710234353Sdim ResultTy = getTypeByID(Record[1]); 711234353Sdim if (ResultTy == 0 || ArgTys.size() < Record.size()-2) 712234353Sdim return Error("invalid type in function type"); 713234353Sdim 714234353Sdim ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 715234353Sdim break; 716234353Sdim } 717224145Sdim case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 718193323Sed if (Record.size() < 1) 719193323Sed return Error("Invalid STRUCT type record"); 720234353Sdim SmallVector<Type*, 8> EltTys; 721224145Sdim for (unsigned i = 1, e = Record.size(); i != e; ++i) { 722224145Sdim if (Type *T = getTypeByID(Record[i])) 723224145Sdim EltTys.push_back(T); 724224145Sdim else 725224145Sdim break; 726224145Sdim } 727224145Sdim if (EltTys.size() != Record.size()-1) 728224145Sdim return Error("invalid type in struct type"); 729198090Srdivacky ResultTy = StructType::get(Context, EltTys, Record[0]); 730193323Sed break; 731193323Sed } 732224145Sdim case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 733224145Sdim if (ConvertToString(Record, 0, TypeName)) 734224145Sdim return Error("Invalid STRUCT_NAME record"); 735224145Sdim continue; 736224145Sdim 737224145Sdim case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 738224145Sdim if (Record.size() < 1) 739224145Sdim return Error("Invalid STRUCT type record"); 740249423Sdim 741224145Sdim if (NumRecords >= TypeList.size()) 742224145Sdim return Error("invalid TYPE table"); 743249423Sdim 744224145Sdim // Check to see if this was forward referenced, if so fill in the temp. 745224145Sdim StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 746224145Sdim if (Res) { 747224145Sdim Res->setName(TypeName); 748224145Sdim TypeList[NumRecords] = 0; 749224145Sdim } else // Otherwise, create a new struct. 750226633Sdim Res = StructType::create(Context, TypeName); 751224145Sdim TypeName.clear(); 752249423Sdim 753224145Sdim SmallVector<Type*, 8> EltTys; 754224145Sdim for (unsigned i = 1, e = Record.size(); i != e; ++i) { 755224145Sdim if (Type *T = getTypeByID(Record[i])) 756224145Sdim EltTys.push_back(T); 757224145Sdim else 758224145Sdim break; 759224145Sdim } 760224145Sdim if (EltTys.size() != Record.size()-1) 761224145Sdim return Error("invalid STRUCT type record"); 762224145Sdim Res->setBody(EltTys, Record[0]); 763224145Sdim ResultTy = Res; 764224145Sdim break; 765224145Sdim } 766224145Sdim case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 767224145Sdim if (Record.size() != 1) 768224145Sdim return Error("Invalid OPAQUE type record"); 769224145Sdim 770224145Sdim if (NumRecords >= TypeList.size()) 771224145Sdim return Error("invalid TYPE table"); 772249423Sdim 773224145Sdim // Check to see if this was forward referenced, if so fill in the temp. 774224145Sdim StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 775224145Sdim if (Res) { 776224145Sdim Res->setName(TypeName); 777224145Sdim TypeList[NumRecords] = 0; 778224145Sdim } else // Otherwise, create a new struct with no body. 779226633Sdim Res = StructType::create(Context, TypeName); 780224145Sdim TypeName.clear(); 781224145Sdim ResultTy = Res; 782224145Sdim break; 783249423Sdim } 784193323Sed case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 785193323Sed if (Record.size() < 2) 786193323Sed return Error("Invalid ARRAY type record"); 787224145Sdim if ((ResultTy = getTypeByID(Record[1]))) 788224145Sdim ResultTy = ArrayType::get(ResultTy, Record[0]); 789224145Sdim else 790224145Sdim return Error("Invalid ARRAY type element"); 791193323Sed break; 792193323Sed case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 793193323Sed if (Record.size() < 2) 794193323Sed return Error("Invalid VECTOR type record"); 795224145Sdim if ((ResultTy = getTypeByID(Record[1]))) 796224145Sdim ResultTy = VectorType::get(ResultTy, Record[0]); 797224145Sdim else 798224145Sdim return Error("Invalid ARRAY type element"); 799193323Sed break; 800193323Sed } 801198090Srdivacky 802224145Sdim if (NumRecords >= TypeList.size()) 803224145Sdim return Error("invalid TYPE table"); 804224145Sdim assert(ResultTy && "Didn't read a type?"); 805224145Sdim assert(TypeList[NumRecords] == 0 && "Already read type?"); 806224145Sdim TypeList[NumRecords++] = ResultTy; 807224145Sdim } 808224145Sdim} 809198090Srdivacky 810193323Sedbool BitcodeReader::ParseValueSymbolTable() { 811193323Sed if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 812193323Sed return Error("Malformed block record"); 813193323Sed 814193323Sed SmallVector<uint64_t, 64> Record; 815198090Srdivacky 816193323Sed // Read all the records for this value table. 817193323Sed SmallString<128> ValueName; 818193323Sed while (1) { 819249423Sdim BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 820249423Sdim 821249423Sdim switch (Entry.Kind) { 822249423Sdim case BitstreamEntry::SubBlock: // Handled for us already. 823249423Sdim case BitstreamEntry::Error: 824249423Sdim return Error("malformed value symbol table block"); 825249423Sdim case BitstreamEntry::EndBlock: 826193323Sed return false; 827249423Sdim case BitstreamEntry::Record: 828249423Sdim // The interesting case. 829249423Sdim break; 830198090Srdivacky } 831198090Srdivacky 832193323Sed // Read a record. 833193323Sed Record.clear(); 834249423Sdim switch (Stream.readRecord(Entry.ID, Record)) { 835193323Sed default: // Default behavior: unknown type. 836193323Sed break; 837193323Sed case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 838193323Sed if (ConvertToString(Record, 1, ValueName)) 839193323Sed return Error("Invalid VST_ENTRY record"); 840193323Sed unsigned ValueID = Record[0]; 841193323Sed if (ValueID >= ValueList.size()) 842193323Sed return Error("Invalid Value ID in VST_ENTRY record"); 843193323Sed Value *V = ValueList[ValueID]; 844198090Srdivacky 845198090Srdivacky V->setName(StringRef(ValueName.data(), ValueName.size())); 846193323Sed ValueName.clear(); 847193323Sed break; 848193323Sed } 849193323Sed case bitc::VST_CODE_BBENTRY: { 850193323Sed if (ConvertToString(Record, 1, ValueName)) 851193323Sed return Error("Invalid VST_BBENTRY record"); 852193323Sed BasicBlock *BB = getBasicBlock(Record[0]); 853193323Sed if (BB == 0) 854193323Sed return Error("Invalid BB ID in VST_BBENTRY record"); 855198090Srdivacky 856198090Srdivacky BB->setName(StringRef(ValueName.data(), ValueName.size())); 857193323Sed ValueName.clear(); 858193323Sed break; 859193323Sed } 860193323Sed } 861193323Sed } 862193323Sed} 863193323Sed 864198090Srdivackybool BitcodeReader::ParseMetadata() { 865202375Srdivacky unsigned NextMDValueNo = MDValueList.size(); 866198090Srdivacky 867198090Srdivacky if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 868198090Srdivacky return Error("Malformed block record"); 869198090Srdivacky 870198090Srdivacky SmallVector<uint64_t, 64> Record; 871198090Srdivacky 872198090Srdivacky // Read all the records. 873198090Srdivacky while (1) { 874249423Sdim BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 875249423Sdim 876249423Sdim switch (Entry.Kind) { 877249423Sdim case BitstreamEntry::SubBlock: // Handled for us already. 878249423Sdim case BitstreamEntry::Error: 879249423Sdim Error("malformed metadata block"); 880249423Sdim return true; 881249423Sdim case BitstreamEntry::EndBlock: 882198090Srdivacky return false; 883249423Sdim case BitstreamEntry::Record: 884249423Sdim // The interesting case. 885249423Sdim break; 886198090Srdivacky } 887198090Srdivacky 888202375Srdivacky bool IsFunctionLocal = false; 889198090Srdivacky // Read a record. 890198090Srdivacky Record.clear(); 891249423Sdim unsigned Code = Stream.readRecord(Entry.ID, Record); 892212904Sdim switch (Code) { 893198090Srdivacky default: // Default behavior: ignore. 894198090Srdivacky break; 895198090Srdivacky case bitc::METADATA_NAME: { 896249423Sdim // Read name of the named metadata. 897239462Sdim SmallString<8> Name(Record.begin(), Record.end()); 898198090Srdivacky Record.clear(); 899198090Srdivacky Code = Stream.ReadCode(); 900198090Srdivacky 901224145Sdim // METADATA_NAME is always followed by METADATA_NAMED_NODE. 902249423Sdim unsigned NextBitCode = Stream.readRecord(Code, Record); 903224145Sdim assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode; 904198090Srdivacky 905198090Srdivacky // Read named metadata elements. 906198090Srdivacky unsigned Size = Record.size(); 907212904Sdim NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 908198090Srdivacky for (unsigned i = 0; i != Size; ++i) { 909202375Srdivacky MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i])); 910202375Srdivacky if (MD == 0) 911202375Srdivacky return Error("Malformed metadata record"); 912212904Sdim NMD->addOperand(MD); 913198090Srdivacky } 914198090Srdivacky break; 915198090Srdivacky } 916224145Sdim case bitc::METADATA_FN_NODE: 917202375Srdivacky IsFunctionLocal = true; 918202375Srdivacky // fall-through 919224145Sdim case bitc::METADATA_NODE: { 920210299Sed if (Record.size() % 2 == 1) 921224145Sdim return Error("Invalid METADATA_NODE record"); 922198090Srdivacky 923198090Srdivacky unsigned Size = Record.size(); 924198090Srdivacky SmallVector<Value*, 8> Elts; 925198090Srdivacky for (unsigned i = 0; i != Size; i += 2) { 926226633Sdim Type *Ty = getTypeByID(Record[i]); 927224145Sdim if (!Ty) return Error("Invalid METADATA_NODE record"); 928198090Srdivacky if (Ty->isMetadataTy()) 929198090Srdivacky Elts.push_back(MDValueList.getValueFwdRef(Record[i+1])); 930202375Srdivacky else if (!Ty->isVoidTy()) 931198090Srdivacky Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty)); 932198090Srdivacky else 933198090Srdivacky Elts.push_back(NULL); 934198090Srdivacky } 935221345Sdim Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal); 936202375Srdivacky IsFunctionLocal = false; 937202375Srdivacky MDValueList.AssignValue(V, NextMDValueNo++); 938198090Srdivacky break; 939198090Srdivacky } 940198090Srdivacky case bitc::METADATA_STRING: { 941239462Sdim SmallString<8> String(Record.begin(), Record.end()); 942239462Sdim Value *V = MDString::get(Context, String); 943202375Srdivacky MDValueList.AssignValue(V, NextMDValueNo++); 944198090Srdivacky break; 945198090Srdivacky } 946198090Srdivacky case bitc::METADATA_KIND: { 947239462Sdim if (Record.size() < 2) 948198090Srdivacky return Error("Invalid METADATA_KIND record"); 949239462Sdim 950198090Srdivacky unsigned Kind = Record[0]; 951239462Sdim SmallString<8> Name(Record.begin()+1, Record.end()); 952239462Sdim 953201360Srdivacky unsigned NewKind = TheModule->getMDKindID(Name.str()); 954212904Sdim if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 955212904Sdim return Error("Conflicting METADATA_KIND records"); 956198090Srdivacky break; 957198090Srdivacky } 958198090Srdivacky } 959198090Srdivacky } 960198090Srdivacky} 961198090Srdivacky 962243830Sdim/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in 963193323Sed/// the LSB for dense VBR encoding. 964243830Sdimuint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 965193323Sed if ((V & 1) == 0) 966193323Sed return V >> 1; 967198090Srdivacky if (V != 1) 968193323Sed return -(V >> 1); 969193323Sed // There is no such thing as -0 with integers. "-0" really means MININT. 970193323Sed return 1ULL << 63; 971193323Sed} 972193323Sed 973193323Sed/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 974193323Sed/// values and aliases that we can. 975193323Sedbool BitcodeReader::ResolveGlobalAndAliasInits() { 976193323Sed std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 977193323Sed std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 978198090Srdivacky 979193323Sed GlobalInitWorklist.swap(GlobalInits); 980193323Sed AliasInitWorklist.swap(AliasInits); 981193323Sed 982193323Sed while (!GlobalInitWorklist.empty()) { 983193323Sed unsigned ValID = GlobalInitWorklist.back().second; 984193323Sed if (ValID >= ValueList.size()) { 985193323Sed // Not ready to resolve this yet, it requires something later in the file. 986193323Sed GlobalInits.push_back(GlobalInitWorklist.back()); 987193323Sed } else { 988193323Sed if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 989193323Sed GlobalInitWorklist.back().first->setInitializer(C); 990193323Sed else 991193323Sed return Error("Global variable initializer is not a constant!"); 992193323Sed } 993198090Srdivacky GlobalInitWorklist.pop_back(); 994193323Sed } 995193323Sed 996193323Sed while (!AliasInitWorklist.empty()) { 997193323Sed unsigned ValID = AliasInitWorklist.back().second; 998193323Sed if (ValID >= ValueList.size()) { 999193323Sed AliasInits.push_back(AliasInitWorklist.back()); 1000193323Sed } else { 1001193323Sed if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 1002193323Sed AliasInitWorklist.back().first->setAliasee(C); 1003193323Sed else 1004193323Sed return Error("Alias initializer is not a constant!"); 1005193323Sed } 1006198090Srdivacky AliasInitWorklist.pop_back(); 1007193323Sed } 1008193323Sed return false; 1009193323Sed} 1010193323Sed 1011239462Sdimstatic APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 1012239462Sdim SmallVector<uint64_t, 8> Words(Vals.size()); 1013239462Sdim std::transform(Vals.begin(), Vals.end(), Words.begin(), 1014243830Sdim BitcodeReader::decodeSignRotatedValue); 1015239462Sdim 1016239462Sdim return APInt(TypeBits, Words); 1017239462Sdim} 1018239462Sdim 1019193323Sedbool BitcodeReader::ParseConstants() { 1020193323Sed if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 1021193323Sed return Error("Malformed block record"); 1022193323Sed 1023193323Sed SmallVector<uint64_t, 64> Record; 1024198090Srdivacky 1025193323Sed // Read all the records for this value table. 1026226633Sdim Type *CurTy = Type::getInt32Ty(Context); 1027193323Sed unsigned NextCstNo = ValueList.size(); 1028193323Sed while (1) { 1029249423Sdim BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1030198090Srdivacky 1031249423Sdim switch (Entry.Kind) { 1032249423Sdim case BitstreamEntry::SubBlock: // Handled for us already. 1033249423Sdim case BitstreamEntry::Error: 1034249423Sdim return Error("malformed block record in AST file"); 1035249423Sdim case BitstreamEntry::EndBlock: 1036249423Sdim if (NextCstNo != ValueList.size()) 1037249423Sdim return Error("Invalid constant reference!"); 1038198090Srdivacky 1039249423Sdim // Once all the constants have been read, go through and resolve forward 1040249423Sdim // references. 1041249423Sdim ValueList.ResolveConstantForwardRefs(); 1042249423Sdim return false; 1043249423Sdim case BitstreamEntry::Record: 1044249423Sdim // The interesting case. 1045249423Sdim break; 1046193323Sed } 1047198090Srdivacky 1048193323Sed // Read a record. 1049193323Sed Record.clear(); 1050193323Sed Value *V = 0; 1051249423Sdim unsigned BitCode = Stream.readRecord(Entry.ID, Record); 1052198090Srdivacky switch (BitCode) { 1053193323Sed default: // Default behavior: unknown constant 1054193323Sed case bitc::CST_CODE_UNDEF: // UNDEF 1055193323Sed V = UndefValue::get(CurTy); 1056193323Sed break; 1057193323Sed case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 1058193323Sed if (Record.empty()) 1059193323Sed return Error("Malformed CST_SETTYPE record"); 1060193323Sed if (Record[0] >= TypeList.size()) 1061193323Sed return Error("Invalid Type ID in CST_SETTYPE record"); 1062193323Sed CurTy = TypeList[Record[0]]; 1063193323Sed continue; // Skip the ValueList manipulation. 1064193323Sed case bitc::CST_CODE_NULL: // NULL 1065193323Sed V = Constant::getNullValue(CurTy); 1066193323Sed break; 1067193323Sed case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 1068204642Srdivacky if (!CurTy->isIntegerTy() || Record.empty()) 1069193323Sed return Error("Invalid CST_INTEGER record"); 1070243830Sdim V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 1071193323Sed break; 1072193323Sed case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 1073204642Srdivacky if (!CurTy->isIntegerTy() || Record.empty()) 1074193323Sed return Error("Invalid WIDE_INTEGER record"); 1075198090Srdivacky 1076239462Sdim APInt VInt = ReadWideAPInt(Record, 1077239462Sdim cast<IntegerType>(CurTy)->getBitWidth()); 1078239462Sdim V = ConstantInt::get(Context, VInt); 1079249423Sdim 1080193323Sed break; 1081193323Sed } 1082193323Sed case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 1083193323Sed if (Record.empty()) 1084193323Sed return Error("Invalid FLOAT record"); 1085234353Sdim if (CurTy->isHalfTy()) 1086249423Sdim V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 1087249423Sdim APInt(16, (uint16_t)Record[0]))); 1088234353Sdim else if (CurTy->isFloatTy()) 1089249423Sdim V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 1090249423Sdim APInt(32, (uint32_t)Record[0]))); 1091198090Srdivacky else if (CurTy->isDoubleTy()) 1092249423Sdim V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 1093249423Sdim APInt(64, Record[0]))); 1094198090Srdivacky else if (CurTy->isX86_FP80Ty()) { 1095193323Sed // Bits are not stored the same way as a normal i80 APInt, compensate. 1096193323Sed uint64_t Rearrange[2]; 1097193323Sed Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 1098193323Sed Rearrange[1] = Record[0] >> 48; 1099249423Sdim V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 1100249423Sdim APInt(80, Rearrange))); 1101198090Srdivacky } else if (CurTy->isFP128Ty()) 1102249423Sdim V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 1103249423Sdim APInt(128, Record))); 1104198090Srdivacky else if (CurTy->isPPC_FP128Ty()) 1105249423Sdim V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 1106249423Sdim APInt(128, Record))); 1107193323Sed else 1108193323Sed V = UndefValue::get(CurTy); 1109193323Sed break; 1110193323Sed } 1111198090Srdivacky 1112193323Sed case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 1113193323Sed if (Record.empty()) 1114193323Sed return Error("Invalid CST_AGGREGATE record"); 1115198090Srdivacky 1116193323Sed unsigned Size = Record.size(); 1117234353Sdim SmallVector<Constant*, 16> Elts; 1118198090Srdivacky 1119226633Sdim if (StructType *STy = dyn_cast<StructType>(CurTy)) { 1120193323Sed for (unsigned i = 0; i != Size; ++i) 1121193323Sed Elts.push_back(ValueList.getConstantFwdRef(Record[i], 1122193323Sed STy->getElementType(i))); 1123193323Sed V = ConstantStruct::get(STy, Elts); 1124226633Sdim } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 1125226633Sdim Type *EltTy = ATy->getElementType(); 1126193323Sed for (unsigned i = 0; i != Size; ++i) 1127193323Sed Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1128193323Sed V = ConstantArray::get(ATy, Elts); 1129226633Sdim } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 1130226633Sdim Type *EltTy = VTy->getElementType(); 1131193323Sed for (unsigned i = 0; i != Size; ++i) 1132193323Sed Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1133193323Sed V = ConstantVector::get(Elts); 1134193323Sed } else { 1135193323Sed V = UndefValue::get(CurTy); 1136193323Sed } 1137193323Sed break; 1138193323Sed } 1139234353Sdim case bitc::CST_CODE_STRING: // STRING: [values] 1140234353Sdim case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 1141193323Sed if (Record.empty()) 1142234353Sdim return Error("Invalid CST_STRING record"); 1143193323Sed 1144239462Sdim SmallString<16> Elts(Record.begin(), Record.end()); 1145234353Sdim V = ConstantDataArray::getString(Context, Elts, 1146234353Sdim BitCode == bitc::CST_CODE_CSTRING); 1147193323Sed break; 1148193323Sed } 1149234353Sdim case bitc::CST_CODE_DATA: {// DATA: [n x value] 1150193323Sed if (Record.empty()) 1151234353Sdim return Error("Invalid CST_DATA record"); 1152249423Sdim 1153234353Sdim Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 1154193323Sed unsigned Size = Record.size(); 1155249423Sdim 1156234353Sdim if (EltTy->isIntegerTy(8)) { 1157234353Sdim SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 1158234353Sdim if (isa<VectorType>(CurTy)) 1159234353Sdim V = ConstantDataVector::get(Context, Elts); 1160234353Sdim else 1161234353Sdim V = ConstantDataArray::get(Context, Elts); 1162234353Sdim } else if (EltTy->isIntegerTy(16)) { 1163234353Sdim SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 1164234353Sdim if (isa<VectorType>(CurTy)) 1165234353Sdim V = ConstantDataVector::get(Context, Elts); 1166234353Sdim else 1167234353Sdim V = ConstantDataArray::get(Context, Elts); 1168234353Sdim } else if (EltTy->isIntegerTy(32)) { 1169234353Sdim SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 1170234353Sdim if (isa<VectorType>(CurTy)) 1171234353Sdim V = ConstantDataVector::get(Context, Elts); 1172234353Sdim else 1173234353Sdim V = ConstantDataArray::get(Context, Elts); 1174234353Sdim } else if (EltTy->isIntegerTy(64)) { 1175234353Sdim SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 1176234353Sdim if (isa<VectorType>(CurTy)) 1177234353Sdim V = ConstantDataVector::get(Context, Elts); 1178234353Sdim else 1179234353Sdim V = ConstantDataArray::get(Context, Elts); 1180234353Sdim } else if (EltTy->isFloatTy()) { 1181239462Sdim SmallVector<float, 16> Elts(Size); 1182239462Sdim std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); 1183234353Sdim if (isa<VectorType>(CurTy)) 1184234353Sdim V = ConstantDataVector::get(Context, Elts); 1185234353Sdim else 1186234353Sdim V = ConstantDataArray::get(Context, Elts); 1187234353Sdim } else if (EltTy->isDoubleTy()) { 1188239462Sdim SmallVector<double, 16> Elts(Size); 1189239462Sdim std::transform(Record.begin(), Record.end(), Elts.begin(), 1190239462Sdim BitsToDouble); 1191234353Sdim if (isa<VectorType>(CurTy)) 1192234353Sdim V = ConstantDataVector::get(Context, Elts); 1193234353Sdim else 1194234353Sdim V = ConstantDataArray::get(Context, Elts); 1195234353Sdim } else { 1196234353Sdim return Error("Unknown element type in CE_DATA"); 1197234353Sdim } 1198193323Sed break; 1199193323Sed } 1200234353Sdim 1201193323Sed case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 1202193323Sed if (Record.size() < 3) return Error("Invalid CE_BINOP record"); 1203193323Sed int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 1204193323Sed if (Opc < 0) { 1205193323Sed V = UndefValue::get(CurTy); // Unknown binop. 1206193323Sed } else { 1207193323Sed Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 1208193323Sed Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 1209198090Srdivacky unsigned Flags = 0; 1210198090Srdivacky if (Record.size() >= 4) { 1211198090Srdivacky if (Opc == Instruction::Add || 1212198090Srdivacky Opc == Instruction::Sub || 1213218893Sdim Opc == Instruction::Mul || 1214218893Sdim Opc == Instruction::Shl) { 1215198090Srdivacky if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 1216198090Srdivacky Flags |= OverflowingBinaryOperator::NoSignedWrap; 1217198090Srdivacky if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 1218198090Srdivacky Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 1219218893Sdim } else if (Opc == Instruction::SDiv || 1220218893Sdim Opc == Instruction::UDiv || 1221218893Sdim Opc == Instruction::LShr || 1222218893Sdim Opc == Instruction::AShr) { 1223218893Sdim if (Record[3] & (1 << bitc::PEO_EXACT)) 1224198090Srdivacky Flags |= SDivOperator::IsExact; 1225198090Srdivacky } 1226198090Srdivacky } 1227198090Srdivacky V = ConstantExpr::get(Opc, LHS, RHS, Flags); 1228193323Sed } 1229193323Sed break; 1230198090Srdivacky } 1231193323Sed case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 1232193323Sed if (Record.size() < 3) return Error("Invalid CE_CAST record"); 1233193323Sed int Opc = GetDecodedCastOpcode(Record[0]); 1234193323Sed if (Opc < 0) { 1235193323Sed V = UndefValue::get(CurTy); // Unknown cast. 1236193323Sed } else { 1237226633Sdim Type *OpTy = getTypeByID(Record[1]); 1238193323Sed if (!OpTy) return Error("Invalid CE_CAST record"); 1239193323Sed Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 1240193323Sed V = ConstantExpr::getCast(Opc, Op, CurTy); 1241193323Sed } 1242193323Sed break; 1243198090Srdivacky } 1244198090Srdivacky case bitc::CST_CODE_CE_INBOUNDS_GEP: 1245193323Sed case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 1246193323Sed if (Record.size() & 1) return Error("Invalid CE_GEP record"); 1247193323Sed SmallVector<Constant*, 16> Elts; 1248193323Sed for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1249226633Sdim Type *ElTy = getTypeByID(Record[i]); 1250193323Sed if (!ElTy) return Error("Invalid CE_GEP record"); 1251193323Sed Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 1252193323Sed } 1253226633Sdim ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 1254226633Sdim V = ConstantExpr::getGetElementPtr(Elts[0], Indices, 1255226633Sdim BitCode == 1256226633Sdim bitc::CST_CODE_CE_INBOUNDS_GEP); 1257193323Sed break; 1258193323Sed } 1259193323Sed case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#] 1260193323Sed if (Record.size() < 3) return Error("Invalid CE_SELECT record"); 1261249423Sdim V = ConstantExpr::getSelect( 1262249423Sdim ValueList.getConstantFwdRef(Record[0], 1263249423Sdim Type::getInt1Ty(Context)), 1264249423Sdim ValueList.getConstantFwdRef(Record[1],CurTy), 1265249423Sdim ValueList.getConstantFwdRef(Record[2],CurTy)); 1266193323Sed break; 1267193323Sed case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] 1268193323Sed if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record"); 1269226633Sdim VectorType *OpTy = 1270193323Sed dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1271193323Sed if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record"); 1272193323Sed Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1273249423Sdim Constant *Op1 = ValueList.getConstantFwdRef(Record[2], 1274249423Sdim Type::getInt32Ty(Context)); 1275193323Sed V = ConstantExpr::getExtractElement(Op0, Op1); 1276193323Sed break; 1277193323Sed } 1278193323Sed case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval] 1279226633Sdim VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1280193323Sed if (Record.size() < 3 || OpTy == 0) 1281193323Sed return Error("Invalid CE_INSERTELT record"); 1282193323Sed Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1283193323Sed Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 1284193323Sed OpTy->getElementType()); 1285249423Sdim Constant *Op2 = ValueList.getConstantFwdRef(Record[2], 1286249423Sdim Type::getInt32Ty(Context)); 1287193323Sed V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 1288193323Sed break; 1289193323Sed } 1290193323Sed case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 1291226633Sdim VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1292193323Sed if (Record.size() < 3 || OpTy == 0) 1293193323Sed return Error("Invalid CE_SHUFFLEVEC record"); 1294193323Sed Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1295193323Sed Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 1296226633Sdim Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1297198090Srdivacky OpTy->getNumElements()); 1298193323Sed Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 1299193323Sed V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1300193323Sed break; 1301193323Sed } 1302193323Sed case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 1303226633Sdim VectorType *RTy = dyn_cast<VectorType>(CurTy); 1304226633Sdim VectorType *OpTy = 1305218893Sdim dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1306193323Sed if (Record.size() < 4 || RTy == 0 || OpTy == 0) 1307193323Sed return Error("Invalid CE_SHUFVEC_EX record"); 1308193323Sed Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1309193323Sed Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1310226633Sdim Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1311198090Srdivacky RTy->getNumElements()); 1312193323Sed Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 1313193323Sed V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1314193323Sed break; 1315193323Sed } 1316193323Sed case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 1317193323Sed if (Record.size() < 4) return Error("Invalid CE_CMP record"); 1318226633Sdim Type *OpTy = getTypeByID(Record[0]); 1319193323Sed if (OpTy == 0) return Error("Invalid CE_CMP record"); 1320193323Sed Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1321193323Sed Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1322193323Sed 1323203954Srdivacky if (OpTy->isFPOrFPVectorTy()) 1324193323Sed V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 1325198090Srdivacky else 1326193323Sed V = ConstantExpr::getICmp(Record[3], Op0, Op1); 1327193323Sed break; 1328193323Sed } 1329243830Sdim // This maintains backward compatibility, pre-asm dialect keywords. 1330243830Sdim // FIXME: Remove with the 4.0 release. 1331243830Sdim case bitc::CST_CODE_INLINEASM_OLD: { 1332193323Sed if (Record.size() < 2) return Error("Invalid INLINEASM record"); 1333193323Sed std::string AsmStr, ConstrStr; 1334198090Srdivacky bool HasSideEffects = Record[0] & 1; 1335198396Srdivacky bool IsAlignStack = Record[0] >> 1; 1336193323Sed unsigned AsmStrSize = Record[1]; 1337193323Sed if (2+AsmStrSize >= Record.size()) 1338193323Sed return Error("Invalid INLINEASM record"); 1339193323Sed unsigned ConstStrSize = Record[2+AsmStrSize]; 1340193323Sed if (3+AsmStrSize+ConstStrSize > Record.size()) 1341193323Sed return Error("Invalid INLINEASM record"); 1342198090Srdivacky 1343193323Sed for (unsigned i = 0; i != AsmStrSize; ++i) 1344193323Sed AsmStr += (char)Record[2+i]; 1345193323Sed for (unsigned i = 0; i != ConstStrSize; ++i) 1346193323Sed ConstrStr += (char)Record[3+AsmStrSize+i]; 1347226633Sdim PointerType *PTy = cast<PointerType>(CurTy); 1348193323Sed V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1349198396Srdivacky AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 1350193323Sed break; 1351193323Sed } 1352243830Sdim // This version adds support for the asm dialect keywords (e.g., 1353243830Sdim // inteldialect). 1354243830Sdim case bitc::CST_CODE_INLINEASM: { 1355243830Sdim if (Record.size() < 2) return Error("Invalid INLINEASM record"); 1356243830Sdim std::string AsmStr, ConstrStr; 1357243830Sdim bool HasSideEffects = Record[0] & 1; 1358243830Sdim bool IsAlignStack = (Record[0] >> 1) & 1; 1359243830Sdim unsigned AsmDialect = Record[0] >> 2; 1360243830Sdim unsigned AsmStrSize = Record[1]; 1361243830Sdim if (2+AsmStrSize >= Record.size()) 1362243830Sdim return Error("Invalid INLINEASM record"); 1363243830Sdim unsigned ConstStrSize = Record[2+AsmStrSize]; 1364243830Sdim if (3+AsmStrSize+ConstStrSize > Record.size()) 1365243830Sdim return Error("Invalid INLINEASM record"); 1366243830Sdim 1367243830Sdim for (unsigned i = 0; i != AsmStrSize; ++i) 1368243830Sdim AsmStr += (char)Record[2+i]; 1369243830Sdim for (unsigned i = 0; i != ConstStrSize; ++i) 1370243830Sdim ConstrStr += (char)Record[3+AsmStrSize+i]; 1371243830Sdim PointerType *PTy = cast<PointerType>(CurTy); 1372243830Sdim V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1373243830Sdim AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 1374243830Sdim InlineAsm::AsmDialect(AsmDialect)); 1375243830Sdim break; 1376243830Sdim } 1377198892Srdivacky case bitc::CST_CODE_BLOCKADDRESS:{ 1378198892Srdivacky if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record"); 1379226633Sdim Type *FnTy = getTypeByID(Record[0]); 1380198892Srdivacky if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record"); 1381198892Srdivacky Function *Fn = 1382198892Srdivacky dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 1383198892Srdivacky if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record"); 1384243830Sdim 1385243830Sdim // If the function is already parsed we can insert the block address right 1386243830Sdim // away. 1387243830Sdim if (!Fn->empty()) { 1388243830Sdim Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 1389243830Sdim for (size_t I = 0, E = Record[2]; I != E; ++I) { 1390243830Sdim if (BBI == BBE) 1391243830Sdim return Error("Invalid blockaddress block #"); 1392243830Sdim ++BBI; 1393243830Sdim } 1394243830Sdim V = BlockAddress::get(Fn, BBI); 1395243830Sdim } else { 1396243830Sdim // Otherwise insert a placeholder and remember it so it can be inserted 1397243830Sdim // when the function is parsed. 1398243830Sdim GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(), 1399243830Sdim Type::getInt8Ty(Context), 1400198892Srdivacky false, GlobalValue::InternalLinkage, 1401243830Sdim 0, ""); 1402243830Sdim BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef)); 1403243830Sdim V = FwdRef; 1404243830Sdim } 1405198892Srdivacky break; 1406193323Sed } 1407249423Sdim } 1408198090Srdivacky 1409193323Sed ValueList.AssignValue(V, NextCstNo); 1410193323Sed ++NextCstNo; 1411193323Sed } 1412193323Sed} 1413193323Sed 1414234353Sdimbool BitcodeReader::ParseUseLists() { 1415234353Sdim if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 1416234353Sdim return Error("Malformed block record"); 1417234353Sdim 1418234353Sdim SmallVector<uint64_t, 64> Record; 1419249423Sdim 1420234353Sdim // Read all the records. 1421234353Sdim while (1) { 1422249423Sdim BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1423249423Sdim 1424249423Sdim switch (Entry.Kind) { 1425249423Sdim case BitstreamEntry::SubBlock: // Handled for us already. 1426249423Sdim case BitstreamEntry::Error: 1427249423Sdim return Error("malformed use list block"); 1428249423Sdim case BitstreamEntry::EndBlock: 1429234353Sdim return false; 1430249423Sdim case BitstreamEntry::Record: 1431249423Sdim // The interesting case. 1432249423Sdim break; 1433234353Sdim } 1434249423Sdim 1435234353Sdim // Read a use list record. 1436234353Sdim Record.clear(); 1437249423Sdim switch (Stream.readRecord(Entry.ID, Record)) { 1438234353Sdim default: // Default behavior: unknown type. 1439234353Sdim break; 1440234353Sdim case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD. 1441234353Sdim unsigned RecordLength = Record.size(); 1442234353Sdim if (RecordLength < 1) 1443234353Sdim return Error ("Invalid UseList reader!"); 1444234353Sdim UseListRecords.push_back(Record); 1445234353Sdim break; 1446234353Sdim } 1447234353Sdim } 1448234353Sdim } 1449234353Sdim} 1450234353Sdim 1451193323Sed/// RememberAndSkipFunctionBody - When we see the block for a function body, 1452193323Sed/// remember where it is and then skip it. This lets us lazily deserialize the 1453193323Sed/// functions. 1454193323Sedbool BitcodeReader::RememberAndSkipFunctionBody() { 1455193323Sed // Get the function we are talking about. 1456193323Sed if (FunctionsWithBodies.empty()) 1457193323Sed return Error("Insufficient function protos"); 1458198090Srdivacky 1459193323Sed Function *Fn = FunctionsWithBodies.back(); 1460193323Sed FunctionsWithBodies.pop_back(); 1461198090Srdivacky 1462193323Sed // Save the current stream state. 1463193323Sed uint64_t CurBit = Stream.GetCurrentBitNo(); 1464203954Srdivacky DeferredFunctionInfo[Fn] = CurBit; 1465198090Srdivacky 1466193323Sed // Skip over the function block for now. 1467193323Sed if (Stream.SkipBlock()) 1468193323Sed return Error("Malformed block record"); 1469193323Sed return false; 1470193323Sed} 1471193323Sed 1472234353Sdimbool BitcodeReader::GlobalCleanup() { 1473234353Sdim // Patch the initializers for globals and aliases up. 1474234353Sdim ResolveGlobalAndAliasInits(); 1475234353Sdim if (!GlobalInits.empty() || !AliasInits.empty()) 1476234353Sdim return Error("Malformed global initializer set"); 1477234353Sdim 1478234353Sdim // Look for intrinsic functions which need to be upgraded at some point 1479234353Sdim for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 1480234353Sdim FI != FE; ++FI) { 1481234353Sdim Function *NewFn; 1482234353Sdim if (UpgradeIntrinsicFunction(FI, NewFn)) 1483234353Sdim UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 1484234353Sdim } 1485234353Sdim 1486234353Sdim // Look for global variables which need to be renamed. 1487234353Sdim for (Module::global_iterator 1488234353Sdim GI = TheModule->global_begin(), GE = TheModule->global_end(); 1489234353Sdim GI != GE; ++GI) 1490234353Sdim UpgradeGlobalVariable(GI); 1491234353Sdim // Force deallocation of memory for these vectors to favor the client that 1492234353Sdim // want lazy deserialization. 1493234353Sdim std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 1494234353Sdim std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 1495234353Sdim return false; 1496234353Sdim} 1497234353Sdim 1498234353Sdimbool BitcodeReader::ParseModule(bool Resume) { 1499234353Sdim if (Resume) 1500234353Sdim Stream.JumpToBit(NextUnreadBit); 1501234353Sdim else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 1502193323Sed return Error("Malformed block record"); 1503193323Sed 1504193323Sed SmallVector<uint64_t, 64> Record; 1505193323Sed std::vector<std::string> SectionTable; 1506193323Sed std::vector<std::string> GCTable; 1507193323Sed 1508193323Sed // Read all the records for this module. 1509249423Sdim while (1) { 1510249423Sdim BitstreamEntry Entry = Stream.advance(); 1511193323Sed 1512249423Sdim switch (Entry.Kind) { 1513249423Sdim case BitstreamEntry::Error: 1514249423Sdim Error("malformed module block"); 1515249423Sdim return true; 1516249423Sdim case BitstreamEntry::EndBlock: 1517234353Sdim return GlobalCleanup(); 1518198090Srdivacky 1519249423Sdim case BitstreamEntry::SubBlock: 1520249423Sdim switch (Entry.ID) { 1521193323Sed default: // Skip unknown content. 1522193323Sed if (Stream.SkipBlock()) 1523193323Sed return Error("Malformed block record"); 1524193323Sed break; 1525193323Sed case bitc::BLOCKINFO_BLOCK_ID: 1526193323Sed if (Stream.ReadBlockInfoBlock()) 1527193323Sed return Error("Malformed BlockInfoBlock"); 1528193323Sed break; 1529193323Sed case bitc::PARAMATTR_BLOCK_ID: 1530193323Sed if (ParseAttributeBlock()) 1531193323Sed return true; 1532193323Sed break; 1533249423Sdim case bitc::PARAMATTR_GROUP_BLOCK_ID: 1534249423Sdim if (ParseAttributeGroupBlock()) 1535249423Sdim return true; 1536249423Sdim break; 1537224145Sdim case bitc::TYPE_BLOCK_ID_NEW: 1538193323Sed if (ParseTypeTable()) 1539193323Sed return true; 1540193323Sed break; 1541193323Sed case bitc::VALUE_SYMTAB_BLOCK_ID: 1542193323Sed if (ParseValueSymbolTable()) 1543193323Sed return true; 1544234353Sdim SeenValueSymbolTable = true; 1545193323Sed break; 1546193323Sed case bitc::CONSTANTS_BLOCK_ID: 1547193323Sed if (ParseConstants() || ResolveGlobalAndAliasInits()) 1548193323Sed return true; 1549193323Sed break; 1550198090Srdivacky case bitc::METADATA_BLOCK_ID: 1551198090Srdivacky if (ParseMetadata()) 1552198090Srdivacky return true; 1553198090Srdivacky break; 1554193323Sed case bitc::FUNCTION_BLOCK_ID: 1555193323Sed // If this is the first function body we've seen, reverse the 1556193323Sed // FunctionsWithBodies list. 1557234353Sdim if (!SeenFirstFunctionBody) { 1558193323Sed std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 1559234353Sdim if (GlobalCleanup()) 1560234353Sdim return true; 1561234353Sdim SeenFirstFunctionBody = true; 1562193323Sed } 1563198090Srdivacky 1564193323Sed if (RememberAndSkipFunctionBody()) 1565193323Sed return true; 1566234353Sdim // For streaming bitcode, suspend parsing when we reach the function 1567234353Sdim // bodies. Subsequent materialization calls will resume it when 1568234353Sdim // necessary. For streaming, the function bodies must be at the end of 1569234353Sdim // the bitcode. If the bitcode file is old, the symbol table will be 1570234353Sdim // at the end instead and will not have been seen yet. In this case, 1571234353Sdim // just finish the parse now. 1572234353Sdim if (LazyStreamer && SeenValueSymbolTable) { 1573234353Sdim NextUnreadBit = Stream.GetCurrentBitNo(); 1574234353Sdim return false; 1575234353Sdim } 1576193323Sed break; 1577234353Sdim case bitc::USELIST_BLOCK_ID: 1578234353Sdim if (ParseUseLists()) 1579234353Sdim return true; 1580234353Sdim break; 1581193323Sed } 1582193323Sed continue; 1583198090Srdivacky 1584249423Sdim case BitstreamEntry::Record: 1585249423Sdim // The interesting case. 1586249423Sdim break; 1587193323Sed } 1588198090Srdivacky 1589249423Sdim 1590193323Sed // Read a record. 1591249423Sdim switch (Stream.readRecord(Entry.ID, Record)) { 1592193323Sed default: break; // Default behavior, ignore unknown content. 1593243830Sdim case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 1594193323Sed if (Record.size() < 1) 1595193323Sed return Error("Malformed MODULE_CODE_VERSION"); 1596243830Sdim // Only version #0 and #1 are supported so far. 1597243830Sdim unsigned module_version = Record[0]; 1598243830Sdim switch (module_version) { 1599243830Sdim default: return Error("Unknown bitstream version!"); 1600243830Sdim case 0: 1601243830Sdim UseRelativeIDs = false; 1602243830Sdim break; 1603243830Sdim case 1: 1604243830Sdim UseRelativeIDs = true; 1605243830Sdim break; 1606243830Sdim } 1607193323Sed break; 1608243830Sdim } 1609193323Sed case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 1610193323Sed std::string S; 1611193323Sed if (ConvertToString(Record, 0, S)) 1612193323Sed return Error("Invalid MODULE_CODE_TRIPLE record"); 1613193323Sed TheModule->setTargetTriple(S); 1614193323Sed break; 1615193323Sed } 1616193323Sed case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 1617193323Sed std::string S; 1618193323Sed if (ConvertToString(Record, 0, S)) 1619193323Sed return Error("Invalid MODULE_CODE_DATALAYOUT record"); 1620193323Sed TheModule->setDataLayout(S); 1621193323Sed break; 1622193323Sed } 1623193323Sed case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 1624193323Sed std::string S; 1625193323Sed if (ConvertToString(Record, 0, S)) 1626193323Sed return Error("Invalid MODULE_CODE_ASM record"); 1627193323Sed TheModule->setModuleInlineAsm(S); 1628193323Sed break; 1629193323Sed } 1630193323Sed case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 1631249423Sdim // FIXME: Remove in 4.0. 1632193323Sed std::string S; 1633193323Sed if (ConvertToString(Record, 0, S)) 1634193323Sed return Error("Invalid MODULE_CODE_DEPLIB record"); 1635249423Sdim // Ignore value. 1636193323Sed break; 1637193323Sed } 1638193323Sed case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 1639193323Sed std::string S; 1640193323Sed if (ConvertToString(Record, 0, S)) 1641193323Sed return Error("Invalid MODULE_CODE_SECTIONNAME record"); 1642193323Sed SectionTable.push_back(S); 1643193323Sed break; 1644193323Sed } 1645193323Sed case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 1646193323Sed std::string S; 1647193323Sed if (ConvertToString(Record, 0, S)) 1648193323Sed return Error("Invalid MODULE_CODE_GCNAME record"); 1649193323Sed GCTable.push_back(S); 1650193323Sed break; 1651193323Sed } 1652193323Sed // GLOBALVAR: [pointer type, isconst, initid, 1653218893Sdim // linkage, alignment, section, visibility, threadlocal, 1654218893Sdim // unnamed_addr] 1655193323Sed case bitc::MODULE_CODE_GLOBALVAR: { 1656193323Sed if (Record.size() < 6) 1657193323Sed return Error("Invalid MODULE_CODE_GLOBALVAR record"); 1658226633Sdim Type *Ty = getTypeByID(Record[0]); 1659218893Sdim if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record"); 1660204642Srdivacky if (!Ty->isPointerTy()) 1661193323Sed return Error("Global not a pointer type!"); 1662193323Sed unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 1663193323Sed Ty = cast<PointerType>(Ty)->getElementType(); 1664198090Srdivacky 1665193323Sed bool isConstant = Record[1]; 1666193323Sed GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 1667193323Sed unsigned Alignment = (1 << Record[4]) >> 1; 1668193323Sed std::string Section; 1669193323Sed if (Record[5]) { 1670193323Sed if (Record[5]-1 >= SectionTable.size()) 1671193323Sed return Error("Invalid section ID"); 1672193323Sed Section = SectionTable[Record[5]-1]; 1673193323Sed } 1674193323Sed GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 1675193323Sed if (Record.size() > 6) 1676193323Sed Visibility = GetDecodedVisibility(Record[6]); 1677239462Sdim 1678239462Sdim GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 1679193323Sed if (Record.size() > 7) 1680239462Sdim TLM = GetDecodedThreadLocalMode(Record[7]); 1681193323Sed 1682218893Sdim bool UnnamedAddr = false; 1683218893Sdim if (Record.size() > 8) 1684218893Sdim UnnamedAddr = Record[8]; 1685218893Sdim 1686249423Sdim bool ExternallyInitialized = false; 1687249423Sdim if (Record.size() > 9) 1688249423Sdim ExternallyInitialized = Record[9]; 1689249423Sdim 1690193323Sed GlobalVariable *NewGV = 1691198090Srdivacky new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0, 1692249423Sdim TLM, AddressSpace, ExternallyInitialized); 1693193323Sed NewGV->setAlignment(Alignment); 1694193323Sed if (!Section.empty()) 1695193323Sed NewGV->setSection(Section); 1696193323Sed NewGV->setVisibility(Visibility); 1697218893Sdim NewGV->setUnnamedAddr(UnnamedAddr); 1698198090Srdivacky 1699193323Sed ValueList.push_back(NewGV); 1700198090Srdivacky 1701193323Sed // Remember which value to use for the global initializer. 1702193323Sed if (unsigned InitID = Record[2]) 1703193323Sed GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 1704193323Sed break; 1705193323Sed } 1706193323Sed // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 1707218893Sdim // alignment, section, visibility, gc, unnamed_addr] 1708193323Sed case bitc::MODULE_CODE_FUNCTION: { 1709193323Sed if (Record.size() < 8) 1710193323Sed return Error("Invalid MODULE_CODE_FUNCTION record"); 1711226633Sdim Type *Ty = getTypeByID(Record[0]); 1712218893Sdim if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record"); 1713204642Srdivacky if (!Ty->isPointerTy()) 1714193323Sed return Error("Function not a pointer type!"); 1715226633Sdim FunctionType *FTy = 1716193323Sed dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 1717193323Sed if (!FTy) 1718193323Sed return Error("Function not a pointer to function type!"); 1719193323Sed 1720193323Sed Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 1721193323Sed "", TheModule); 1722193323Sed 1723198090Srdivacky Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 1724193323Sed bool isProto = Record[2]; 1725193323Sed Func->setLinkage(GetDecodedLinkage(Record[3])); 1726193323Sed Func->setAttributes(getAttributes(Record[4])); 1727198090Srdivacky 1728193323Sed Func->setAlignment((1 << Record[5]) >> 1); 1729193323Sed if (Record[6]) { 1730193323Sed if (Record[6]-1 >= SectionTable.size()) 1731193323Sed return Error("Invalid section ID"); 1732193323Sed Func->setSection(SectionTable[Record[6]-1]); 1733193323Sed } 1734193323Sed Func->setVisibility(GetDecodedVisibility(Record[7])); 1735193323Sed if (Record.size() > 8 && Record[8]) { 1736193323Sed if (Record[8]-1 > GCTable.size()) 1737193323Sed return Error("Invalid GC ID"); 1738193323Sed Func->setGC(GCTable[Record[8]-1].c_str()); 1739193323Sed } 1740218893Sdim bool UnnamedAddr = false; 1741218893Sdim if (Record.size() > 9) 1742218893Sdim UnnamedAddr = Record[9]; 1743218893Sdim Func->setUnnamedAddr(UnnamedAddr); 1744193323Sed ValueList.push_back(Func); 1745198090Srdivacky 1746193323Sed // If this is a function with a body, remember the prototype we are 1747193323Sed // creating now, so that we can match up the body with them later. 1748234353Sdim if (!isProto) { 1749193323Sed FunctionsWithBodies.push_back(Func); 1750234353Sdim if (LazyStreamer) DeferredFunctionInfo[Func] = 0; 1751234353Sdim } 1752193323Sed break; 1753193323Sed } 1754193323Sed // ALIAS: [alias type, aliasee val#, linkage] 1755193323Sed // ALIAS: [alias type, aliasee val#, linkage, visibility] 1756193323Sed case bitc::MODULE_CODE_ALIAS: { 1757193323Sed if (Record.size() < 3) 1758193323Sed return Error("Invalid MODULE_ALIAS record"); 1759226633Sdim Type *Ty = getTypeByID(Record[0]); 1760218893Sdim if (!Ty) return Error("Invalid MODULE_ALIAS record"); 1761204642Srdivacky if (!Ty->isPointerTy()) 1762193323Sed return Error("Function not a pointer type!"); 1763198090Srdivacky 1764193323Sed GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]), 1765193323Sed "", 0, TheModule); 1766193323Sed // Old bitcode files didn't have visibility field. 1767193323Sed if (Record.size() > 3) 1768193323Sed NewGA->setVisibility(GetDecodedVisibility(Record[3])); 1769193323Sed ValueList.push_back(NewGA); 1770193323Sed AliasInits.push_back(std::make_pair(NewGA, Record[1])); 1771193323Sed break; 1772193323Sed } 1773193323Sed /// MODULE_CODE_PURGEVALS: [numvals] 1774193323Sed case bitc::MODULE_CODE_PURGEVALS: 1775193323Sed // Trim down the value list to the specified size. 1776193323Sed if (Record.size() < 1 || Record[0] > ValueList.size()) 1777193323Sed return Error("Invalid MODULE_PURGEVALS record"); 1778193323Sed ValueList.shrinkTo(Record[0]); 1779193323Sed break; 1780193323Sed } 1781193323Sed Record.clear(); 1782193323Sed } 1783193323Sed} 1784193323Sed 1785203954Srdivackybool BitcodeReader::ParseBitcodeInto(Module *M) { 1786193323Sed TheModule = 0; 1787198090Srdivacky 1788234353Sdim if (InitStream()) return true; 1789198090Srdivacky 1790193323Sed // Sniff for the signature. 1791193323Sed if (Stream.Read(8) != 'B' || 1792193323Sed Stream.Read(8) != 'C' || 1793193323Sed Stream.Read(4) != 0x0 || 1794193323Sed Stream.Read(4) != 0xC || 1795193323Sed Stream.Read(4) != 0xE || 1796193323Sed Stream.Read(4) != 0xD) 1797193323Sed return Error("Invalid bitcode signature"); 1798198090Srdivacky 1799193323Sed // We expect a number of well-defined blocks, though we don't necessarily 1800193323Sed // need to understand them all. 1801249423Sdim while (1) { 1802249423Sdim if (Stream.AtEndOfStream()) 1803249423Sdim return false; 1804198090Srdivacky 1805249423Sdim BitstreamEntry Entry = 1806249423Sdim Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 1807223017Sdim 1808249423Sdim switch (Entry.Kind) { 1809249423Sdim case BitstreamEntry::Error: 1810249423Sdim Error("malformed module file"); 1811249423Sdim return true; 1812249423Sdim case BitstreamEntry::EndBlock: 1813249423Sdim return false; 1814249423Sdim 1815249423Sdim case BitstreamEntry::SubBlock: 1816249423Sdim switch (Entry.ID) { 1817249423Sdim case bitc::BLOCKINFO_BLOCK_ID: 1818249423Sdim if (Stream.ReadBlockInfoBlock()) 1819249423Sdim return Error("Malformed BlockInfoBlock"); 1820249423Sdim break; 1821249423Sdim case bitc::MODULE_BLOCK_ID: 1822249423Sdim // Reject multiple MODULE_BLOCK's in a single bitstream. 1823249423Sdim if (TheModule) 1824249423Sdim return Error("Multiple MODULE_BLOCKs in same stream"); 1825249423Sdim TheModule = M; 1826249423Sdim if (ParseModule(false)) 1827249423Sdim return true; 1828249423Sdim if (LazyStreamer) return false; 1829249423Sdim break; 1830249423Sdim default: 1831249423Sdim if (Stream.SkipBlock()) 1832249423Sdim return Error("Malformed block record"); 1833249423Sdim break; 1834249423Sdim } 1835249423Sdim continue; 1836249423Sdim case BitstreamEntry::Record: 1837249423Sdim // There should be no records in the top-level of blocks. 1838249423Sdim 1839249423Sdim // The ranlib in Xcode 4 will align archive members by appending newlines 1840226633Sdim // to the end of them. If this file size is a multiple of 4 but not 8, we 1841226633Sdim // have to read and ignore these final 4 bytes :-( 1842249423Sdim if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 && 1843223017Sdim Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a && 1844239462Sdim Stream.AtEndOfStream()) 1845223017Sdim return false; 1846223017Sdim 1847193323Sed return Error("Invalid record at top-level"); 1848223017Sdim } 1849193323Sed } 1850193323Sed} 1851193323Sed 1852218893Sdimbool BitcodeReader::ParseModuleTriple(std::string &Triple) { 1853218893Sdim if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 1854218893Sdim return Error("Malformed block record"); 1855218893Sdim 1856218893Sdim SmallVector<uint64_t, 64> Record; 1857218893Sdim 1858218893Sdim // Read all the records for this module. 1859249423Sdim while (1) { 1860249423Sdim BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1861218893Sdim 1862249423Sdim switch (Entry.Kind) { 1863249423Sdim case BitstreamEntry::SubBlock: // Handled for us already. 1864249423Sdim case BitstreamEntry::Error: 1865249423Sdim return Error("malformed module block"); 1866249423Sdim case BitstreamEntry::EndBlock: 1867218893Sdim return false; 1868249423Sdim case BitstreamEntry::Record: 1869249423Sdim // The interesting case. 1870249423Sdim break; 1871218893Sdim } 1872218893Sdim 1873218893Sdim // Read a record. 1874249423Sdim switch (Stream.readRecord(Entry.ID, Record)) { 1875218893Sdim default: break; // Default behavior, ignore unknown content. 1876218893Sdim case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 1877218893Sdim std::string S; 1878218893Sdim if (ConvertToString(Record, 0, S)) 1879218893Sdim return Error("Invalid MODULE_CODE_TRIPLE record"); 1880218893Sdim Triple = S; 1881218893Sdim break; 1882218893Sdim } 1883218893Sdim } 1884218893Sdim Record.clear(); 1885218893Sdim } 1886218893Sdim} 1887218893Sdim 1888218893Sdimbool BitcodeReader::ParseTriple(std::string &Triple) { 1889234353Sdim if (InitStream()) return true; 1890218893Sdim 1891218893Sdim // Sniff for the signature. 1892218893Sdim if (Stream.Read(8) != 'B' || 1893218893Sdim Stream.Read(8) != 'C' || 1894218893Sdim Stream.Read(4) != 0x0 || 1895218893Sdim Stream.Read(4) != 0xC || 1896218893Sdim Stream.Read(4) != 0xE || 1897218893Sdim Stream.Read(4) != 0xD) 1898218893Sdim return Error("Invalid bitcode signature"); 1899218893Sdim 1900218893Sdim // We expect a number of well-defined blocks, though we don't necessarily 1901218893Sdim // need to understand them all. 1902249423Sdim while (1) { 1903249423Sdim BitstreamEntry Entry = Stream.advance(); 1904218893Sdim 1905249423Sdim switch (Entry.Kind) { 1906249423Sdim case BitstreamEntry::Error: 1907249423Sdim Error("malformed module file"); 1908249423Sdim return true; 1909249423Sdim case BitstreamEntry::EndBlock: 1910249423Sdim return false; 1911218893Sdim 1912249423Sdim case BitstreamEntry::SubBlock: 1913249423Sdim if (Entry.ID == bitc::MODULE_BLOCK_ID) 1914249423Sdim return ParseModuleTriple(Triple); 1915218893Sdim 1916249423Sdim // Ignore other sub-blocks. 1917249423Sdim if (Stream.SkipBlock()) { 1918249423Sdim Error("malformed block record in AST file"); 1919218893Sdim return true; 1920249423Sdim } 1921249423Sdim continue; 1922249423Sdim 1923249423Sdim case BitstreamEntry::Record: 1924249423Sdim Stream.skipRecord(Entry.ID); 1925249423Sdim continue; 1926218893Sdim } 1927218893Sdim } 1928218893Sdim} 1929218893Sdim 1930198090Srdivacky/// ParseMetadataAttachment - Parse metadata attachments. 1931198090Srdivackybool BitcodeReader::ParseMetadataAttachment() { 1932198090Srdivacky if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 1933198090Srdivacky return Error("Malformed block record"); 1934193323Sed 1935198090Srdivacky SmallVector<uint64_t, 64> Record; 1936249423Sdim while (1) { 1937249423Sdim BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1938249423Sdim 1939249423Sdim switch (Entry.Kind) { 1940249423Sdim case BitstreamEntry::SubBlock: // Handled for us already. 1941249423Sdim case BitstreamEntry::Error: 1942249423Sdim return Error("malformed metadata block"); 1943249423Sdim case BitstreamEntry::EndBlock: 1944249423Sdim return false; 1945249423Sdim case BitstreamEntry::Record: 1946249423Sdim // The interesting case. 1947198090Srdivacky break; 1948198090Srdivacky } 1949249423Sdim 1950198090Srdivacky // Read a metadata attachment record. 1951198090Srdivacky Record.clear(); 1952249423Sdim switch (Stream.readRecord(Entry.ID, Record)) { 1953198090Srdivacky default: // Default behavior: ignore. 1954198090Srdivacky break; 1955224145Sdim case bitc::METADATA_ATTACHMENT: { 1956198090Srdivacky unsigned RecordLength = Record.size(); 1957198090Srdivacky if (Record.empty() || (RecordLength - 1) % 2 == 1) 1958198090Srdivacky return Error ("Invalid METADATA_ATTACHMENT reader!"); 1959198090Srdivacky Instruction *Inst = InstructionList[Record[0]]; 1960198090Srdivacky for (unsigned i = 1; i != RecordLength; i = i+2) { 1961198090Srdivacky unsigned Kind = Record[i]; 1962212904Sdim DenseMap<unsigned, unsigned>::iterator I = 1963212904Sdim MDKindMap.find(Kind); 1964212904Sdim if (I == MDKindMap.end()) 1965212904Sdim return Error("Invalid metadata kind ID"); 1966198090Srdivacky Value *Node = MDValueList.getValueFwdRef(Record[i+1]); 1967212904Sdim Inst->setMetadata(I->second, cast<MDNode>(Node)); 1968198090Srdivacky } 1969198090Srdivacky break; 1970198090Srdivacky } 1971198090Srdivacky } 1972198090Srdivacky } 1973198090Srdivacky} 1974198090Srdivacky 1975193323Sed/// ParseFunctionBody - Lazily parse the specified function body block. 1976193323Sedbool BitcodeReader::ParseFunctionBody(Function *F) { 1977193323Sed if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 1978193323Sed return Error("Malformed block record"); 1979198090Srdivacky 1980204642Srdivacky InstructionList.clear(); 1981193323Sed unsigned ModuleValueListSize = ValueList.size(); 1982212904Sdim unsigned ModuleMDValueListSize = MDValueList.size(); 1983198090Srdivacky 1984193323Sed // Add all the function arguments to the value table. 1985193323Sed for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 1986193323Sed ValueList.push_back(I); 1987198090Srdivacky 1988193323Sed unsigned NextValueNo = ValueList.size(); 1989193323Sed BasicBlock *CurBB = 0; 1990193323Sed unsigned CurBBNo = 0; 1991193323Sed 1992206124Srdivacky DebugLoc LastLoc; 1993249423Sdim 1994193323Sed // Read all the records. 1995193323Sed SmallVector<uint64_t, 64> Record; 1996193323Sed while (1) { 1997249423Sdim BitstreamEntry Entry = Stream.advance(); 1998198090Srdivacky 1999249423Sdim switch (Entry.Kind) { 2000249423Sdim case BitstreamEntry::Error: 2001249423Sdim return Error("Bitcode error in function block"); 2002249423Sdim case BitstreamEntry::EndBlock: 2003249423Sdim goto OutOfRecordLoop; 2004249423Sdim 2005249423Sdim case BitstreamEntry::SubBlock: 2006249423Sdim switch (Entry.ID) { 2007193323Sed default: // Skip unknown content. 2008193323Sed if (Stream.SkipBlock()) 2009193323Sed return Error("Malformed block record"); 2010193323Sed break; 2011193323Sed case bitc::CONSTANTS_BLOCK_ID: 2012193323Sed if (ParseConstants()) return true; 2013193323Sed NextValueNo = ValueList.size(); 2014193323Sed break; 2015193323Sed case bitc::VALUE_SYMTAB_BLOCK_ID: 2016193323Sed if (ParseValueSymbolTable()) return true; 2017193323Sed break; 2018198090Srdivacky case bitc::METADATA_ATTACHMENT_ID: 2019198090Srdivacky if (ParseMetadataAttachment()) return true; 2020198090Srdivacky break; 2021202375Srdivacky case bitc::METADATA_BLOCK_ID: 2022202375Srdivacky if (ParseMetadata()) return true; 2023202375Srdivacky break; 2024193323Sed } 2025193323Sed continue; 2026198090Srdivacky 2027249423Sdim case BitstreamEntry::Record: 2028249423Sdim // The interesting case. 2029249423Sdim break; 2030193323Sed } 2031198090Srdivacky 2032193323Sed // Read a record. 2033193323Sed Record.clear(); 2034193323Sed Instruction *I = 0; 2035249423Sdim unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2036198090Srdivacky switch (BitCode) { 2037193323Sed default: // Default behavior: reject 2038193323Sed return Error("Unknown instruction"); 2039193323Sed case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 2040193323Sed if (Record.size() < 1 || Record[0] == 0) 2041193323Sed return Error("Invalid DECLAREBLOCKS record"); 2042193323Sed // Create all the basic blocks for the function. 2043193323Sed FunctionBBs.resize(Record[0]); 2044193323Sed for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 2045198090Srdivacky FunctionBBs[i] = BasicBlock::Create(Context, "", F); 2046193323Sed CurBB = FunctionBBs[0]; 2047193323Sed continue; 2048249423Sdim 2049206124Srdivacky case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 2050206124Srdivacky // This record indicates that the last instruction is at the same 2051206124Srdivacky // location as the previous instruction with a location. 2052206124Srdivacky I = 0; 2053249423Sdim 2054206124Srdivacky // Get the last instruction emitted. 2055206124Srdivacky if (CurBB && !CurBB->empty()) 2056206124Srdivacky I = &CurBB->back(); 2057206124Srdivacky else if (CurBBNo && FunctionBBs[CurBBNo-1] && 2058206124Srdivacky !FunctionBBs[CurBBNo-1]->empty()) 2059206124Srdivacky I = &FunctionBBs[CurBBNo-1]->back(); 2060249423Sdim 2061206124Srdivacky if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record"); 2062206124Srdivacky I->setDebugLoc(LastLoc); 2063206124Srdivacky I = 0; 2064206124Srdivacky continue; 2065249423Sdim 2066224145Sdim case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 2067206124Srdivacky I = 0; // Get the last instruction emitted. 2068206124Srdivacky if (CurBB && !CurBB->empty()) 2069206124Srdivacky I = &CurBB->back(); 2070206124Srdivacky else if (CurBBNo && FunctionBBs[CurBBNo-1] && 2071206124Srdivacky !FunctionBBs[CurBBNo-1]->empty()) 2072206124Srdivacky I = &FunctionBBs[CurBBNo-1]->back(); 2073206124Srdivacky if (I == 0 || Record.size() < 4) 2074206124Srdivacky return Error("Invalid FUNC_CODE_DEBUG_LOC record"); 2075249423Sdim 2076206124Srdivacky unsigned Line = Record[0], Col = Record[1]; 2077206124Srdivacky unsigned ScopeID = Record[2], IAID = Record[3]; 2078249423Sdim 2079206124Srdivacky MDNode *Scope = 0, *IA = 0; 2080206124Srdivacky if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1)); 2081206124Srdivacky if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1)); 2082206124Srdivacky LastLoc = DebugLoc::get(Line, Col, Scope, IA); 2083206124Srdivacky I->setDebugLoc(LastLoc); 2084206124Srdivacky I = 0; 2085206124Srdivacky continue; 2086206124Srdivacky } 2087206124Srdivacky 2088193323Sed case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 2089193323Sed unsigned OpNum = 0; 2090193323Sed Value *LHS, *RHS; 2091193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2092243830Sdim popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2093198090Srdivacky OpNum+1 > Record.size()) 2094193323Sed return Error("Invalid BINOP record"); 2095198090Srdivacky 2096198090Srdivacky int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 2097193323Sed if (Opc == -1) return Error("Invalid BINOP record"); 2098193323Sed I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 2099198090Srdivacky InstructionList.push_back(I); 2100198090Srdivacky if (OpNum < Record.size()) { 2101198090Srdivacky if (Opc == Instruction::Add || 2102198090Srdivacky Opc == Instruction::Sub || 2103218893Sdim Opc == Instruction::Mul || 2104218893Sdim Opc == Instruction::Shl) { 2105203954Srdivacky if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2106198090Srdivacky cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 2107203954Srdivacky if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2108198090Srdivacky cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 2109218893Sdim } else if (Opc == Instruction::SDiv || 2110218893Sdim Opc == Instruction::UDiv || 2111218893Sdim Opc == Instruction::LShr || 2112218893Sdim Opc == Instruction::AShr) { 2113218893Sdim if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 2114198090Srdivacky cast<BinaryOperator>(I)->setIsExact(true); 2115249423Sdim } else if (isa<FPMathOperator>(I)) { 2116249423Sdim FastMathFlags FMF; 2117249423Sdim if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra)) 2118249423Sdim FMF.setUnsafeAlgebra(); 2119249423Sdim if (0 != (Record[OpNum] & FastMathFlags::NoNaNs)) 2120249423Sdim FMF.setNoNaNs(); 2121249423Sdim if (0 != (Record[OpNum] & FastMathFlags::NoInfs)) 2122249423Sdim FMF.setNoInfs(); 2123249423Sdim if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros)) 2124249423Sdim FMF.setNoSignedZeros(); 2125249423Sdim if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal)) 2126249423Sdim FMF.setAllowReciprocal(); 2127249423Sdim if (FMF.any()) 2128249423Sdim I->setFastMathFlags(FMF); 2129198090Srdivacky } 2130249423Sdim 2131198090Srdivacky } 2132193323Sed break; 2133193323Sed } 2134193323Sed case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 2135193323Sed unsigned OpNum = 0; 2136193323Sed Value *Op; 2137193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2138193323Sed OpNum+2 != Record.size()) 2139193323Sed return Error("Invalid CAST record"); 2140198090Srdivacky 2141226633Sdim Type *ResTy = getTypeByID(Record[OpNum]); 2142193323Sed int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 2143193323Sed if (Opc == -1 || ResTy == 0) 2144193323Sed return Error("Invalid CAST record"); 2145193323Sed I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 2146198090Srdivacky InstructionList.push_back(I); 2147193323Sed break; 2148193323Sed } 2149198090Srdivacky case bitc::FUNC_CODE_INST_INBOUNDS_GEP: 2150193323Sed case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 2151193323Sed unsigned OpNum = 0; 2152193323Sed Value *BasePtr; 2153193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 2154193323Sed return Error("Invalid GEP record"); 2155193323Sed 2156193323Sed SmallVector<Value*, 16> GEPIdx; 2157193323Sed while (OpNum != Record.size()) { 2158193323Sed Value *Op; 2159193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2160193323Sed return Error("Invalid GEP record"); 2161193323Sed GEPIdx.push_back(Op); 2162193323Sed } 2163193323Sed 2164226633Sdim I = GetElementPtrInst::Create(BasePtr, GEPIdx); 2165198090Srdivacky InstructionList.push_back(I); 2166198090Srdivacky if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP) 2167198090Srdivacky cast<GetElementPtrInst>(I)->setIsInBounds(true); 2168193323Sed break; 2169193323Sed } 2170198090Srdivacky 2171193323Sed case bitc::FUNC_CODE_INST_EXTRACTVAL: { 2172193323Sed // EXTRACTVAL: [opty, opval, n x indices] 2173193323Sed unsigned OpNum = 0; 2174193323Sed Value *Agg; 2175193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2176193323Sed return Error("Invalid EXTRACTVAL record"); 2177193323Sed 2178193323Sed SmallVector<unsigned, 4> EXTRACTVALIdx; 2179193323Sed for (unsigned RecSize = Record.size(); 2180193323Sed OpNum != RecSize; ++OpNum) { 2181193323Sed uint64_t Index = Record[OpNum]; 2182193323Sed if ((unsigned)Index != Index) 2183193323Sed return Error("Invalid EXTRACTVAL index"); 2184193323Sed EXTRACTVALIdx.push_back((unsigned)Index); 2185193323Sed } 2186193323Sed 2187224145Sdim I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 2188198090Srdivacky InstructionList.push_back(I); 2189193323Sed break; 2190193323Sed } 2191198090Srdivacky 2192193323Sed case bitc::FUNC_CODE_INST_INSERTVAL: { 2193193323Sed // INSERTVAL: [opty, opval, opty, opval, n x indices] 2194193323Sed unsigned OpNum = 0; 2195193323Sed Value *Agg; 2196193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2197193323Sed return Error("Invalid INSERTVAL record"); 2198193323Sed Value *Val; 2199193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 2200193323Sed return Error("Invalid INSERTVAL record"); 2201193323Sed 2202193323Sed SmallVector<unsigned, 4> INSERTVALIdx; 2203193323Sed for (unsigned RecSize = Record.size(); 2204193323Sed OpNum != RecSize; ++OpNum) { 2205193323Sed uint64_t Index = Record[OpNum]; 2206193323Sed if ((unsigned)Index != Index) 2207193323Sed return Error("Invalid INSERTVAL index"); 2208193323Sed INSERTVALIdx.push_back((unsigned)Index); 2209193323Sed } 2210193323Sed 2211224145Sdim I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 2212198090Srdivacky InstructionList.push_back(I); 2213193323Sed break; 2214193323Sed } 2215198090Srdivacky 2216193323Sed case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 2217193323Sed // obsolete form of select 2218193323Sed // handles select i1 ... in old bitcode 2219193323Sed unsigned OpNum = 0; 2220193323Sed Value *TrueVal, *FalseVal, *Cond; 2221193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2222243830Sdim popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 2223243830Sdim popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 2224193323Sed return Error("Invalid SELECT record"); 2225198090Srdivacky 2226193323Sed I = SelectInst::Create(Cond, TrueVal, FalseVal); 2227198090Srdivacky InstructionList.push_back(I); 2228193323Sed break; 2229193323Sed } 2230198090Srdivacky 2231193323Sed case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 2232193323Sed // new form of select 2233193323Sed // handles select i1 or select [N x i1] 2234193323Sed unsigned OpNum = 0; 2235193323Sed Value *TrueVal, *FalseVal, *Cond; 2236193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2237243830Sdim popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 2238193323Sed getValueTypePair(Record, OpNum, NextValueNo, Cond)) 2239193323Sed return Error("Invalid SELECT record"); 2240193323Sed 2241193323Sed // select condition can be either i1 or [N x i1] 2242226633Sdim if (VectorType* vector_type = 2243226633Sdim dyn_cast<VectorType>(Cond->getType())) { 2244193323Sed // expect <n x i1> 2245198090Srdivacky if (vector_type->getElementType() != Type::getInt1Ty(Context)) 2246193323Sed return Error("Invalid SELECT condition type"); 2247193323Sed } else { 2248193323Sed // expect i1 2249198090Srdivacky if (Cond->getType() != Type::getInt1Ty(Context)) 2250193323Sed return Error("Invalid SELECT condition type"); 2251198090Srdivacky } 2252198090Srdivacky 2253193323Sed I = SelectInst::Create(Cond, TrueVal, FalseVal); 2254198090Srdivacky InstructionList.push_back(I); 2255193323Sed break; 2256193323Sed } 2257198090Srdivacky 2258193323Sed case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 2259193323Sed unsigned OpNum = 0; 2260193323Sed Value *Vec, *Idx; 2261193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2262243830Sdim popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx)) 2263193323Sed return Error("Invalid EXTRACTELT record"); 2264198090Srdivacky I = ExtractElementInst::Create(Vec, Idx); 2265198090Srdivacky InstructionList.push_back(I); 2266193323Sed break; 2267193323Sed } 2268198090Srdivacky 2269193323Sed case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 2270193323Sed unsigned OpNum = 0; 2271193323Sed Value *Vec, *Elt, *Idx; 2272193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2273243830Sdim popValue(Record, OpNum, NextValueNo, 2274193323Sed cast<VectorType>(Vec->getType())->getElementType(), Elt) || 2275243830Sdim popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx)) 2276193323Sed return Error("Invalid INSERTELT record"); 2277193323Sed I = InsertElementInst::Create(Vec, Elt, Idx); 2278198090Srdivacky InstructionList.push_back(I); 2279193323Sed break; 2280193323Sed } 2281198090Srdivacky 2282193323Sed case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 2283193323Sed unsigned OpNum = 0; 2284193323Sed Value *Vec1, *Vec2, *Mask; 2285193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 2286243830Sdim popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 2287193323Sed return Error("Invalid SHUFFLEVEC record"); 2288193323Sed 2289193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 2290193323Sed return Error("Invalid SHUFFLEVEC record"); 2291193323Sed I = new ShuffleVectorInst(Vec1, Vec2, Mask); 2292198090Srdivacky InstructionList.push_back(I); 2293193323Sed break; 2294193323Sed } 2295193323Sed 2296198090Srdivacky case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 2297198090Srdivacky // Old form of ICmp/FCmp returning bool 2298198090Srdivacky // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 2299198090Srdivacky // both legal on vectors but had different behaviour. 2300198090Srdivacky case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 2301198090Srdivacky // FCmp/ICmp returning bool or vector of bool 2302198090Srdivacky 2303193323Sed unsigned OpNum = 0; 2304193323Sed Value *LHS, *RHS; 2305193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2306243830Sdim popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2307193323Sed OpNum+1 != Record.size()) 2308193323Sed return Error("Invalid CMP record"); 2309198090Srdivacky 2310203954Srdivacky if (LHS->getType()->isFPOrFPVectorTy()) 2311193323Sed I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 2312193323Sed else 2313193323Sed I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 2314198090Srdivacky InstructionList.push_back(I); 2315193323Sed break; 2316193323Sed } 2317198090Srdivacky 2318193323Sed case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 2319193323Sed { 2320193323Sed unsigned Size = Record.size(); 2321193323Sed if (Size == 0) { 2322198090Srdivacky I = ReturnInst::Create(Context); 2323198090Srdivacky InstructionList.push_back(I); 2324193323Sed break; 2325193323Sed } 2326193323Sed 2327193323Sed unsigned OpNum = 0; 2328224145Sdim Value *Op = NULL; 2329224145Sdim if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2330224145Sdim return Error("Invalid RET record"); 2331224145Sdim if (OpNum != Record.size()) 2332224145Sdim return Error("Invalid RET record"); 2333193323Sed 2334224145Sdim I = ReturnInst::Create(Context, Op); 2335198090Srdivacky InstructionList.push_back(I); 2336193323Sed break; 2337193323Sed } 2338193323Sed case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 2339193323Sed if (Record.size() != 1 && Record.size() != 3) 2340193323Sed return Error("Invalid BR record"); 2341193323Sed BasicBlock *TrueDest = getBasicBlock(Record[0]); 2342193323Sed if (TrueDest == 0) 2343193323Sed return Error("Invalid BR record"); 2344193323Sed 2345198090Srdivacky if (Record.size() == 1) { 2346193323Sed I = BranchInst::Create(TrueDest); 2347198090Srdivacky InstructionList.push_back(I); 2348198090Srdivacky } 2349193323Sed else { 2350193323Sed BasicBlock *FalseDest = getBasicBlock(Record[1]); 2351243830Sdim Value *Cond = getValue(Record, 2, NextValueNo, 2352243830Sdim Type::getInt1Ty(Context)); 2353193323Sed if (FalseDest == 0 || Cond == 0) 2354193323Sed return Error("Invalid BR record"); 2355193323Sed I = BranchInst::Create(TrueDest, FalseDest, Cond); 2356198090Srdivacky InstructionList.push_back(I); 2357193323Sed } 2358193323Sed break; 2359193323Sed } 2360198892Srdivacky case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 2361249423Sdim // Check magic 2362239462Sdim if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 2363239462Sdim // New SwitchInst format with case ranges. 2364249423Sdim 2365239462Sdim Type *OpTy = getTypeByID(Record[1]); 2366239462Sdim unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 2367239462Sdim 2368243830Sdim Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 2369239462Sdim BasicBlock *Default = getBasicBlock(Record[3]); 2370239462Sdim if (OpTy == 0 || Cond == 0 || Default == 0) 2371239462Sdim return Error("Invalid SWITCH record"); 2372239462Sdim 2373239462Sdim unsigned NumCases = Record[4]; 2374249423Sdim 2375239462Sdim SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 2376239462Sdim InstructionList.push_back(SI); 2377249423Sdim 2378239462Sdim unsigned CurIdx = 5; 2379239462Sdim for (unsigned i = 0; i != NumCases; ++i) { 2380239462Sdim IntegersSubsetToBB CaseBuilder; 2381239462Sdim unsigned NumItems = Record[CurIdx++]; 2382239462Sdim for (unsigned ci = 0; ci != NumItems; ++ci) { 2383239462Sdim bool isSingleNumber = Record[CurIdx++]; 2384249423Sdim 2385239462Sdim APInt Low; 2386239462Sdim unsigned ActiveWords = 1; 2387239462Sdim if (ValueBitWidth > 64) 2388239462Sdim ActiveWords = Record[CurIdx++]; 2389239462Sdim Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 2390239462Sdim ValueBitWidth); 2391239462Sdim CurIdx += ActiveWords; 2392239462Sdim 2393239462Sdim if (!isSingleNumber) { 2394239462Sdim ActiveWords = 1; 2395239462Sdim if (ValueBitWidth > 64) 2396239462Sdim ActiveWords = Record[CurIdx++]; 2397239462Sdim APInt High = 2398239462Sdim ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 2399239462Sdim ValueBitWidth); 2400249423Sdim 2401239462Sdim CaseBuilder.add(IntItem::fromType(OpTy, Low), 2402239462Sdim IntItem::fromType(OpTy, High)); 2403239462Sdim CurIdx += ActiveWords; 2404239462Sdim } else 2405239462Sdim CaseBuilder.add(IntItem::fromType(OpTy, Low)); 2406239462Sdim } 2407239462Sdim BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 2408249423Sdim IntegersSubset Case = CaseBuilder.getCase(); 2409239462Sdim SI->addCase(Case, DestBB); 2410239462Sdim } 2411239462Sdim uint16_t Hash = SI->hash(); 2412239462Sdim if (Hash != (Record[0] & 0xFFFF)) 2413239462Sdim return Error("Invalid SWITCH record"); 2414239462Sdim I = SI; 2415239462Sdim break; 2416239462Sdim } 2417249423Sdim 2418239462Sdim // Old SwitchInst format without case ranges. 2419249423Sdim 2420193323Sed if (Record.size() < 3 || (Record.size() & 1) == 0) 2421193323Sed return Error("Invalid SWITCH record"); 2422226633Sdim Type *OpTy = getTypeByID(Record[0]); 2423243830Sdim Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 2424193323Sed BasicBlock *Default = getBasicBlock(Record[2]); 2425193323Sed if (OpTy == 0 || Cond == 0 || Default == 0) 2426193323Sed return Error("Invalid SWITCH record"); 2427193323Sed unsigned NumCases = (Record.size()-3)/2; 2428193323Sed SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 2429198090Srdivacky InstructionList.push_back(SI); 2430193323Sed for (unsigned i = 0, e = NumCases; i != e; ++i) { 2431198090Srdivacky ConstantInt *CaseVal = 2432193323Sed dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 2433193323Sed BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 2434193323Sed if (CaseVal == 0 || DestBB == 0) { 2435193323Sed delete SI; 2436193323Sed return Error("Invalid SWITCH record!"); 2437193323Sed } 2438193323Sed SI->addCase(CaseVal, DestBB); 2439193323Sed } 2440193323Sed I = SI; 2441193323Sed break; 2442193323Sed } 2443198892Srdivacky case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 2444198892Srdivacky if (Record.size() < 2) 2445198892Srdivacky return Error("Invalid INDIRECTBR record"); 2446226633Sdim Type *OpTy = getTypeByID(Record[0]); 2447243830Sdim Value *Address = getValue(Record, 1, NextValueNo, OpTy); 2448198892Srdivacky if (OpTy == 0 || Address == 0) 2449198892Srdivacky return Error("Invalid INDIRECTBR record"); 2450198892Srdivacky unsigned NumDests = Record.size()-2; 2451198892Srdivacky IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 2452198892Srdivacky InstructionList.push_back(IBI); 2453198892Srdivacky for (unsigned i = 0, e = NumDests; i != e; ++i) { 2454198892Srdivacky if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 2455198892Srdivacky IBI->addDestination(DestBB); 2456198892Srdivacky } else { 2457198892Srdivacky delete IBI; 2458198892Srdivacky return Error("Invalid INDIRECTBR record!"); 2459198892Srdivacky } 2460198892Srdivacky } 2461198892Srdivacky I = IBI; 2462198892Srdivacky break; 2463198892Srdivacky } 2464249423Sdim 2465193323Sed case bitc::FUNC_CODE_INST_INVOKE: { 2466193323Sed // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 2467193323Sed if (Record.size() < 4) return Error("Invalid INVOKE record"); 2468249423Sdim AttributeSet PAL = getAttributes(Record[0]); 2469193323Sed unsigned CCInfo = Record[1]; 2470193323Sed BasicBlock *NormalBB = getBasicBlock(Record[2]); 2471193323Sed BasicBlock *UnwindBB = getBasicBlock(Record[3]); 2472198090Srdivacky 2473193323Sed unsigned OpNum = 4; 2474193323Sed Value *Callee; 2475193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 2476193323Sed return Error("Invalid INVOKE record"); 2477198090Srdivacky 2478226633Sdim PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 2479226633Sdim FunctionType *FTy = !CalleeTy ? 0 : 2480193323Sed dyn_cast<FunctionType>(CalleeTy->getElementType()); 2481193323Sed 2482193323Sed // Check that the right number of fixed parameters are here. 2483193323Sed if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 || 2484193323Sed Record.size() < OpNum+FTy->getNumParams()) 2485193323Sed return Error("Invalid INVOKE record"); 2486198090Srdivacky 2487193323Sed SmallVector<Value*, 16> Ops; 2488193323Sed for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 2489243830Sdim Ops.push_back(getValue(Record, OpNum, NextValueNo, 2490243830Sdim FTy->getParamType(i))); 2491193323Sed if (Ops.back() == 0) return Error("Invalid INVOKE record"); 2492193323Sed } 2493198090Srdivacky 2494193323Sed if (!FTy->isVarArg()) { 2495193323Sed if (Record.size() != OpNum) 2496193323Sed return Error("Invalid INVOKE record"); 2497193323Sed } else { 2498193323Sed // Read type/value pairs for varargs params. 2499193323Sed while (OpNum != Record.size()) { 2500193323Sed Value *Op; 2501193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2502193323Sed return Error("Invalid INVOKE record"); 2503193323Sed Ops.push_back(Op); 2504193323Sed } 2505193323Sed } 2506198090Srdivacky 2507224145Sdim I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops); 2508198090Srdivacky InstructionList.push_back(I); 2509198090Srdivacky cast<InvokeInst>(I)->setCallingConv( 2510198090Srdivacky static_cast<CallingConv::ID>(CCInfo)); 2511193323Sed cast<InvokeInst>(I)->setAttributes(PAL); 2512193323Sed break; 2513193323Sed } 2514226633Sdim case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 2515226633Sdim unsigned Idx = 0; 2516226633Sdim Value *Val = 0; 2517226633Sdim if (getValueTypePair(Record, Idx, NextValueNo, Val)) 2518226633Sdim return Error("Invalid RESUME record"); 2519226633Sdim I = ResumeInst::Create(Val); 2520226633Sdim InstructionList.push_back(I); 2521226633Sdim break; 2522226633Sdim } 2523193323Sed case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 2524198090Srdivacky I = new UnreachableInst(Context); 2525198090Srdivacky InstructionList.push_back(I); 2526193323Sed break; 2527193323Sed case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 2528193323Sed if (Record.size() < 1 || ((Record.size()-1)&1)) 2529193323Sed return Error("Invalid PHI record"); 2530226633Sdim Type *Ty = getTypeByID(Record[0]); 2531193323Sed if (!Ty) return Error("Invalid PHI record"); 2532198090Srdivacky 2533221345Sdim PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 2534198090Srdivacky InstructionList.push_back(PN); 2535198090Srdivacky 2536193323Sed for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 2537243830Sdim Value *V; 2538243830Sdim // With the new function encoding, it is possible that operands have 2539243830Sdim // negative IDs (for forward references). Use a signed VBR 2540243830Sdim // representation to keep the encoding small. 2541243830Sdim if (UseRelativeIDs) 2542243830Sdim V = getValueSigned(Record, 1+i, NextValueNo, Ty); 2543243830Sdim else 2544243830Sdim V = getValue(Record, 1+i, NextValueNo, Ty); 2545193323Sed BasicBlock *BB = getBasicBlock(Record[2+i]); 2546193323Sed if (!V || !BB) return Error("Invalid PHI record"); 2547193323Sed PN->addIncoming(V, BB); 2548193323Sed } 2549193323Sed I = PN; 2550193323Sed break; 2551193323Sed } 2552198090Srdivacky 2553226633Sdim case bitc::FUNC_CODE_INST_LANDINGPAD: { 2554226633Sdim // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 2555226633Sdim unsigned Idx = 0; 2556226633Sdim if (Record.size() < 4) 2557226633Sdim return Error("Invalid LANDINGPAD record"); 2558226633Sdim Type *Ty = getTypeByID(Record[Idx++]); 2559226633Sdim if (!Ty) return Error("Invalid LANDINGPAD record"); 2560226633Sdim Value *PersFn = 0; 2561226633Sdim if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 2562226633Sdim return Error("Invalid LANDINGPAD record"); 2563226633Sdim 2564226633Sdim bool IsCleanup = !!Record[Idx++]; 2565226633Sdim unsigned NumClauses = Record[Idx++]; 2566226633Sdim LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses); 2567226633Sdim LP->setCleanup(IsCleanup); 2568226633Sdim for (unsigned J = 0; J != NumClauses; ++J) { 2569226633Sdim LandingPadInst::ClauseType CT = 2570226633Sdim LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 2571226633Sdim Value *Val; 2572226633Sdim 2573226633Sdim if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 2574226633Sdim delete LP; 2575226633Sdim return Error("Invalid LANDINGPAD record"); 2576226633Sdim } 2577226633Sdim 2578226633Sdim assert((CT != LandingPadInst::Catch || 2579226633Sdim !isa<ArrayType>(Val->getType())) && 2580226633Sdim "Catch clause has a invalid type!"); 2581226633Sdim assert((CT != LandingPadInst::Filter || 2582226633Sdim isa<ArrayType>(Val->getType())) && 2583226633Sdim "Filter clause has invalid type!"); 2584226633Sdim LP->addClause(Val); 2585226633Sdim } 2586226633Sdim 2587226633Sdim I = LP; 2588226633Sdim InstructionList.push_back(I); 2589226633Sdim break; 2590226633Sdim } 2591226633Sdim 2592210299Sed case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 2593224145Sdim if (Record.size() != 4) 2594193323Sed return Error("Invalid ALLOCA record"); 2595226633Sdim PointerType *Ty = 2596224145Sdim dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 2597226633Sdim Type *OpTy = getTypeByID(Record[1]); 2598224145Sdim Value *Size = getFnValueByID(Record[2], OpTy); 2599224145Sdim unsigned Align = Record[3]; 2600193323Sed if (!Ty || !Size) return Error("Invalid ALLOCA record"); 2601193323Sed I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 2602198090Srdivacky InstructionList.push_back(I); 2603193323Sed break; 2604193323Sed } 2605193323Sed case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 2606193323Sed unsigned OpNum = 0; 2607193323Sed Value *Op; 2608193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2609193323Sed OpNum+2 != Record.size()) 2610193323Sed return Error("Invalid LOAD record"); 2611198090Srdivacky 2612193323Sed I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 2613198090Srdivacky InstructionList.push_back(I); 2614193323Sed break; 2615193323Sed } 2616226633Sdim case bitc::FUNC_CODE_INST_LOADATOMIC: { 2617226633Sdim // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 2618226633Sdim unsigned OpNum = 0; 2619226633Sdim Value *Op; 2620226633Sdim if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2621226633Sdim OpNum+4 != Record.size()) 2622226633Sdim return Error("Invalid LOADATOMIC record"); 2623226633Sdim 2624249423Sdim 2625226633Sdim AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2626226633Sdim if (Ordering == NotAtomic || Ordering == Release || 2627226633Sdim Ordering == AcquireRelease) 2628226633Sdim return Error("Invalid LOADATOMIC record"); 2629226633Sdim if (Ordering != NotAtomic && Record[OpNum] == 0) 2630226633Sdim return Error("Invalid LOADATOMIC record"); 2631226633Sdim SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2632226633Sdim 2633226633Sdim I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1, 2634226633Sdim Ordering, SynchScope); 2635226633Sdim InstructionList.push_back(I); 2636226633Sdim break; 2637226633Sdim } 2638224145Sdim case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol] 2639193323Sed unsigned OpNum = 0; 2640193323Sed Value *Val, *Ptr; 2641193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2642243830Sdim popValue(Record, OpNum, NextValueNo, 2643193323Sed cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2644193323Sed OpNum+2 != Record.size()) 2645193323Sed return Error("Invalid STORE record"); 2646198090Srdivacky 2647193323Sed I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 2648198090Srdivacky InstructionList.push_back(I); 2649193323Sed break; 2650193323Sed } 2651226633Sdim case bitc::FUNC_CODE_INST_STOREATOMIC: { 2652226633Sdim // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 2653226633Sdim unsigned OpNum = 0; 2654226633Sdim Value *Val, *Ptr; 2655226633Sdim if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2656243830Sdim popValue(Record, OpNum, NextValueNo, 2657226633Sdim cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2658226633Sdim OpNum+4 != Record.size()) 2659226633Sdim return Error("Invalid STOREATOMIC record"); 2660226633Sdim 2661226633Sdim AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2662226633Sdim if (Ordering == NotAtomic || Ordering == Acquire || 2663226633Sdim Ordering == AcquireRelease) 2664226633Sdim return Error("Invalid STOREATOMIC record"); 2665226633Sdim SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2666226633Sdim if (Ordering != NotAtomic && Record[OpNum] == 0) 2667226633Sdim return Error("Invalid STOREATOMIC record"); 2668226633Sdim 2669226633Sdim I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1, 2670226633Sdim Ordering, SynchScope); 2671226633Sdim InstructionList.push_back(I); 2672226633Sdim break; 2673226633Sdim } 2674226633Sdim case bitc::FUNC_CODE_INST_CMPXCHG: { 2675226633Sdim // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope] 2676226633Sdim unsigned OpNum = 0; 2677226633Sdim Value *Ptr, *Cmp, *New; 2678226633Sdim if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2679243830Sdim popValue(Record, OpNum, NextValueNo, 2680226633Sdim cast<PointerType>(Ptr->getType())->getElementType(), Cmp) || 2681243830Sdim popValue(Record, OpNum, NextValueNo, 2682226633Sdim cast<PointerType>(Ptr->getType())->getElementType(), New) || 2683226633Sdim OpNum+3 != Record.size()) 2684226633Sdim return Error("Invalid CMPXCHG record"); 2685226633Sdim AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]); 2686226633Sdim if (Ordering == NotAtomic || Ordering == Unordered) 2687226633Sdim return Error("Invalid CMPXCHG record"); 2688226633Sdim SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]); 2689226633Sdim I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope); 2690226633Sdim cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 2691226633Sdim InstructionList.push_back(I); 2692226633Sdim break; 2693226633Sdim } 2694226633Sdim case bitc::FUNC_CODE_INST_ATOMICRMW: { 2695226633Sdim // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 2696226633Sdim unsigned OpNum = 0; 2697226633Sdim Value *Ptr, *Val; 2698226633Sdim if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2699243830Sdim popValue(Record, OpNum, NextValueNo, 2700226633Sdim cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2701226633Sdim OpNum+4 != Record.size()) 2702226633Sdim return Error("Invalid ATOMICRMW record"); 2703226633Sdim AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]); 2704226633Sdim if (Operation < AtomicRMWInst::FIRST_BINOP || 2705226633Sdim Operation > AtomicRMWInst::LAST_BINOP) 2706226633Sdim return Error("Invalid ATOMICRMW record"); 2707226633Sdim AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2708226633Sdim if (Ordering == NotAtomic || Ordering == Unordered) 2709226633Sdim return Error("Invalid ATOMICRMW record"); 2710226633Sdim SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2711226633Sdim I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 2712226633Sdim cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 2713226633Sdim InstructionList.push_back(I); 2714226633Sdim break; 2715226633Sdim } 2716226633Sdim case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 2717226633Sdim if (2 != Record.size()) 2718226633Sdim return Error("Invalid FENCE record"); 2719226633Sdim AtomicOrdering Ordering = GetDecodedOrdering(Record[0]); 2720226633Sdim if (Ordering == NotAtomic || Ordering == Unordered || 2721226633Sdim Ordering == Monotonic) 2722226633Sdim return Error("Invalid FENCE record"); 2723226633Sdim SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]); 2724226633Sdim I = new FenceInst(Context, Ordering, SynchScope); 2725226633Sdim InstructionList.push_back(I); 2726226633Sdim break; 2727226633Sdim } 2728224145Sdim case bitc::FUNC_CODE_INST_CALL: { 2729193323Sed // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 2730193323Sed if (Record.size() < 3) 2731193323Sed return Error("Invalid CALL record"); 2732198090Srdivacky 2733249423Sdim AttributeSet PAL = getAttributes(Record[0]); 2734193323Sed unsigned CCInfo = Record[1]; 2735198090Srdivacky 2736193323Sed unsigned OpNum = 2; 2737193323Sed Value *Callee; 2738193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 2739193323Sed return Error("Invalid CALL record"); 2740198090Srdivacky 2741226633Sdim PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 2742226633Sdim FunctionType *FTy = 0; 2743193323Sed if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 2744193323Sed if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 2745193323Sed return Error("Invalid CALL record"); 2746198090Srdivacky 2747193323Sed SmallVector<Value*, 16> Args; 2748193323Sed // Read the fixed params. 2749193323Sed for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 2750224145Sdim if (FTy->getParamType(i)->isLabelTy()) 2751193323Sed Args.push_back(getBasicBlock(Record[OpNum])); 2752193323Sed else 2753243830Sdim Args.push_back(getValue(Record, OpNum, NextValueNo, 2754243830Sdim FTy->getParamType(i))); 2755193323Sed if (Args.back() == 0) return Error("Invalid CALL record"); 2756193323Sed } 2757198090Srdivacky 2758193323Sed // Read type/value pairs for varargs params. 2759193323Sed if (!FTy->isVarArg()) { 2760193323Sed if (OpNum != Record.size()) 2761193323Sed return Error("Invalid CALL record"); 2762193323Sed } else { 2763193323Sed while (OpNum != Record.size()) { 2764193323Sed Value *Op; 2765193323Sed if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2766193323Sed return Error("Invalid CALL record"); 2767193323Sed Args.push_back(Op); 2768193323Sed } 2769193323Sed } 2770198090Srdivacky 2771224145Sdim I = CallInst::Create(Callee, Args); 2772198090Srdivacky InstructionList.push_back(I); 2773198090Srdivacky cast<CallInst>(I)->setCallingConv( 2774198090Srdivacky static_cast<CallingConv::ID>(CCInfo>>1)); 2775193323Sed cast<CallInst>(I)->setTailCall(CCInfo & 1); 2776193323Sed cast<CallInst>(I)->setAttributes(PAL); 2777193323Sed break; 2778193323Sed } 2779193323Sed case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 2780193323Sed if (Record.size() < 3) 2781193323Sed return Error("Invalid VAARG record"); 2782226633Sdim Type *OpTy = getTypeByID(Record[0]); 2783243830Sdim Value *Op = getValue(Record, 1, NextValueNo, OpTy); 2784226633Sdim Type *ResTy = getTypeByID(Record[2]); 2785193323Sed if (!OpTy || !Op || !ResTy) 2786193323Sed return Error("Invalid VAARG record"); 2787193323Sed I = new VAArgInst(Op, ResTy); 2788198090Srdivacky InstructionList.push_back(I); 2789193323Sed break; 2790193323Sed } 2791193323Sed } 2792193323Sed 2793193323Sed // Add instruction to end of current BB. If there is no current BB, reject 2794193323Sed // this file. 2795193323Sed if (CurBB == 0) { 2796193323Sed delete I; 2797193323Sed return Error("Invalid instruction with no BB"); 2798193323Sed } 2799193323Sed CurBB->getInstList().push_back(I); 2800198090Srdivacky 2801193323Sed // If this was a terminator instruction, move to the next block. 2802193323Sed if (isa<TerminatorInst>(I)) { 2803193323Sed ++CurBBNo; 2804193323Sed CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0; 2805193323Sed } 2806198090Srdivacky 2807193323Sed // Non-void values get registered in the value table for future use. 2808202375Srdivacky if (I && !I->getType()->isVoidTy()) 2809193323Sed ValueList.AssignValue(I, NextValueNo++); 2810193323Sed } 2811198090Srdivacky 2812249423SdimOutOfRecordLoop: 2813249423Sdim 2814193323Sed // Check the function list for unresolved values. 2815193323Sed if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 2816193323Sed if (A->getParent() == 0) { 2817193323Sed // We found at least one unresolved value. Nuke them all to avoid leaks. 2818193323Sed for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 2819212904Sdim if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) { 2820193323Sed A->replaceAllUsesWith(UndefValue::get(A->getType())); 2821193323Sed delete A; 2822193323Sed } 2823193323Sed } 2824193323Sed return Error("Never resolved value found in function!"); 2825193323Sed } 2826193323Sed } 2827198090Srdivacky 2828212904Sdim // FIXME: Check for unresolved forward-declared metadata references 2829212904Sdim // and clean up leaks. 2830212904Sdim 2831198892Srdivacky // See if anything took the address of blocks in this function. If so, 2832198892Srdivacky // resolve them now. 2833198892Srdivacky DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI = 2834198892Srdivacky BlockAddrFwdRefs.find(F); 2835198892Srdivacky if (BAFRI != BlockAddrFwdRefs.end()) { 2836198892Srdivacky std::vector<BlockAddrRefTy> &RefList = BAFRI->second; 2837198892Srdivacky for (unsigned i = 0, e = RefList.size(); i != e; ++i) { 2838198892Srdivacky unsigned BlockIdx = RefList[i].first; 2839198892Srdivacky if (BlockIdx >= FunctionBBs.size()) 2840198892Srdivacky return Error("Invalid blockaddress block #"); 2841249423Sdim 2842198892Srdivacky GlobalVariable *FwdRef = RefList[i].second; 2843198892Srdivacky FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx])); 2844198892Srdivacky FwdRef->eraseFromParent(); 2845198892Srdivacky } 2846249423Sdim 2847198892Srdivacky BlockAddrFwdRefs.erase(BAFRI); 2848198892Srdivacky } 2849249423Sdim 2850193323Sed // Trim the value list down to the size it was before we parsed this function. 2851193323Sed ValueList.shrinkTo(ModuleValueListSize); 2852212904Sdim MDValueList.shrinkTo(ModuleMDValueListSize); 2853193323Sed std::vector<BasicBlock*>().swap(FunctionBBs); 2854193323Sed return false; 2855193323Sed} 2856193323Sed 2857234353Sdim/// FindFunctionInStream - Find the function body in the bitcode stream 2858234353Sdimbool BitcodeReader::FindFunctionInStream(Function *F, 2859234353Sdim DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) { 2860234353Sdim while (DeferredFunctionInfoIterator->second == 0) { 2861234353Sdim if (Stream.AtEndOfStream()) 2862234353Sdim return Error("Could not find Function in stream"); 2863234353Sdim // ParseModule will parse the next body in the stream and set its 2864234353Sdim // position in the DeferredFunctionInfo map. 2865234353Sdim if (ParseModule(true)) return true; 2866234353Sdim } 2867234353Sdim return false; 2868234353Sdim} 2869234353Sdim 2870193323Sed//===----------------------------------------------------------------------===// 2871203954Srdivacky// GVMaterializer implementation 2872193323Sed//===----------------------------------------------------------------------===// 2873193323Sed 2874193323Sed 2875203954Srdivackybool BitcodeReader::isMaterializable(const GlobalValue *GV) const { 2876203954Srdivacky if (const Function *F = dyn_cast<Function>(GV)) { 2877203954Srdivacky return F->isDeclaration() && 2878203954Srdivacky DeferredFunctionInfo.count(const_cast<Function*>(F)); 2879203954Srdivacky } 2880203954Srdivacky return false; 2881203954Srdivacky} 2882198090Srdivacky 2883203954Srdivackybool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) { 2884203954Srdivacky Function *F = dyn_cast<Function>(GV); 2885203954Srdivacky // If it's not a function or is already material, ignore the request. 2886203954Srdivacky if (!F || !F->isMaterializable()) return false; 2887203954Srdivacky 2888203954Srdivacky DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 2889193323Sed assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 2890234353Sdim // If its position is recorded as 0, its body is somewhere in the stream 2891234353Sdim // but we haven't seen it yet. 2892234353Sdim if (DFII->second == 0) 2893234353Sdim if (LazyStreamer && FindFunctionInStream(F, DFII)) return true; 2894198090Srdivacky 2895203954Srdivacky // Move the bit stream to the saved position of the deferred function body. 2896203954Srdivacky Stream.JumpToBit(DFII->second); 2897198090Srdivacky 2898193323Sed if (ParseFunctionBody(F)) { 2899193323Sed if (ErrInfo) *ErrInfo = ErrorString; 2900193323Sed return true; 2901193323Sed } 2902193323Sed 2903193323Sed // Upgrade any old intrinsic calls in the function. 2904193323Sed for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 2905193323Sed E = UpgradedIntrinsics.end(); I != E; ++I) { 2906193323Sed if (I->first != I->second) { 2907193323Sed for (Value::use_iterator UI = I->first->use_begin(), 2908193323Sed UE = I->first->use_end(); UI != UE; ) { 2909193323Sed if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 2910193323Sed UpgradeIntrinsicCall(CI, I->second); 2911193323Sed } 2912193323Sed } 2913193323Sed } 2914198090Srdivacky 2915193323Sed return false; 2916193323Sed} 2917193323Sed 2918203954Srdivackybool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 2919203954Srdivacky const Function *F = dyn_cast<Function>(GV); 2920203954Srdivacky if (!F || F->isDeclaration()) 2921203954Srdivacky return false; 2922203954Srdivacky return DeferredFunctionInfo.count(const_cast<Function*>(F)); 2923203954Srdivacky} 2924203954Srdivacky 2925203954Srdivackyvoid BitcodeReader::Dematerialize(GlobalValue *GV) { 2926203954Srdivacky Function *F = dyn_cast<Function>(GV); 2927203954Srdivacky // If this function isn't dematerializable, this is a noop. 2928203954Srdivacky if (!F || !isDematerializable(F)) 2929193323Sed return; 2930198090Srdivacky 2931193323Sed assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 2932198090Srdivacky 2933193323Sed // Just forget the function body, we can remat it later. 2934193323Sed F->deleteBody(); 2935193323Sed} 2936193323Sed 2937193323Sed 2938203954Srdivackybool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) { 2939203954Srdivacky assert(M == TheModule && 2940203954Srdivacky "Can only Materialize the Module this BitcodeReader is attached to."); 2941194612Sed // Iterate over the module, deserializing any functions that are still on 2942194612Sed // disk. 2943194612Sed for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 2944194612Sed F != E; ++F) 2945203954Srdivacky if (F->isMaterializable() && 2946203954Srdivacky Materialize(F, ErrInfo)) 2947203954Srdivacky return true; 2948193323Sed 2949234353Sdim // At this point, if there are any function bodies, the current bit is 2950234353Sdim // pointing to the END_BLOCK record after them. Now make sure the rest 2951234353Sdim // of the bits in the module have been read. 2952234353Sdim if (NextUnreadBit) 2953234353Sdim ParseModule(true); 2954234353Sdim 2955198090Srdivacky // Upgrade any intrinsic calls that slipped through (should not happen!) and 2956198090Srdivacky // delete the old functions to clean up. We can't do this unless the entire 2957198090Srdivacky // module is materialized because there could always be another function body 2958193323Sed // with calls to the old function. 2959193323Sed for (std::vector<std::pair<Function*, Function*> >::iterator I = 2960193323Sed UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 2961193323Sed if (I->first != I->second) { 2962193323Sed for (Value::use_iterator UI = I->first->use_begin(), 2963193323Sed UE = I->first->use_end(); UI != UE; ) { 2964193323Sed if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 2965193323Sed UpgradeIntrinsicCall(CI, I->second); 2966193323Sed } 2967193323Sed if (!I->first->use_empty()) 2968193323Sed I->first->replaceAllUsesWith(I->second); 2969193323Sed I->first->eraseFromParent(); 2970193323Sed } 2971193323Sed } 2972193323Sed std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 2973198090Srdivacky 2974234353Sdim return false; 2975234353Sdim} 2976226633Sdim 2977234353Sdimbool BitcodeReader::InitStream() { 2978234353Sdim if (LazyStreamer) return InitLazyStream(); 2979234353Sdim return InitStreamFromBuffer(); 2980234353Sdim} 2981198090Srdivacky 2982234353Sdimbool BitcodeReader::InitStreamFromBuffer() { 2983243830Sdim const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 2984234353Sdim const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 2985234353Sdim 2986234353Sdim if (Buffer->getBufferSize() & 3) { 2987234353Sdim if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd)) 2988234353Sdim return Error("Invalid bitcode signature"); 2989234353Sdim else 2990234353Sdim return Error("Bitcode stream should be a multiple of 4 bytes in length"); 2991234353Sdim } 2992234353Sdim 2993234353Sdim // If we have a wrapper header, parse it and ignore the non-bc file contents. 2994234353Sdim // The magic number is 0x0B17C0DE stored in little endian. 2995234353Sdim if (isBitcodeWrapper(BufPtr, BufEnd)) 2996234353Sdim if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 2997234353Sdim return Error("Invalid bitcode wrapper header"); 2998234353Sdim 2999234353Sdim StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 3000234353Sdim Stream.init(*StreamFile); 3001234353Sdim 3002203954Srdivacky return false; 3003193323Sed} 3004193323Sed 3005234353Sdimbool BitcodeReader::InitLazyStream() { 3006234353Sdim // Check and strip off the bitcode wrapper; BitstreamReader expects never to 3007234353Sdim // see it. 3008234353Sdim StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer); 3009234353Sdim StreamFile.reset(new BitstreamReader(Bytes)); 3010234353Sdim Stream.init(*StreamFile); 3011193323Sed 3012234353Sdim unsigned char buf[16]; 3013234353Sdim if (Bytes->readBytes(0, 16, buf, NULL) == -1) 3014234353Sdim return Error("Bitcode stream must be at least 16 bytes in length"); 3015234353Sdim 3016234353Sdim if (!isBitcode(buf, buf + 16)) 3017234353Sdim return Error("Invalid bitcode signature"); 3018234353Sdim 3019234353Sdim if (isBitcodeWrapper(buf, buf + 4)) { 3020234353Sdim const unsigned char *bitcodeStart = buf; 3021234353Sdim const unsigned char *bitcodeEnd = buf + 16; 3022234353Sdim SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 3023234353Sdim Bytes->dropLeadingBytes(bitcodeStart - buf); 3024234353Sdim Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart); 3025234353Sdim } 3026234353Sdim return false; 3027234353Sdim} 3028234353Sdim 3029193323Sed//===----------------------------------------------------------------------===// 3030193323Sed// External interface 3031193323Sed//===----------------------------------------------------------------------===// 3032193323Sed 3033203954Srdivacky/// getLazyBitcodeModule - lazy function-at-a-time loading from a file. 3034193323Sed/// 3035203954SrdivackyModule *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer, 3036203954Srdivacky LLVMContext& Context, 3037203954Srdivacky std::string *ErrMsg) { 3038203954Srdivacky Module *M = new Module(Buffer->getBufferIdentifier(), Context); 3039195340Sed BitcodeReader *R = new BitcodeReader(Buffer, Context); 3040203954Srdivacky M->setMaterializer(R); 3041203954Srdivacky if (R->ParseBitcodeInto(M)) { 3042193323Sed if (ErrMsg) 3043193323Sed *ErrMsg = R->getErrorString(); 3044198090Srdivacky 3045203954Srdivacky delete M; // Also deletes R. 3046193323Sed return 0; 3047193323Sed } 3048203954Srdivacky // Have the BitcodeReader dtor delete 'Buffer'. 3049203954Srdivacky R->setBufferOwned(true); 3050234353Sdim 3051234353Sdim R->materializeForwardReferencedFunctions(); 3052234353Sdim 3053203954Srdivacky return M; 3054193323Sed} 3055193323Sed 3056234353Sdim 3057234353SdimModule *llvm::getStreamedBitcodeModule(const std::string &name, 3058234353Sdim DataStreamer *streamer, 3059234353Sdim LLVMContext &Context, 3060234353Sdim std::string *ErrMsg) { 3061234353Sdim Module *M = new Module(name, Context); 3062234353Sdim BitcodeReader *R = new BitcodeReader(streamer, Context); 3063234353Sdim M->setMaterializer(R); 3064234353Sdim if (R->ParseBitcodeInto(M)) { 3065234353Sdim if (ErrMsg) 3066234353Sdim *ErrMsg = R->getErrorString(); 3067234353Sdim delete M; // Also deletes R. 3068234353Sdim return 0; 3069234353Sdim } 3070234353Sdim R->setBufferOwned(false); // no buffer to delete 3071234353Sdim return M; 3072234353Sdim} 3073234353Sdim 3074193323Sed/// ParseBitcodeFile - Read the specified bitcode file, returning the module. 3075193323Sed/// If an error occurs, return null and fill in *ErrMsg if non-null. 3076198090SrdivackyModule *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, 3077195340Sed std::string *ErrMsg){ 3078203954Srdivacky Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg); 3079203954Srdivacky if (!M) return 0; 3080198090Srdivacky 3081193323Sed // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether 3082193323Sed // there was an error. 3083203954Srdivacky static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false); 3084198090Srdivacky 3085203954Srdivacky // Read in the entire module, and destroy the BitcodeReader. 3086203954Srdivacky if (M->MaterializeAllPermanently(ErrMsg)) { 3087203954Srdivacky delete M; 3088218893Sdim return 0; 3089203954Srdivacky } 3090218893Sdim 3091234353Sdim // TODO: Restore the use-lists to the in-memory state when the bitcode was 3092234353Sdim // written. We must defer until the Module has been fully materialized. 3093234353Sdim 3094193323Sed return M; 3095193323Sed} 3096218893Sdim 3097218893Sdimstd::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer, 3098218893Sdim LLVMContext& Context, 3099218893Sdim std::string *ErrMsg) { 3100218893Sdim BitcodeReader *R = new BitcodeReader(Buffer, Context); 3101218893Sdim // Don't let the BitcodeReader dtor delete 'Buffer'. 3102218893Sdim R->setBufferOwned(false); 3103218893Sdim 3104218893Sdim std::string Triple(""); 3105218893Sdim if (R->ParseTriple(Triple)) 3106218893Sdim if (ErrMsg) 3107218893Sdim *ErrMsg = R->getErrorString(); 3108218893Sdim 3109218893Sdim delete R; 3110218893Sdim return Triple; 3111218893Sdim} 3112