LLVM API Documentation
00001 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This header defines the BitcodeReader class. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "llvm/Bitcode/ReaderWriter.h" 00015 #include "BitcodeReader.h" 00016 #include "llvm/Constants.h" 00017 #include "llvm/DerivedTypes.h" 00018 #include "llvm/InlineAsm.h" 00019 #include "llvm/Instructions.h" 00020 #include "llvm/LLVMContext.h" 00021 #include "llvm/Metadata.h" 00022 #include "llvm/Module.h" 00023 #include "llvm/Operator.h" 00024 #include "llvm/AutoUpgrade.h" 00025 #include "llvm/ADT/SmallString.h" 00026 #include "llvm/ADT/SmallVector.h" 00027 #include "llvm/Support/MathExtras.h" 00028 #include "llvm/Support/MemoryBuffer.h" 00029 #include "llvm/OperandTraits.h" 00030 using namespace llvm; 00031 00032 void BitcodeReader::FreeState() { 00033 delete Buffer; 00034 Buffer = 0; 00035 std::vector<PATypeHolder>().swap(TypeList); 00036 ValueList.clear(); 00037 MDValueList.clear(); 00038 00039 std::vector<AttrListPtr>().swap(MAttributes); 00040 std::vector<BasicBlock*>().swap(FunctionBBs); 00041 std::vector<Function*>().swap(FunctionsWithBodies); 00042 DeferredFunctionInfo.clear(); 00043 } 00044 00045 //===----------------------------------------------------------------------===// 00046 // Helper functions to implement forward reference resolution, etc. 00047 //===----------------------------------------------------------------------===// 00048 00049 /// ConvertToString - Convert a string from a record into an std::string, return 00050 /// true on failure. 00051 template<typename StrTy> 00052 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx, 00053 StrTy &Result) { 00054 if (Idx > Record.size()) 00055 return true; 00056 00057 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 00058 Result += (char)Record[i]; 00059 return false; 00060 } 00061 00062 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) { 00063 switch (Val) { 00064 default: // Map unknown/new linkages to external 00065 case 0: return GlobalValue::ExternalLinkage; 00066 case 1: return GlobalValue::WeakAnyLinkage; 00067 case 2: return GlobalValue::AppendingLinkage; 00068 case 3: return GlobalValue::InternalLinkage; 00069 case 4: return GlobalValue::LinkOnceAnyLinkage; 00070 case 5: return GlobalValue::DLLImportLinkage; 00071 case 6: return GlobalValue::DLLExportLinkage; 00072 case 7: return GlobalValue::ExternalWeakLinkage; 00073 case 8: return GlobalValue::CommonLinkage; 00074 case 9: return GlobalValue::PrivateLinkage; 00075 case 10: return GlobalValue::WeakODRLinkage; 00076 case 11: return GlobalValue::LinkOnceODRLinkage; 00077 case 12: return GlobalValue::AvailableExternallyLinkage; 00078 case 13: return GlobalValue::LinkerPrivateLinkage; 00079 } 00080 } 00081 00082 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 00083 switch (Val) { 00084 default: // Map unknown visibilities to default. 00085 case 0: return GlobalValue::DefaultVisibility; 00086 case 1: return GlobalValue::HiddenVisibility; 00087 case 2: return GlobalValue::ProtectedVisibility; 00088 } 00089 } 00090 00091 static int GetDecodedCastOpcode(unsigned Val) { 00092 switch (Val) { 00093 default: return -1; 00094 case bitc::CAST_TRUNC : return Instruction::Trunc; 00095 case bitc::CAST_ZEXT : return Instruction::ZExt; 00096 case bitc::CAST_SEXT : return Instruction::SExt; 00097 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 00098 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 00099 case bitc::CAST_UITOFP : return Instruction::UIToFP; 00100 case bitc::CAST_SITOFP : return Instruction::SIToFP; 00101 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 00102 case bitc::CAST_FPEXT : return Instruction::FPExt; 00103 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 00104 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 00105 case bitc::CAST_BITCAST : return Instruction::BitCast; 00106 } 00107 } 00108 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) { 00109 switch (Val) { 00110 default: return -1; 00111 case bitc::BINOP_ADD: 00112 return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add; 00113 case bitc::BINOP_SUB: 00114 return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub; 00115 case bitc::BINOP_MUL: 00116 return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul; 00117 case bitc::BINOP_UDIV: return Instruction::UDiv; 00118 case bitc::BINOP_SDIV: 00119 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv; 00120 case bitc::BINOP_UREM: return Instruction::URem; 00121 case bitc::BINOP_SREM: 00122 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem; 00123 case bitc::BINOP_SHL: return Instruction::Shl; 00124 case bitc::BINOP_LSHR: return Instruction::LShr; 00125 case bitc::BINOP_ASHR: return Instruction::AShr; 00126 case bitc::BINOP_AND: return Instruction::And; 00127 case bitc::BINOP_OR: return Instruction::Or; 00128 case bitc::BINOP_XOR: return Instruction::Xor; 00129 } 00130 } 00131 00132 namespace llvm { 00133 namespace { 00134 /// @brief A class for maintaining the slot number definition 00135 /// as a placeholder for the actual definition for forward constants defs. 00136 class ConstantPlaceHolder : public ConstantExpr { 00137 ConstantPlaceHolder(); // DO NOT IMPLEMENT 00138 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT 00139 public: 00140 // allocate space for exactly one operand 00141 void *operator new(size_t s) { 00142 return User::operator new(s, 1); 00143 } 00144 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context) 00145 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 00146 Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 00147 } 00148 00149 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast. 00150 static inline bool classof(const ConstantPlaceHolder *) { return true; } 00151 static bool classof(const Value *V) { 00152 return isa<ConstantExpr>(V) && 00153 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 00154 } 00155 00156 00157 /// Provide fast operand accessors 00158 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 00159 }; 00160 } 00161 00162 // FIXME: can we inherit this from ConstantExpr? 00163 template <> 00164 struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> { 00165 }; 00166 } 00167 00168 00169 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { 00170 if (Idx == size()) { 00171 push_back(V); 00172 return; 00173 } 00174 00175 if (Idx >= size()) 00176 resize(Idx+1); 00177 00178 WeakVH &OldV = ValuePtrs[Idx]; 00179 if (OldV == 0) { 00180 OldV = V; 00181 return; 00182 } 00183 00184 // Handle constants and non-constants (e.g. instrs) differently for 00185 // efficiency. 00186 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 00187 ResolveConstants.push_back(std::make_pair(PHC, Idx)); 00188 OldV = V; 00189 } else { 00190 // If there was a forward reference to this value, replace it. 00191 Value *PrevVal = OldV; 00192 OldV->replaceAllUsesWith(V); 00193 delete PrevVal; 00194 } 00195 } 00196 00197 00198 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 00199 const Type *Ty) { 00200 if (Idx >= size()) 00201 resize(Idx + 1); 00202 00203 if (Value *V = ValuePtrs[Idx]) { 00204 assert(Ty == V->getType() && "Type mismatch in constant table!"); 00205 return cast<Constant>(V); 00206 } 00207 00208 // Create and return a placeholder, which will later be RAUW'd. 00209 Constant *C = new ConstantPlaceHolder(Ty, Context); 00210 ValuePtrs[Idx] = C; 00211 return C; 00212 } 00213 00214 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) { 00215 if (Idx >= size()) 00216 resize(Idx + 1); 00217 00218 if (Value *V = ValuePtrs[Idx]) { 00219 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!"); 00220 return V; 00221 } 00222 00223 // No type specified, must be invalid reference. 00224 if (Ty == 0) return 0; 00225 00226 // Create and return a placeholder, which will later be RAUW'd. 00227 Value *V = new Argument(Ty); 00228 ValuePtrs[Idx] = V; 00229 return V; 00230 } 00231 00232 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk 00233 /// resolves any forward references. The idea behind this is that we sometimes 00234 /// get constants (such as large arrays) which reference *many* forward ref 00235 /// constants. Replacing each of these causes a lot of thrashing when 00236 /// building/reuniquing the constant. Instead of doing this, we look at all the 00237 /// uses and rewrite all the place holders at once for any constant that uses 00238 /// a placeholder. 00239 void BitcodeReaderValueList::ResolveConstantForwardRefs() { 00240 // Sort the values by-pointer so that they are efficient to look up with a 00241 // binary search. 00242 std::sort(ResolveConstants.begin(), ResolveConstants.end()); 00243 00244 SmallVector<Constant*, 64> NewOps; 00245 00246 while (!ResolveConstants.empty()) { 00247 Value *RealVal = operator[](ResolveConstants.back().second); 00248 Constant *Placeholder = ResolveConstants.back().first; 00249 ResolveConstants.pop_back(); 00250 00251 // Loop over all users of the placeholder, updating them to reference the 00252 // new value. If they reference more than one placeholder, update them all 00253 // at once. 00254 while (!Placeholder->use_empty()) { 00255 Value::use_iterator UI = Placeholder->use_begin(); 00256 00257 // If the using object isn't uniqued, just update the operands. This 00258 // handles instructions and initializers for global variables. 00259 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) { 00260 UI.getUse().set(RealVal); 00261 continue; 00262 } 00263 00264 // Otherwise, we have a constant that uses the placeholder. Replace that 00265 // constant with a new constant that has *all* placeholder uses updated. 00266 Constant *UserC = cast<Constant>(*UI); 00267 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 00268 I != E; ++I) { 00269 Value *NewOp; 00270 if (!isa<ConstantPlaceHolder>(*I)) { 00271 // Not a placeholder reference. 00272 NewOp = *I; 00273 } else if (*I == Placeholder) { 00274 // Common case is that it just references this one placeholder. 00275 NewOp = RealVal; 00276 } else { 00277 // Otherwise, look up the placeholder in ResolveConstants. 00278 ResolveConstantsTy::iterator It = 00279 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 00280 std::pair<Constant*, unsigned>(cast<Constant>(*I), 00281 0)); 00282 assert(It != ResolveConstants.end() && It->first == *I); 00283 NewOp = operator[](It->second); 00284 } 00285 00286 NewOps.push_back(cast<Constant>(NewOp)); 00287 } 00288 00289 // Make the new constant. 00290 Constant *NewC; 00291 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 00292 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], 00293 NewOps.size()); 00294 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 00295 NewC = ConstantStruct::get(Context, &NewOps[0], NewOps.size(), 00296 UserCS->getType()->isPacked()); 00297 } else if (isa<ConstantVector>(UserC)) { 00298 NewC = ConstantVector::get(&NewOps[0], NewOps.size()); 00299 } else { 00300 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 00301 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0], 00302 NewOps.size()); 00303 } 00304 00305 UserC->replaceAllUsesWith(NewC); 00306 UserC->destroyConstant(); 00307 NewOps.clear(); 00308 } 00309 00310 // Update all ValueHandles, they should be the only users at this point. 00311 Placeholder->replaceAllUsesWith(RealVal); 00312 delete Placeholder; 00313 } 00314 } 00315 00316 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) { 00317 if (Idx == size()) { 00318 push_back(V); 00319 return; 00320 } 00321 00322 if (Idx >= size()) 00323 resize(Idx+1); 00324 00325 WeakVH &OldV = MDValuePtrs[Idx]; 00326 if (OldV == 0) { 00327 OldV = V; 00328 return; 00329 } 00330 00331 // If there was a forward reference to this value, replace it. 00332 Value *PrevVal = OldV; 00333 OldV->replaceAllUsesWith(V); 00334 delete PrevVal; 00335 } 00336 00337 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) { 00338 if (Idx >= size()) 00339 resize(Idx + 1); 00340 00341 if (Value *V = MDValuePtrs[Idx]) { 00342 assert(V->getType() == Type::getMetadataTy(Context) && "Type mismatch in value table!"); 00343 return V; 00344 } 00345 00346 // Create and return a placeholder, which will later be RAUW'd. 00347 Value *V = new Argument(Type::getMetadataTy(Context)); 00348 MDValuePtrs[Idx] = V; 00349 return V; 00350 } 00351 00352 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) { 00353 // If the TypeID is in range, return it. 00354 if (ID < TypeList.size()) 00355 return TypeList[ID].get(); 00356 if (!isTypeTable) return 0; 00357 00358 // The type table allows forward references. Push as many Opaque types as 00359 // needed to get up to ID. 00360 while (TypeList.size() <= ID) 00361 TypeList.push_back(OpaqueType::get(Context)); 00362 return TypeList.back().get(); 00363 } 00364 00365 //===----------------------------------------------------------------------===// 00366 // Functions for parsing blocks from the bitcode file 00367 //===----------------------------------------------------------------------===// 00368 00369 bool BitcodeReader::ParseAttributeBlock() { 00370 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 00371 return Error("Malformed block record"); 00372 00373 if (!MAttributes.empty()) 00374 return Error("Multiple PARAMATTR blocks found!"); 00375 00376 SmallVector<uint64_t, 64> Record; 00377 00378 SmallVector<AttributeWithIndex, 8> Attrs; 00379 00380 // Read all the records. 00381 while (1) { 00382 unsigned Code = Stream.ReadCode(); 00383 if (Code == bitc::END_BLOCK) { 00384 if (Stream.ReadBlockEnd()) 00385 return Error("Error at end of PARAMATTR block"); 00386 return false; 00387 } 00388 00389 if (Code == bitc::ENTER_SUBBLOCK) { 00390 // No known subblocks, always skip them. 00391 Stream.ReadSubBlockID(); 00392 if (Stream.SkipBlock()) 00393 return Error("Malformed block record"); 00394 continue; 00395 } 00396 00397 if (Code == bitc::DEFINE_ABBREV) { 00398 Stream.ReadAbbrevRecord(); 00399 continue; 00400 } 00401 00402 // Read a record. 00403 Record.clear(); 00404 switch (Stream.ReadRecord(Code, Record)) { 00405 default: // Default behavior: ignore. 00406 break; 00407 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...] 00408 if (Record.size() & 1) 00409 return Error("Invalid ENTRY record"); 00410 00411 // FIXME : Remove this autoupgrade code in LLVM 3.0. 00412 // If Function attributes are using index 0 then transfer them 00413 // to index ~0. Index 0 is used for return value attributes but used to be 00414 // used for function attributes. 00415 Attributes RetAttribute = Attribute::None; 00416 Attributes FnAttribute = Attribute::None; 00417 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 00418 // FIXME: remove in LLVM 3.0 00419 // The alignment is stored as a 16-bit raw value from bits 31--16. 00420 // We shift the bits above 31 down by 11 bits. 00421 00422 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16; 00423 if (Alignment && !isPowerOf2_32(Alignment)) 00424 return Error("Alignment is not a power of two."); 00425 00426 Attributes ReconstitutedAttr = Record[i+1] & 0xffff; 00427 if (Alignment) 00428 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment); 00429 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11; 00430 Record[i+1] = ReconstitutedAttr; 00431 00432 if (Record[i] == 0) 00433 RetAttribute = Record[i+1]; 00434 else if (Record[i] == ~0U) 00435 FnAttribute = Record[i+1]; 00436 } 00437 00438 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn| 00439 Attribute::ReadOnly|Attribute::ReadNone); 00440 00441 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None && 00442 (RetAttribute & OldRetAttrs) != 0) { 00443 if (FnAttribute == Attribute::None) { // add a slot so they get added. 00444 Record.push_back(~0U); 00445 Record.push_back(0); 00446 } 00447 00448 FnAttribute |= RetAttribute & OldRetAttrs; 00449 RetAttribute &= ~OldRetAttrs; 00450 } 00451 00452 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 00453 if (Record[i] == 0) { 00454 if (RetAttribute != Attribute::None) 00455 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute)); 00456 } else if (Record[i] == ~0U) { 00457 if (FnAttribute != Attribute::None) 00458 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute)); 00459 } else if (Record[i+1] != Attribute::None) 00460 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1])); 00461 } 00462 00463 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end())); 00464 Attrs.clear(); 00465 break; 00466 } 00467 } 00468 } 00469 } 00470 00471 00472 bool BitcodeReader::ParseTypeTable() { 00473 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID)) 00474 return Error("Malformed block record"); 00475 00476 if (!TypeList.empty()) 00477 return Error("Multiple TYPE_BLOCKs found!"); 00478 00479 SmallVector<uint64_t, 64> Record; 00480 unsigned NumRecords = 0; 00481 00482 // Read all the records for this type table. 00483 while (1) { 00484 unsigned Code = Stream.ReadCode(); 00485 if (Code == bitc::END_BLOCK) { 00486 if (NumRecords != TypeList.size()) 00487 return Error("Invalid type forward reference in TYPE_BLOCK"); 00488 if (Stream.ReadBlockEnd()) 00489 return Error("Error at end of type table block"); 00490 return false; 00491 } 00492 00493 if (Code == bitc::ENTER_SUBBLOCK) { 00494 // No known subblocks, always skip them. 00495 Stream.ReadSubBlockID(); 00496 if (Stream.SkipBlock()) 00497 return Error("Malformed block record"); 00498 continue; 00499 } 00500 00501 if (Code == bitc::DEFINE_ABBREV) { 00502 Stream.ReadAbbrevRecord(); 00503 continue; 00504 } 00505 00506 // Read a record. 00507 Record.clear(); 00508 const Type *ResultTy = 0; 00509 switch (Stream.ReadRecord(Code, Record)) { 00510 default: // Default behavior: unknown type. 00511 ResultTy = 0; 00512 break; 00513 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 00514 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 00515 // type list. This allows us to reserve space. 00516 if (Record.size() < 1) 00517 return Error("Invalid TYPE_CODE_NUMENTRY record"); 00518 TypeList.reserve(Record[0]); 00519 continue; 00520 case bitc::TYPE_CODE_VOID: // VOID 00521 ResultTy = Type::getVoidTy(Context); 00522 break; 00523 case bitc::TYPE_CODE_FLOAT: // FLOAT 00524 ResultTy = Type::getFloatTy(Context); 00525 break; 00526 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 00527 ResultTy = Type::getDoubleTy(Context); 00528 break; 00529 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 00530 ResultTy = Type::getX86_FP80Ty(Context); 00531 break; 00532 case bitc::TYPE_CODE_FP128: // FP128 00533 ResultTy = Type::getFP128Ty(Context); 00534 break; 00535 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 00536 ResultTy = Type::getPPC_FP128Ty(Context); 00537 break; 00538 case bitc::TYPE_CODE_LABEL: // LABEL 00539 ResultTy = Type::getLabelTy(Context); 00540 break; 00541 case bitc::TYPE_CODE_OPAQUE: // OPAQUE 00542 ResultTy = 0; 00543 break; 00544 case bitc::TYPE_CODE_METADATA: // METADATA 00545 ResultTy = Type::getMetadataTy(Context); 00546 break; 00547 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 00548 if (Record.size() < 1) 00549 return Error("Invalid Integer type record"); 00550 00551 ResultTy = IntegerType::get(Context, Record[0]); 00552 break; 00553 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 00554 // [pointee type, address space] 00555 if (Record.size() < 1) 00556 return Error("Invalid POINTER type record"); 00557 unsigned AddressSpace = 0; 00558 if (Record.size() == 2) 00559 AddressSpace = Record[1]; 00560 ResultTy = PointerType::get(getTypeByID(Record[0], true), 00561 AddressSpace); 00562 break; 00563 } 00564 case bitc::TYPE_CODE_FUNCTION: { 00565 // FIXME: attrid is dead, remove it in LLVM 3.0 00566 // FUNCTION: [vararg, attrid, retty, paramty x N] 00567 if (Record.size() < 3) 00568 return Error("Invalid FUNCTION type record"); 00569 std::vector<const Type*> ArgTys; 00570 for (unsigned i = 3, e = Record.size(); i != e; ++i) 00571 ArgTys.push_back(getTypeByID(Record[i], true)); 00572 00573 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys, 00574 Record[0]); 00575 break; 00576 } 00577 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N] 00578 if (Record.size() < 1) 00579 return Error("Invalid STRUCT type record"); 00580 std::vector<const Type*> EltTys; 00581 for (unsigned i = 1, e = Record.size(); i != e; ++i) 00582 EltTys.push_back(getTypeByID(Record[i], true)); 00583 ResultTy = StructType::get(Context, EltTys, Record[0]); 00584 break; 00585 } 00586 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 00587 if (Record.size() < 2) 00588 return Error("Invalid ARRAY type record"); 00589 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]); 00590 break; 00591 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 00592 if (Record.size() < 2) 00593 return Error("Invalid VECTOR type record"); 00594 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]); 00595 break; 00596 } 00597 00598 if (NumRecords == TypeList.size()) { 00599 // If this is a new type slot, just append it. 00600 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context)); 00601 ++NumRecords; 00602 } else if (ResultTy == 0) { 00603 // Otherwise, this was forward referenced, so an opaque type was created, 00604 // but the result type is actually just an opaque. Leave the one we 00605 // created previously. 00606 ++NumRecords; 00607 } else { 00608 // Otherwise, this was forward referenced, so an opaque type was created. 00609 // Resolve the opaque type to the real type now. 00610 assert(NumRecords < TypeList.size() && "Typelist imbalance"); 00611 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get()); 00612 00613 // Don't directly push the new type on the Tab. Instead we want to replace 00614 // the opaque type we previously inserted with the new concrete value. The 00615 // refinement from the abstract (opaque) type to the new type causes all 00616 // uses of the abstract type to use the concrete type (NewTy). This will 00617 // also cause the opaque type to be deleted. 00618 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy); 00619 00620 // This should have replaced the old opaque type with the new type in the 00621 // value table... or with a preexisting type that was already in the 00622 // system. Let's just make sure it did. 00623 assert(TypeList[NumRecords-1].get() != OldTy && 00624 "refineAbstractType didn't work!"); 00625 } 00626 } 00627 } 00628 00629 00630 bool BitcodeReader::ParseTypeSymbolTable() { 00631 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID)) 00632 return Error("Malformed block record"); 00633 00634 SmallVector<uint64_t, 64> Record; 00635 00636 // Read all the records for this type table. 00637 std::string TypeName; 00638 while (1) { 00639 unsigned Code = Stream.ReadCode(); 00640 if (Code == bitc::END_BLOCK) { 00641 if (Stream.ReadBlockEnd()) 00642 return Error("Error at end of type symbol table block"); 00643 return false; 00644 } 00645 00646 if (Code == bitc::ENTER_SUBBLOCK) { 00647 // No known subblocks, always skip them. 00648 Stream.ReadSubBlockID(); 00649 if (Stream.SkipBlock()) 00650 return Error("Malformed block record"); 00651 continue; 00652 } 00653 00654 if (Code == bitc::DEFINE_ABBREV) { 00655 Stream.ReadAbbrevRecord(); 00656 continue; 00657 } 00658 00659 // Read a record. 00660 Record.clear(); 00661 switch (Stream.ReadRecord(Code, Record)) { 00662 default: // Default behavior: unknown type. 00663 break; 00664 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N] 00665 if (ConvertToString(Record, 1, TypeName)) 00666 return Error("Invalid TST_ENTRY record"); 00667 unsigned TypeID = Record[0]; 00668 if (TypeID >= TypeList.size()) 00669 return Error("Invalid Type ID in TST_ENTRY record"); 00670 00671 TheModule->addTypeName(TypeName, TypeList[TypeID].get()); 00672 TypeName.clear(); 00673 break; 00674 } 00675 } 00676 } 00677 00678 bool BitcodeReader::ParseValueSymbolTable() { 00679 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 00680 return Error("Malformed block record"); 00681 00682 SmallVector<uint64_t, 64> Record; 00683 00684 // Read all the records for this value table. 00685 SmallString<128> ValueName; 00686 while (1) { 00687 unsigned Code = Stream.ReadCode(); 00688 if (Code == bitc::END_BLOCK) { 00689 if (Stream.ReadBlockEnd()) 00690 return Error("Error at end of value symbol table block"); 00691 return false; 00692 } 00693 if (Code == bitc::ENTER_SUBBLOCK) { 00694 // No known subblocks, always skip them. 00695 Stream.ReadSubBlockID(); 00696 if (Stream.SkipBlock()) 00697 return Error("Malformed block record"); 00698 continue; 00699 } 00700 00701 if (Code == bitc::DEFINE_ABBREV) { 00702 Stream.ReadAbbrevRecord(); 00703 continue; 00704 } 00705 00706 // Read a record. 00707 Record.clear(); 00708 switch (Stream.ReadRecord(Code, Record)) { 00709 default: // Default behavior: unknown type. 00710 break; 00711 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 00712 if (ConvertToString(Record, 1, ValueName)) 00713 return Error("Invalid VST_ENTRY record"); 00714 unsigned ValueID = Record[0]; 00715 if (ValueID >= ValueList.size()) 00716 return Error("Invalid Value ID in VST_ENTRY record"); 00717 Value *V = ValueList[ValueID]; 00718 00719 V->setName(StringRef(ValueName.data(), ValueName.size())); 00720 ValueName.clear(); 00721 break; 00722 } 00723 case bitc::VST_CODE_BBENTRY: { 00724 if (ConvertToString(Record, 1, ValueName)) 00725 return Error("Invalid VST_BBENTRY record"); 00726 BasicBlock *BB = getBasicBlock(Record[0]); 00727 if (BB == 0) 00728 return Error("Invalid BB ID in VST_BBENTRY record"); 00729 00730 BB->setName(StringRef(ValueName.data(), ValueName.size())); 00731 ValueName.clear(); 00732 break; 00733 } 00734 } 00735 } 00736 } 00737 00738 bool BitcodeReader::ParseMetadata() { 00739 unsigned NextValueNo = MDValueList.size(); 00740 00741 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 00742 return Error("Malformed block record"); 00743 00744 SmallVector<uint64_t, 64> Record; 00745 00746 // Read all the records. 00747 while (1) { 00748 unsigned Code = Stream.ReadCode(); 00749 if (Code == bitc::END_BLOCK) { 00750 if (Stream.ReadBlockEnd()) 00751 return Error("Error at end of PARAMATTR block"); 00752 return false; 00753 } 00754 00755 if (Code == bitc::ENTER_SUBBLOCK) { 00756 // No known subblocks, always skip them. 00757 Stream.ReadSubBlockID(); 00758 if (Stream.SkipBlock()) 00759 return Error("Malformed block record"); 00760 continue; 00761 } 00762 00763 if (Code == bitc::DEFINE_ABBREV) { 00764 Stream.ReadAbbrevRecord(); 00765 continue; 00766 } 00767 00768 // Read a record. 00769 Record.clear(); 00770 switch (Stream.ReadRecord(Code, Record)) { 00771 default: // Default behavior: ignore. 00772 break; 00773 case bitc::METADATA_NAME: { 00774 // Read named of the named metadata. 00775 unsigned NameLength = Record.size(); 00776 SmallString<8> Name; 00777 Name.resize(NameLength); 00778 for (unsigned i = 0; i != NameLength; ++i) 00779 Name[i] = Record[i]; 00780 Record.clear(); 00781 Code = Stream.ReadCode(); 00782 00783 // METADATA_NAME is always followed by METADATA_NAMED_NODE. 00784 if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE) 00785 assert ( 0 && "Inavlid Named Metadata record"); 00786 00787 // Read named metadata elements. 00788 unsigned Size = Record.size(); 00789 SmallVector<MetadataBase*, 8> Elts; 00790 for (unsigned i = 0; i != Size; ++i) { 00791 Value *MD = MDValueList.getValueFwdRef(Record[i]); 00792 if (MetadataBase *B = dyn_cast<MetadataBase>(MD)) 00793 Elts.push_back(B); 00794 } 00795 Value *V = NamedMDNode::Create(Context, Name.str(), Elts.data(), 00796 Elts.size(), TheModule); 00797 MDValueList.AssignValue(V, NextValueNo++); 00798 break; 00799 } 00800 case bitc::METADATA_NODE: { 00801 if (Record.empty() || Record.size() % 2 == 1) 00802 return Error("Invalid METADATA_NODE record"); 00803 00804 unsigned Size = Record.size(); 00805 SmallVector<Value*, 8> Elts; 00806 for (unsigned i = 0; i != Size; i += 2) { 00807 const Type *Ty = getTypeByID(Record[i], false); 00808 if (Ty == Type::getMetadataTy(Context)) 00809 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1])); 00810 else if (Ty != Type::getVoidTy(Context)) 00811 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty)); 00812 else 00813 Elts.push_back(NULL); 00814 } 00815 Value *V = MDNode::get(Context, &Elts[0], Elts.size()); 00816 MDValueList.AssignValue(V, NextValueNo++); 00817 break; 00818 } 00819 case bitc::METADATA_STRING: { 00820 unsigned MDStringLength = Record.size(); 00821 SmallString<8> String; 00822 String.resize(MDStringLength); 00823 for (unsigned i = 0; i != MDStringLength; ++i) 00824 String[i] = Record[i]; 00825 Value *V = MDString::get(Context, 00826 StringRef(String.data(), String.size())); 00827 MDValueList.AssignValue(V, NextValueNo++); 00828 break; 00829 } 00830 } 00831 } 00832 } 00833 00834 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in 00835 /// the LSB for dense VBR encoding. 00836 static uint64_t DecodeSignRotatedValue(uint64_t V) { 00837 if ((V & 1) == 0) 00838 return V >> 1; 00839 if (V != 1) 00840 return -(V >> 1); 00841 // There is no such thing as -0 with integers. "-0" really means MININT. 00842 return 1ULL << 63; 00843 } 00844 00845 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 00846 /// values and aliases that we can. 00847 bool BitcodeReader::ResolveGlobalAndAliasInits() { 00848 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 00849 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 00850 00851 GlobalInitWorklist.swap(GlobalInits); 00852 AliasInitWorklist.swap(AliasInits); 00853 00854 while (!GlobalInitWorklist.empty()) { 00855 unsigned ValID = GlobalInitWorklist.back().second; 00856 if (ValID >= ValueList.size()) { 00857 // Not ready to resolve this yet, it requires something later in the file. 00858 GlobalInits.push_back(GlobalInitWorklist.back()); 00859 } else { 00860 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 00861 GlobalInitWorklist.back().first->setInitializer(C); 00862 else 00863 return Error("Global variable initializer is not a constant!"); 00864 } 00865 GlobalInitWorklist.pop_back(); 00866 } 00867 00868 while (!AliasInitWorklist.empty()) { 00869 unsigned ValID = AliasInitWorklist.back().second; 00870 if (ValID >= ValueList.size()) { 00871 AliasInits.push_back(AliasInitWorklist.back()); 00872 } else { 00873 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 00874 AliasInitWorklist.back().first->setAliasee(C); 00875 else 00876 return Error("Alias initializer is not a constant!"); 00877 } 00878 AliasInitWorklist.pop_back(); 00879 } 00880 return false; 00881 } 00882 00883 static void SetOptimizationFlags(Value *V, uint64_t Flags) { 00884 if (OverflowingBinaryOperator *OBO = 00885 dyn_cast<OverflowingBinaryOperator>(V)) { 00886 if (Flags & (1 << bitc::OBO_NO_SIGNED_WRAP)) 00887 OBO->setHasNoSignedWrap(true); 00888 if (Flags & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 00889 OBO->setHasNoUnsignedWrap(true); 00890 } else if (SDivOperator *Div = dyn_cast<SDivOperator>(V)) { 00891 if (Flags & (1 << bitc::SDIV_EXACT)) 00892 Div->setIsExact(true); 00893 } 00894 } 00895 00896 bool BitcodeReader::ParseConstants() { 00897 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 00898 return Error("Malformed block record"); 00899 00900 SmallVector<uint64_t, 64> Record; 00901 00902 // Read all the records for this value table. 00903 const Type *CurTy = Type::getInt32Ty(Context); 00904 unsigned NextCstNo = ValueList.size(); 00905 while (1) { 00906 unsigned Code = Stream.ReadCode(); 00907 if (Code == bitc::END_BLOCK) 00908 break; 00909 00910 if (Code == bitc::ENTER_SUBBLOCK) { 00911 // No known subblocks, always skip them. 00912 Stream.ReadSubBlockID(); 00913 if (Stream.SkipBlock()) 00914 return Error("Malformed block record"); 00915 continue; 00916 } 00917 00918 if (Code == bitc::DEFINE_ABBREV) { 00919 Stream.ReadAbbrevRecord(); 00920 continue; 00921 } 00922 00923 // Read a record. 00924 Record.clear(); 00925 Value *V = 0; 00926 unsigned BitCode = Stream.ReadRecord(Code, Record); 00927 switch (BitCode) { 00928 default: // Default behavior: unknown constant 00929 case bitc::CST_CODE_UNDEF: // UNDEF 00930 V = UndefValue::get(CurTy); 00931 break; 00932 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 00933 if (Record.empty()) 00934 return Error("Malformed CST_SETTYPE record"); 00935 if (Record[0] >= TypeList.size()) 00936 return Error("Invalid Type ID in CST_SETTYPE record"); 00937 CurTy = TypeList[Record[0]]; 00938 continue; // Skip the ValueList manipulation. 00939 case bitc::CST_CODE_NULL: // NULL 00940 V = Constant::getNullValue(CurTy); 00941 break; 00942 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 00943 if (!isa<IntegerType>(CurTy) || Record.empty()) 00944 return Error("Invalid CST_INTEGER record"); 00945 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0])); 00946 break; 00947 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 00948 if (!isa<IntegerType>(CurTy) || Record.empty()) 00949 return Error("Invalid WIDE_INTEGER record"); 00950 00951 unsigned NumWords = Record.size(); 00952 SmallVector<uint64_t, 8> Words; 00953 Words.resize(NumWords); 00954 for (unsigned i = 0; i != NumWords; ++i) 00955 Words[i] = DecodeSignRotatedValue(Record[i]); 00956 V = ConstantInt::get(Context, 00957 APInt(cast<IntegerType>(CurTy)->getBitWidth(), 00958 NumWords, &Words[0])); 00959 break; 00960 } 00961 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 00962 if (Record.empty()) 00963 return Error("Invalid FLOAT record"); 00964 if (CurTy == Type::getFloatTy(Context)) 00965 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0]))); 00966 else if (CurTy == Type::getDoubleTy(Context)) 00967 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0]))); 00968 else if (CurTy == Type::getX86_FP80Ty(Context)) { 00969 // Bits are not stored the same way as a normal i80 APInt, compensate. 00970 uint64_t Rearrange[2]; 00971 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 00972 Rearrange[1] = Record[0] >> 48; 00973 V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange))); 00974 } else if (CurTy == Type::getFP128Ty(Context)) 00975 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true)); 00976 else if (CurTy == Type::getPPC_FP128Ty(Context)) 00977 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]))); 00978 else 00979 V = UndefValue::get(CurTy); 00980 break; 00981 } 00982 00983 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 00984 if (Record.empty()) 00985 return Error("Invalid CST_AGGREGATE record"); 00986 00987 unsigned Size = Record.size(); 00988 std::vector<Constant*> Elts; 00989 00990 if (const StructType *STy = dyn_cast<StructType>(CurTy)) { 00991 for (unsigned i = 0; i != Size; ++i) 00992 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 00993 STy->getElementType(i))); 00994 V = ConstantStruct::get(STy, Elts); 00995 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 00996 const Type *EltTy = ATy->getElementType(); 00997 for (unsigned i = 0; i != Size; ++i) 00998 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 00999 V = ConstantArray::get(ATy, Elts); 01000 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 01001 const Type *EltTy = VTy->getElementType(); 01002 for (unsigned i = 0; i != Size; ++i) 01003 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 01004 V = ConstantVector::get(Elts); 01005 } else { 01006 V = UndefValue::get(CurTy); 01007 } 01008 break; 01009 } 01010 case bitc::CST_CODE_STRING: { // STRING: [values] 01011 if (Record.empty()) 01012 return Error("Invalid CST_AGGREGATE record"); 01013 01014 const ArrayType *ATy = cast<ArrayType>(CurTy); 01015 const Type *EltTy = ATy->getElementType(); 01016 01017 unsigned Size = Record.size(); 01018 std::vector<Constant*> Elts; 01019 for (unsigned i = 0; i != Size; ++i) 01020 Elts.push_back(ConstantInt::get(EltTy, Record[i])); 01021 V = ConstantArray::get(ATy, Elts); 01022 break; 01023 } 01024 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 01025 if (Record.empty()) 01026 return Error("Invalid CST_AGGREGATE record"); 01027 01028 const ArrayType *ATy = cast<ArrayType>(CurTy); 01029 const Type *EltTy = ATy->getElementType(); 01030 01031 unsigned Size = Record.size(); 01032 std::vector<Constant*> Elts; 01033 for (unsigned i = 0; i != Size; ++i) 01034 Elts.push_back(ConstantInt::get(EltTy, Record[i])); 01035 Elts.push_back(Constant::getNullValue(EltTy)); 01036 V = ConstantArray::get(ATy, Elts); 01037 break; 01038 } 01039 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 01040 if (Record.size() < 3) return Error("Invalid CE_BINOP record"); 01041 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 01042 if (Opc < 0) { 01043 V = UndefValue::get(CurTy); // Unknown binop. 01044 } else { 01045 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 01046 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 01047 V = ConstantExpr::get(Opc, LHS, RHS); 01048 } 01049 if (Record.size() >= 4) 01050 SetOptimizationFlags(V, Record[3]); 01051 break; 01052 } 01053 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 01054 if (Record.size() < 3) return Error("Invalid CE_CAST record"); 01055 int Opc = GetDecodedCastOpcode(Record[0]); 01056 if (Opc < 0) { 01057 V = UndefValue::get(CurTy); // Unknown cast. 01058 } else { 01059 const Type *OpTy = getTypeByID(Record[1]); 01060 if (!OpTy) return Error("Invalid CE_CAST record"); 01061 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 01062 V = ConstantExpr::getCast(Opc, Op, CurTy); 01063 } 01064 break; 01065 } 01066 case bitc::CST_CODE_CE_INBOUNDS_GEP: 01067 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 01068 if (Record.size() & 1) return Error("Invalid CE_GEP record"); 01069 SmallVector<Constant*, 16> Elts; 01070 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 01071 const Type *ElTy = getTypeByID(Record[i]); 01072 if (!ElTy) return Error("Invalid CE_GEP record"); 01073 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 01074 } 01075 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], 01076 Elts.size()-1); 01077 if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) 01078 cast<GEPOperator>(V)->setIsInBounds(true); 01079 break; 01080 } 01081 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#] 01082 if (Record.size() < 3) return Error("Invalid CE_SELECT record"); 01083 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 01084 Type::getInt1Ty(Context)), 01085 ValueList.getConstantFwdRef(Record[1],CurTy), 01086 ValueList.getConstantFwdRef(Record[2],CurTy)); 01087 break; 01088 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] 01089 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record"); 01090 const VectorType *OpTy = 01091 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 01092 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record"); 01093 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 01094 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 01095 V = ConstantExpr::getExtractElement(Op0, Op1); 01096 break; 01097 } 01098 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval] 01099 const VectorType *OpTy = dyn_cast<VectorType>(CurTy); 01100 if (Record.size() < 3 || OpTy == 0) 01101 return Error("Invalid CE_INSERTELT record"); 01102 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 01103 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 01104 OpTy->getElementType()); 01105 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 01106 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 01107 break; 01108 } 01109 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 01110 const VectorType *OpTy = dyn_cast<VectorType>(CurTy); 01111 if (Record.size() < 3 || OpTy == 0) 01112 return Error("Invalid CE_SHUFFLEVEC record"); 01113 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 01114 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 01115 const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 01116 OpTy->getNumElements()); 01117 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 01118 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 01119 break; 01120 } 01121 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 01122 const VectorType *RTy = dyn_cast<VectorType>(CurTy); 01123 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0])); 01124 if (Record.size() < 4 || RTy == 0 || OpTy == 0) 01125 return Error("Invalid CE_SHUFVEC_EX record"); 01126 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 01127 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 01128 const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 01129 RTy->getNumElements()); 01130 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 01131 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 01132 break; 01133 } 01134 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 01135 if (Record.size() < 4) return Error("Invalid CE_CMP record"); 01136 const Type *OpTy = getTypeByID(Record[0]); 01137 if (OpTy == 0) return Error("Invalid CE_CMP record"); 01138 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 01139 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 01140 01141 if (OpTy->isFloatingPoint()) 01142 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 01143 else 01144 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 01145 break; 01146 } 01147 case bitc::CST_CODE_INLINEASM: { 01148 if (Record.size() < 2) return Error("Invalid INLINEASM record"); 01149 std::string AsmStr, ConstrStr; 01150 bool HasSideEffects = Record[0]; 01151 unsigned AsmStrSize = Record[1]; 01152 if (2+AsmStrSize >= Record.size()) 01153 return Error("Invalid INLINEASM record"); 01154 unsigned ConstStrSize = Record[2+AsmStrSize]; 01155 if (3+AsmStrSize+ConstStrSize > Record.size()) 01156 return Error("Invalid INLINEASM record"); 01157 01158 for (unsigned i = 0; i != AsmStrSize; ++i) 01159 AsmStr += (char)Record[2+i]; 01160 for (unsigned i = 0; i != ConstStrSize; ++i) 01161 ConstrStr += (char)Record[3+AsmStrSize+i]; 01162 const PointerType *PTy = cast<PointerType>(CurTy); 01163 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 01164 AsmStr, ConstrStr, HasSideEffects); 01165 break; 01166 } 01167 } 01168 01169 ValueList.AssignValue(V, NextCstNo); 01170 ++NextCstNo; 01171 } 01172 01173 if (NextCstNo != ValueList.size()) 01174 return Error("Invalid constant reference!"); 01175 01176 if (Stream.ReadBlockEnd()) 01177 return Error("Error at end of constants block"); 01178 01179 // Once all the constants have been read, go through and resolve forward 01180 // references. 01181 ValueList.ResolveConstantForwardRefs(); 01182 return false; 01183 } 01184 01185 /// RememberAndSkipFunctionBody - When we see the block for a function body, 01186 /// remember where it is and then skip it. This lets us lazily deserialize the 01187 /// functions. 01188 bool BitcodeReader::RememberAndSkipFunctionBody() { 01189 // Get the function we are talking about. 01190 if (FunctionsWithBodies.empty()) 01191 return Error("Insufficient function protos"); 01192 01193 Function *Fn = FunctionsWithBodies.back(); 01194 FunctionsWithBodies.pop_back(); 01195 01196 // Save the current stream state. 01197 uint64_t CurBit = Stream.GetCurrentBitNo(); 01198 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage()); 01199 01200 // Set the functions linkage to GhostLinkage so we know it is lazily 01201 // deserialized. 01202 Fn->setLinkage(GlobalValue::GhostLinkage); 01203 01204 // Skip over the function block for now. 01205 if (Stream.SkipBlock()) 01206 return Error("Malformed block record"); 01207 return false; 01208 } 01209 01210 bool BitcodeReader::ParseModule(const std::string &ModuleID) { 01211 // Reject multiple MODULE_BLOCK's in a single bitstream. 01212 if (TheModule) 01213 return Error("Multiple MODULE_BLOCKs in same stream"); 01214 01215 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 01216 return Error("Malformed block record"); 01217 01218 // Otherwise, create the module. 01219 TheModule = new Module(ModuleID, Context); 01220 01221 SmallVector<uint64_t, 64> Record; 01222 std::vector<std::string> SectionTable; 01223 std::vector<std::string> GCTable; 01224 01225 // Read all the records for this module. 01226 while (!Stream.AtEndOfStream()) { 01227 unsigned Code = Stream.ReadCode(); 01228 if (Code == bitc::END_BLOCK) { 01229 if (Stream.ReadBlockEnd()) 01230 return Error("Error at end of module block"); 01231 01232 // Patch the initializers for globals and aliases up. 01233 ResolveGlobalAndAliasInits(); 01234 if (!GlobalInits.empty() || !AliasInits.empty()) 01235 return Error("Malformed global initializer set"); 01236 if (!FunctionsWithBodies.empty()) 01237 return Error("Too few function bodies found"); 01238 01239 // Look for intrinsic functions which need to be upgraded at some point 01240 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 01241 FI != FE; ++FI) { 01242 Function* NewFn; 01243 if (UpgradeIntrinsicFunction(FI, NewFn)) 01244 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 01245 } 01246 01247 // Force deallocation of memory for these vectors to favor the client that 01248 // want lazy deserialization. 01249 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 01250 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 01251 std::vector<Function*>().swap(FunctionsWithBodies); 01252 return false; 01253 } 01254 01255 if (Code == bitc::ENTER_SUBBLOCK) { 01256 switch (Stream.ReadSubBlockID()) { 01257 default: // Skip unknown content. 01258 if (Stream.SkipBlock()) 01259 return Error("Malformed block record"); 01260 break; 01261 case bitc::BLOCKINFO_BLOCK_ID: 01262 if (Stream.ReadBlockInfoBlock()) 01263 return Error("Malformed BlockInfoBlock"); 01264 break; 01265 case bitc::PARAMATTR_BLOCK_ID: 01266 if (ParseAttributeBlock()) 01267 return true; 01268 break; 01269 case bitc::TYPE_BLOCK_ID: 01270 if (ParseTypeTable()) 01271 return true; 01272 break; 01273 case bitc::TYPE_SYMTAB_BLOCK_ID: 01274 if (ParseTypeSymbolTable()) 01275 return true; 01276 break; 01277 case bitc::VALUE_SYMTAB_BLOCK_ID: 01278 if (ParseValueSymbolTable()) 01279 return true; 01280 break; 01281 case bitc::CONSTANTS_BLOCK_ID: 01282 if (ParseConstants() || ResolveGlobalAndAliasInits()) 01283 return true; 01284 break; 01285 case bitc::METADATA_BLOCK_ID: 01286 if (ParseMetadata()) 01287 return true; 01288 break; 01289 case bitc::FUNCTION_BLOCK_ID: 01290 // If this is the first function body we've seen, reverse the 01291 // FunctionsWithBodies list. 01292 if (!HasReversedFunctionsWithBodies) { 01293 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 01294 HasReversedFunctionsWithBodies = true; 01295 } 01296 01297 if (RememberAndSkipFunctionBody()) 01298 return true; 01299 break; 01300 } 01301 continue; 01302 } 01303 01304 if (Code == bitc::DEFINE_ABBREV) { 01305 Stream.ReadAbbrevRecord(); 01306 continue; 01307 } 01308 01309 // Read a record. 01310 switch (Stream.ReadRecord(Code, Record)) { 01311 default: break; // Default behavior, ignore unknown content. 01312 case bitc::MODULE_CODE_VERSION: // VERSION: [version#] 01313 if (Record.size() < 1) 01314 return Error("Malformed MODULE_CODE_VERSION"); 01315 // Only version #0 is supported so far. 01316 if (Record[0] != 0) 01317 return Error("Unknown bitstream version!"); 01318 break; 01319 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 01320 std::string S; 01321 if (ConvertToString(Record, 0, S)) 01322 return Error("Invalid MODULE_CODE_TRIPLE record"); 01323 TheModule->setTargetTriple(S); 01324 break; 01325 } 01326 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 01327 std::string S; 01328 if (ConvertToString(Record, 0, S)) 01329 return Error("Invalid MODULE_CODE_DATALAYOUT record"); 01330 TheModule->setDataLayout(S); 01331 break; 01332 } 01333 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 01334 std::string S; 01335 if (ConvertToString(Record, 0, S)) 01336 return Error("Invalid MODULE_CODE_ASM record"); 01337 TheModule->setModuleInlineAsm(S); 01338 break; 01339 } 01340 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 01341 std::string S; 01342 if (ConvertToString(Record, 0, S)) 01343 return Error("Invalid MODULE_CODE_DEPLIB record"); 01344 TheModule->addLibrary(S); 01345 break; 01346 } 01347 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 01348 std::string S; 01349 if (ConvertToString(Record, 0, S)) 01350 return Error("Invalid MODULE_CODE_SECTIONNAME record"); 01351 SectionTable.push_back(S); 01352 break; 01353 } 01354 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 01355 std::string S; 01356 if (ConvertToString(Record, 0, S)) 01357 return Error("Invalid MODULE_CODE_GCNAME record"); 01358 GCTable.push_back(S); 01359 break; 01360 } 01361 // GLOBALVAR: [pointer type, isconst, initid, 01362 // linkage, alignment, section, visibility, threadlocal] 01363 case bitc::MODULE_CODE_GLOBALVAR: { 01364 if (Record.size() < 6) 01365 return Error("Invalid MODULE_CODE_GLOBALVAR record"); 01366 const Type *Ty = getTypeByID(Record[0]); 01367 if (!isa<PointerType>(Ty)) 01368 return Error("Global not a pointer type!"); 01369 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 01370 Ty = cast<PointerType>(Ty)->getElementType(); 01371 01372 bool isConstant = Record[1]; 01373 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 01374 unsigned Alignment = (1 << Record[4]) >> 1; 01375 std::string Section; 01376 if (Record[5]) { 01377 if (Record[5]-1 >= SectionTable.size()) 01378 return Error("Invalid section ID"); 01379 Section = SectionTable[Record[5]-1]; 01380 } 01381 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 01382 if (Record.size() > 6) 01383 Visibility = GetDecodedVisibility(Record[6]); 01384 bool isThreadLocal = false; 01385 if (Record.size() > 7) 01386 isThreadLocal = Record[7]; 01387 01388 GlobalVariable *NewGV = 01389 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0, 01390 isThreadLocal, AddressSpace); 01391 NewGV->setAlignment(Alignment); 01392 if (!Section.empty()) 01393 NewGV->setSection(Section); 01394 NewGV->setVisibility(Visibility); 01395 NewGV->setThreadLocal(isThreadLocal); 01396 01397 ValueList.push_back(NewGV); 01398 01399 // Remember which value to use for the global initializer. 01400 if (unsigned InitID = Record[2]) 01401 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 01402 break; 01403 } 01404 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 01405 // alignment, section, visibility, gc] 01406 case bitc::MODULE_CODE_FUNCTION: { 01407 if (Record.size() < 8) 01408 return Error("Invalid MODULE_CODE_FUNCTION record"); 01409 const Type *Ty = getTypeByID(Record[0]); 01410 if (!isa<PointerType>(Ty)) 01411 return Error("Function not a pointer type!"); 01412 const FunctionType *FTy = 01413 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 01414 if (!FTy) 01415 return Error("Function not a pointer to function type!"); 01416 01417 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 01418 "", TheModule); 01419 01420 Func->setCallingConv(Record[1]); 01421 bool isProto = Record[2]; 01422 Func->setLinkage(GetDecodedLinkage(Record[3])); 01423 Func->setAttributes(getAttributes(Record[4])); 01424 01425 Func->setAlignment((1 << Record[5]) >> 1); 01426 if (Record[6]) { 01427 if (Record[6]-1 >= SectionTable.size()) 01428 return Error("Invalid section ID"); 01429 Func->setSection(SectionTable[Record[6]-1]); 01430 } 01431 Func->setVisibility(GetDecodedVisibility(Record[7])); 01432 if (Record.size() > 8 && Record[8]) { 01433 if (Record[8]-1 > GCTable.size()) 01434 return Error("Invalid GC ID"); 01435 Func->setGC(GCTable[Record[8]-1].c_str()); 01436 } 01437 ValueList.push_back(Func); 01438 01439 // If this is a function with a body, remember the prototype we are 01440 // creating now, so that we can match up the body with them later. 01441 if (!isProto) 01442 FunctionsWithBodies.push_back(Func); 01443 break; 01444 } 01445 // ALIAS: [alias type, aliasee val#, linkage] 01446 // ALIAS: [alias type, aliasee val#, linkage, visibility] 01447 case bitc::MODULE_CODE_ALIAS: { 01448 if (Record.size() < 3) 01449 return Error("Invalid MODULE_ALIAS record"); 01450 const Type *Ty = getTypeByID(Record[0]); 01451 if (!isa<PointerType>(Ty)) 01452 return Error("Function not a pointer type!"); 01453 01454 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]), 01455 "", 0, TheModule); 01456 // Old bitcode files didn't have visibility field. 01457 if (Record.size() > 3) 01458 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 01459 ValueList.push_back(NewGA); 01460 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 01461 break; 01462 } 01463 /// MODULE_CODE_PURGEVALS: [numvals] 01464 case bitc::MODULE_CODE_PURGEVALS: 01465 // Trim down the value list to the specified size. 01466 if (Record.size() < 1 || Record[0] > ValueList.size()) 01467 return Error("Invalid MODULE_PURGEVALS record"); 01468 ValueList.shrinkTo(Record[0]); 01469 break; 01470 } 01471 Record.clear(); 01472 } 01473 01474 return Error("Premature end of bitstream"); 01475 } 01476 01477 bool BitcodeReader::ParseBitcode() { 01478 TheModule = 0; 01479 01480 if (Buffer->getBufferSize() & 3) 01481 return Error("Bitcode stream should be a multiple of 4 bytes in length"); 01482 01483 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart(); 01484 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 01485 01486 // If we have a wrapper header, parse it and ignore the non-bc file contents. 01487 // The magic number is 0x0B17C0DE stored in little endian. 01488 if (isBitcodeWrapper(BufPtr, BufEnd)) 01489 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd)) 01490 return Error("Invalid bitcode wrapper header"); 01491 01492 StreamFile.init(BufPtr, BufEnd); 01493 Stream.init(StreamFile); 01494 01495 // Sniff for the signature. 01496 if (Stream.Read(8) != 'B' || 01497 Stream.Read(8) != 'C' || 01498 Stream.Read(4) != 0x0 || 01499 Stream.Read(4) != 0xC || 01500 Stream.Read(4) != 0xE || 01501 Stream.Read(4) != 0xD) 01502 return Error("Invalid bitcode signature"); 01503 01504 // We expect a number of well-defined blocks, though we don't necessarily 01505 // need to understand them all. 01506 while (!Stream.AtEndOfStream()) { 01507 unsigned Code = Stream.ReadCode(); 01508 01509 if (Code != bitc::ENTER_SUBBLOCK) 01510 return Error("Invalid record at top-level"); 01511 01512 unsigned BlockID = Stream.ReadSubBlockID(); 01513 01514 // We only know the MODULE subblock ID. 01515 switch (BlockID) { 01516 case bitc::BLOCKINFO_BLOCK_ID: 01517 if (Stream.ReadBlockInfoBlock()) 01518 return Error("Malformed BlockInfoBlock"); 01519 break; 01520 case bitc::MODULE_BLOCK_ID: 01521 if (ParseModule(Buffer->getBufferIdentifier())) 01522 return true; 01523 break; 01524 default: 01525 if (Stream.SkipBlock()) 01526 return Error("Malformed block record"); 01527 break; 01528 } 01529 } 01530 01531 return false; 01532 } 01533 01534 01535 /// ParseFunctionBody - Lazily parse the specified function body block. 01536 bool BitcodeReader::ParseFunctionBody(Function *F) { 01537 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 01538 return Error("Malformed block record"); 01539 01540 unsigned ModuleValueListSize = ValueList.size(); 01541 01542 // Add all the function arguments to the value table. 01543 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 01544 ValueList.push_back(I); 01545 01546 unsigned NextValueNo = ValueList.size(); 01547 BasicBlock *CurBB = 0; 01548 unsigned CurBBNo = 0; 01549 01550 // Read all the records. 01551 SmallVector<uint64_t, 64> Record; 01552 while (1) { 01553 unsigned Code = Stream.ReadCode(); 01554 if (Code == bitc::END_BLOCK) { 01555 if (Stream.ReadBlockEnd()) 01556 return Error("Error at end of function block"); 01557 break; 01558 } 01559 01560 if (Code == bitc::ENTER_SUBBLOCK) { 01561 switch (Stream.ReadSubBlockID()) { 01562 default: // Skip unknown content. 01563 if (Stream.SkipBlock()) 01564 return Error("Malformed block record"); 01565 break; 01566 case bitc::CONSTANTS_BLOCK_ID: 01567 if (ParseConstants()) return true; 01568 NextValueNo = ValueList.size(); 01569 break; 01570 case bitc::VALUE_SYMTAB_BLOCK_ID: 01571 if (ParseValueSymbolTable()) return true; 01572 break; 01573 } 01574 continue; 01575 } 01576 01577 if (Code == bitc::DEFINE_ABBREV) { 01578 Stream.ReadAbbrevRecord(); 01579 continue; 01580 } 01581 01582 // Read a record. 01583 Record.clear(); 01584 Instruction *I = 0; 01585 unsigned BitCode = Stream.ReadRecord(Code, Record); 01586 switch (BitCode) { 01587 default: // Default behavior: reject 01588 return Error("Unknown instruction"); 01589 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 01590 if (Record.size() < 1 || Record[0] == 0) 01591 return Error("Invalid DECLAREBLOCKS record"); 01592 // Create all the basic blocks for the function. 01593 FunctionBBs.resize(Record[0]); 01594 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 01595 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 01596 CurBB = FunctionBBs[0]; 01597 continue; 01598 01599 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 01600 unsigned OpNum = 0; 01601 Value *LHS, *RHS; 01602 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 01603 getValue(Record, OpNum, LHS->getType(), RHS) || 01604 OpNum+1 > Record.size()) 01605 return Error("Invalid BINOP record"); 01606 01607 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 01608 if (Opc == -1) return Error("Invalid BINOP record"); 01609 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 01610 if (OpNum < Record.size()) 01611 SetOptimizationFlags(I, Record[3]); 01612 break; 01613 } 01614 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 01615 unsigned OpNum = 0; 01616 Value *Op; 01617 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 01618 OpNum+2 != Record.size()) 01619 return Error("Invalid CAST record"); 01620 01621 const Type *ResTy = getTypeByID(Record[OpNum]); 01622 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 01623 if (Opc == -1 || ResTy == 0) 01624 return Error("Invalid CAST record"); 01625 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 01626 break; 01627 } 01628 case bitc::FUNC_CODE_INST_INBOUNDS_GEP: 01629 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 01630 unsigned OpNum = 0; 01631 Value *BasePtr; 01632 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 01633 return Error("Invalid GEP record"); 01634 01635 SmallVector<Value*, 16> GEPIdx; 01636 while (OpNum != Record.size()) { 01637 Value *Op; 01638 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 01639 return Error("Invalid GEP record"); 01640 GEPIdx.push_back(Op); 01641 } 01642 01643 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end()); 01644 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP) 01645 cast<GEPOperator>(I)->setIsInBounds(true); 01646 break; 01647 } 01648 01649 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 01650 // EXTRACTVAL: [opty, opval, n x indices] 01651 unsigned OpNum = 0; 01652 Value *Agg; 01653 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 01654 return Error("Invalid EXTRACTVAL record"); 01655 01656 SmallVector<unsigned, 4> EXTRACTVALIdx; 01657 for (unsigned RecSize = Record.size(); 01658 OpNum != RecSize; ++OpNum) { 01659 uint64_t Index = Record[OpNum]; 01660 if ((unsigned)Index != Index) 01661 return Error("Invalid EXTRACTVAL index"); 01662 EXTRACTVALIdx.push_back((unsigned)Index); 01663 } 01664 01665 I = ExtractValueInst::Create(Agg, 01666 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end()); 01667 break; 01668 } 01669 01670 case bitc::FUNC_CODE_INST_INSERTVAL: { 01671 // INSERTVAL: [opty, opval, opty, opval, n x indices] 01672 unsigned OpNum = 0; 01673 Value *Agg; 01674 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 01675 return Error("Invalid INSERTVAL record"); 01676 Value *Val; 01677 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 01678 return Error("Invalid INSERTVAL record"); 01679 01680 SmallVector<unsigned, 4> INSERTVALIdx; 01681 for (unsigned RecSize = Record.size(); 01682 OpNum != RecSize; ++OpNum) { 01683 uint64_t Index = Record[OpNum]; 01684 if ((unsigned)Index != Index) 01685 return Error("Invalid INSERTVAL index"); 01686 INSERTVALIdx.push_back((unsigned)Index); 01687 } 01688 01689 I = InsertValueInst::Create(Agg, Val, 01690 INSERTVALIdx.begin(), INSERTVALIdx.end()); 01691 break; 01692 } 01693 01694 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 01695 // obsolete form of select 01696 // handles select i1 ... in old bitcode 01697 unsigned OpNum = 0; 01698 Value *TrueVal, *FalseVal, *Cond; 01699 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 01700 getValue(Record, OpNum, TrueVal->getType(), FalseVal) || 01701 getValue(Record, OpNum, Type::getInt1Ty(Context), Cond)) 01702 return Error("Invalid SELECT record"); 01703 01704 I = SelectInst::Create(Cond, TrueVal, FalseVal); 01705 break; 01706 } 01707 01708 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 01709 // new form of select 01710 // handles select i1 or select [N x i1] 01711 unsigned OpNum = 0; 01712 Value *TrueVal, *FalseVal, *Cond; 01713 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 01714 getValue(Record, OpNum, TrueVal->getType(), FalseVal) || 01715 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 01716 return Error("Invalid SELECT record"); 01717 01718 // select condition can be either i1 or [N x i1] 01719 if (const VectorType* vector_type = 01720 dyn_cast<const VectorType>(Cond->getType())) { 01721 // expect <n x i1> 01722 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 01723 return Error("Invalid SELECT condition type"); 01724 } else { 01725 // expect i1 01726 if (Cond->getType() != Type::getInt1Ty(Context)) 01727 return Error("Invalid SELECT condition type"); 01728 } 01729 01730 I = SelectInst::Create(Cond, TrueVal, FalseVal); 01731 break; 01732 } 01733 01734 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 01735 unsigned OpNum = 0; 01736 Value *Vec, *Idx; 01737 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 01738 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx)) 01739 return Error("Invalid EXTRACTELT record"); 01740 I = ExtractElementInst::Create(Vec, Idx); 01741 break; 01742 } 01743 01744 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 01745 unsigned OpNum = 0; 01746 Value *Vec, *Elt, *Idx; 01747 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 01748 getValue(Record, OpNum, 01749 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 01750 getValue(Record, OpNum, Type::getInt32Ty(Context), Idx)) 01751 return Error("Invalid INSERTELT record"); 01752 I = InsertElementInst::Create(Vec, Elt, Idx); 01753 break; 01754 } 01755 01756 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 01757 unsigned OpNum = 0; 01758 Value *Vec1, *Vec2, *Mask; 01759 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 01760 getValue(Record, OpNum, Vec1->getType(), Vec2)) 01761 return Error("Invalid SHUFFLEVEC record"); 01762 01763 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 01764 return Error("Invalid SHUFFLEVEC record"); 01765 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 01766 break; 01767 } 01768 01769 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 01770 // Old form of ICmp/FCmp returning bool 01771 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 01772 // both legal on vectors but had different behaviour. 01773 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 01774 // FCmp/ICmp returning bool or vector of bool 01775 01776 unsigned OpNum = 0; 01777 Value *LHS, *RHS; 01778 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 01779 getValue(Record, OpNum, LHS->getType(), RHS) || 01780 OpNum+1 != Record.size()) 01781 return Error("Invalid CMP record"); 01782 01783 if (LHS->getType()->isFPOrFPVector()) 01784 I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS); 01785 else 01786 I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS); 01787 break; 01788 } 01789 01790 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n] 01791 if (Record.size() != 2) 01792 return Error("Invalid GETRESULT record"); 01793 unsigned OpNum = 0; 01794 Value *Op; 01795 getValueTypePair(Record, OpNum, NextValueNo, Op); 01796 unsigned Index = Record[1]; 01797 I = ExtractValueInst::Create(Op, Index); 01798 break; 01799 } 01800 01801 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 01802 { 01803 unsigned Size = Record.size(); 01804 if (Size == 0) { 01805 I = ReturnInst::Create(Context); 01806 break; 01807 } 01808 01809 unsigned OpNum = 0; 01810 SmallVector<Value *,4> Vs; 01811 do { 01812 Value *Op = NULL; 01813 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 01814 return Error("Invalid RET record"); 01815 Vs.push_back(Op); 01816 } while(OpNum != Record.size()); 01817 01818 const Type *ReturnType = F->getReturnType(); 01819 if (Vs.size() > 1 || 01820 (isa<StructType>(ReturnType) && 01821 (Vs.empty() || Vs[0]->getType() != ReturnType))) { 01822 Value *RV = UndefValue::get(ReturnType); 01823 for (unsigned i = 0, e = Vs.size(); i != e; ++i) { 01824 I = InsertValueInst::Create(RV, Vs[i], i, "mrv"); 01825 CurBB->getInstList().push_back(I); 01826 ValueList.AssignValue(I, NextValueNo++); 01827 RV = I; 01828 } 01829 I = ReturnInst::Create(Context, RV); 01830 break; 01831 } 01832 01833 I = ReturnInst::Create(Context, Vs[0]); 01834 break; 01835 } 01836 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 01837 if (Record.size() != 1 && Record.size() != 3) 01838 return Error("Invalid BR record"); 01839 BasicBlock *TrueDest = getBasicBlock(Record[0]); 01840 if (TrueDest == 0) 01841 return Error("Invalid BR record"); 01842 01843 if (Record.size() == 1) 01844 I = BranchInst::Create(TrueDest); 01845 else { 01846 BasicBlock *FalseDest = getBasicBlock(Record[1]); 01847 Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context)); 01848 if (FalseDest == 0 || Cond == 0) 01849 return Error("Invalid BR record"); 01850 I = BranchInst::Create(TrueDest, FalseDest, Cond); 01851 } 01852 break; 01853 } 01854 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops] 01855 if (Record.size() < 3 || (Record.size() & 1) == 0) 01856 return Error("Invalid SWITCH record"); 01857 const Type *OpTy = getTypeByID(Record[0]); 01858 Value *Cond = getFnValueByID(Record[1], OpTy); 01859 BasicBlock *Default = getBasicBlock(Record[2]); 01860 if (OpTy == 0 || Cond == 0 || Default == 0) 01861 return Error("Invalid SWITCH record"); 01862 unsigned NumCases = (Record.size()-3)/2; 01863 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 01864 for (unsigned i = 0, e = NumCases; i != e; ++i) { 01865 ConstantInt *CaseVal = 01866 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 01867 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 01868 if (CaseVal == 0 || DestBB == 0) { 01869 delete SI; 01870 return Error("Invalid SWITCH record!"); 01871 } 01872 SI->addCase(CaseVal, DestBB); 01873 } 01874 I = SI; 01875 break; 01876 } 01877 01878 case bitc::FUNC_CODE_INST_INVOKE: { 01879 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 01880 if (Record.size() < 4) return Error("Invalid INVOKE record"); 01881 AttrListPtr PAL = getAttributes(Record[0]); 01882 unsigned CCInfo = Record[1]; 01883 BasicBlock *NormalBB = getBasicBlock(Record[2]); 01884 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 01885 01886 unsigned OpNum = 4; 01887 Value *Callee; 01888 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 01889 return Error("Invalid INVOKE record"); 01890 01891 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 01892 const FunctionType *FTy = !CalleeTy ? 0 : 01893 dyn_cast<FunctionType>(CalleeTy->getElementType()); 01894 01895 // Check that the right number of fixed parameters are here. 01896 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 || 01897 Record.size() < OpNum+FTy->getNumParams()) 01898 return Error("Invalid INVOKE record"); 01899 01900 SmallVector<Value*, 16> Ops; 01901 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 01902 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 01903 if (Ops.back() == 0) return Error("Invalid INVOKE record"); 01904 } 01905 01906 if (!FTy->isVarArg()) { 01907 if (Record.size() != OpNum) 01908 return Error("Invalid INVOKE record"); 01909 } else { 01910 // Read type/value pairs for varargs params. 01911 while (OpNum != Record.size()) { 01912 Value *Op; 01913 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 01914 return Error("Invalid INVOKE record"); 01915 Ops.push_back(Op); 01916 } 01917 } 01918 01919 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, 01920 Ops.begin(), Ops.end()); 01921 cast<InvokeInst>(I)->setCallingConv(CCInfo); 01922 cast<InvokeInst>(I)->setAttributes(PAL); 01923 break; 01924 } 01925 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND 01926 I = new UnwindInst(Context); 01927 break; 01928 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 01929 I = new UnreachableInst(Context); 01930 break; 01931 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 01932 if (Record.size() < 1 || ((Record.size()-1)&1)) 01933 return Error("Invalid PHI record"); 01934 const Type *Ty = getTypeByID(Record[0]); 01935 if (!Ty) return Error("Invalid PHI record"); 01936 01937 PHINode *PN = PHINode::Create(Ty); 01938 PN->reserveOperandSpace((Record.size()-1)/2); 01939 01940 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 01941 Value *V = getFnValueByID(Record[1+i], Ty); 01942 BasicBlock *BB = getBasicBlock(Record[2+i]); 01943 if (!V || !BB) return Error("Invalid PHI record"); 01944 PN->addIncoming(V, BB); 01945 } 01946 I = PN; 01947 break; 01948 } 01949 01950 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align] 01951 if (Record.size() < 3) 01952 return Error("Invalid MALLOC record"); 01953 const PointerType *Ty = 01954 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 01955 Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context)); 01956 unsigned Align = Record[2]; 01957 if (!Ty || !Size) return Error("Invalid MALLOC record"); 01958 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1); 01959 break; 01960 } 01961 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty] 01962 unsigned OpNum = 0; 01963 Value *Op; 01964 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 01965 OpNum != Record.size()) 01966 return Error("Invalid FREE record"); 01967 I = new FreeInst(Op); 01968 break; 01969 } 01970 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align] 01971 if (Record.size() < 3) 01972 return Error("Invalid ALLOCA record"); 01973 const PointerType *Ty = 01974 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 01975 Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context)); 01976 unsigned Align = Record[2]; 01977 if (!Ty || !Size) return Error("Invalid ALLOCA record"); 01978 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 01979 break; 01980 } 01981 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 01982 unsigned OpNum = 0; 01983 Value *Op; 01984 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 01985 OpNum+2 != Record.size()) 01986 return Error("Invalid LOAD record"); 01987 01988 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 01989 break; 01990 } 01991 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol] 01992 unsigned OpNum = 0; 01993 Value *Val, *Ptr; 01994 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 01995 getValue(Record, OpNum, 01996 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 01997 OpNum+2 != Record.size()) 01998 return Error("Invalid STORE record"); 01999 02000 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 02001 break; 02002 } 02003 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol] 02004 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0. 02005 unsigned OpNum = 0; 02006 Value *Val, *Ptr; 02007 if (getValueTypePair(Record, OpNum, NextValueNo, Val) || 02008 getValue(Record, OpNum, 02009 PointerType::getUnqual(Val->getType()), Ptr)|| 02010 OpNum+2 != Record.size()) 02011 return Error("Invalid STORE record"); 02012 02013 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 02014 break; 02015 } 02016 case bitc::FUNC_CODE_INST_CALL: { 02017 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 02018 if (Record.size() < 3) 02019 return Error("Invalid CALL record"); 02020 02021 AttrListPtr PAL = getAttributes(Record[0]); 02022 unsigned CCInfo = Record[1]; 02023 02024 unsigned OpNum = 2; 02025 Value *Callee; 02026 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 02027 return Error("Invalid CALL record"); 02028 02029 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 02030 const FunctionType *FTy = 0; 02031 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 02032 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 02033 return Error("Invalid CALL record"); 02034 02035 SmallVector<Value*, 16> Args; 02036 // Read the fixed params. 02037 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 02038 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID) 02039 Args.push_back(getBasicBlock(Record[OpNum])); 02040 else 02041 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i))); 02042 if (Args.back() == 0) return Error("Invalid CALL record"); 02043 } 02044 02045 // Read type/value pairs for varargs params. 02046 if (!FTy->isVarArg()) { 02047 if (OpNum != Record.size()) 02048 return Error("Invalid CALL record"); 02049 } else { 02050 while (OpNum != Record.size()) { 02051 Value *Op; 02052 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 02053 return Error("Invalid CALL record"); 02054 Args.push_back(Op); 02055 } 02056 } 02057 02058 I = CallInst::Create(Callee, Args.begin(), Args.end()); 02059 cast<CallInst>(I)->setCallingConv(CCInfo>>1); 02060 cast<CallInst>(I)->setTailCall(CCInfo & 1); 02061 cast<CallInst>(I)->setAttributes(PAL); 02062 break; 02063 } 02064 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 02065 if (Record.size() < 3) 02066 return Error("Invalid VAARG record"); 02067 const Type *OpTy = getTypeByID(Record[0]); 02068 Value *Op = getFnValueByID(Record[1], OpTy); 02069 const Type *ResTy = getTypeByID(Record[2]); 02070 if (!OpTy || !Op || !ResTy) 02071 return Error("Invalid VAARG record"); 02072 I = new VAArgInst(Op, ResTy); 02073 break; 02074 } 02075 } 02076 02077 // Add instruction to end of current BB. If there is no current BB, reject 02078 // this file. 02079 if (CurBB == 0) { 02080 delete I; 02081 return Error("Invalid instruction with no BB"); 02082 } 02083 CurBB->getInstList().push_back(I); 02084 02085 // If this was a terminator instruction, move to the next block. 02086 if (isa<TerminatorInst>(I)) { 02087 ++CurBBNo; 02088 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0; 02089 } 02090 02091 // Non-void values get registered in the value table for future use. 02092 if (I && I->getType() != Type::getVoidTy(Context)) 02093 ValueList.AssignValue(I, NextValueNo++); 02094 } 02095 02096 // Check the function list for unresolved values. 02097 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 02098 if (A->getParent() == 0) { 02099 // We found at least one unresolved value. Nuke them all to avoid leaks. 02100 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 02101 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) { 02102 A->replaceAllUsesWith(UndefValue::get(A->getType())); 02103 delete A; 02104 } 02105 } 02106 return Error("Never resolved value found in function!"); 02107 } 02108 } 02109 02110 // Trim the value list down to the size it was before we parsed this function. 02111 ValueList.shrinkTo(ModuleValueListSize); 02112 std::vector<BasicBlock*>().swap(FunctionBBs); 02113 02114 return false; 02115 } 02116 02117 //===----------------------------------------------------------------------===// 02118 // ModuleProvider implementation 02119 //===----------------------------------------------------------------------===// 02120 02121 02122 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) { 02123 // If it already is material, ignore the request. 02124 if (!F->hasNotBeenReadFromBitcode()) return false; 02125 02126 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII = 02127 DeferredFunctionInfo.find(F); 02128 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 02129 02130 // Move the bit stream to the saved position of the deferred function body and 02131 // restore the real linkage type for the function. 02132 Stream.JumpToBit(DFII->second.first); 02133 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second); 02134 02135 if (ParseFunctionBody(F)) { 02136 if (ErrInfo) *ErrInfo = ErrorString; 02137 return true; 02138 } 02139 02140 // Upgrade any old intrinsic calls in the function. 02141 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 02142 E = UpgradedIntrinsics.end(); I != E; ++I) { 02143 if (I->first != I->second) { 02144 for (Value::use_iterator UI = I->first->use_begin(), 02145 UE = I->first->use_end(); UI != UE; ) { 02146 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 02147 UpgradeIntrinsicCall(CI, I->second); 02148 } 02149 } 02150 } 02151 02152 return false; 02153 } 02154 02155 void BitcodeReader::dematerializeFunction(Function *F) { 02156 // If this function isn't materialized, or if it is a proto, this is a noop. 02157 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration()) 02158 return; 02159 02160 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 02161 02162 // Just forget the function body, we can remat it later. 02163 F->deleteBody(); 02164 F->setLinkage(GlobalValue::GhostLinkage); 02165 } 02166 02167 02168 Module *BitcodeReader::materializeModule(std::string *ErrInfo) { 02169 // Iterate over the module, deserializing any functions that are still on 02170 // disk. 02171 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 02172 F != E; ++F) 02173 if (F->hasNotBeenReadFromBitcode() && 02174 materializeFunction(F, ErrInfo)) 02175 return 0; 02176 02177 // Upgrade any intrinsic calls that slipped through (should not happen!) and 02178 // delete the old functions to clean up. We can't do this unless the entire 02179 // module is materialized because there could always be another function body 02180 // with calls to the old function. 02181 for (std::vector<std::pair<Function*, Function*> >::iterator I = 02182 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 02183 if (I->first != I->second) { 02184 for (Value::use_iterator UI = I->first->use_begin(), 02185 UE = I->first->use_end(); UI != UE; ) { 02186 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 02187 UpgradeIntrinsicCall(CI, I->second); 02188 } 02189 if (!I->first->use_empty()) 02190 I->first->replaceAllUsesWith(I->second); 02191 I->first->eraseFromParent(); 02192 } 02193 } 02194 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 02195 02196 return TheModule; 02197 } 02198 02199 02200 /// This method is provided by the parent ModuleProvde class and overriden 02201 /// here. It simply releases the module from its provided and frees up our 02202 /// state. 02203 /// @brief Release our hold on the generated module 02204 Module *BitcodeReader::releaseModule(std::string *ErrInfo) { 02205 // Since we're losing control of this Module, we must hand it back complete 02206 Module *M = ModuleProvider::releaseModule(ErrInfo); 02207 FreeState(); 02208 return M; 02209 } 02210 02211 02212 //===----------------------------------------------------------------------===// 02213 // External interface 02214 //===----------------------------------------------------------------------===// 02215 02216 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file. 02217 /// 02218 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer, 02219 LLVMContext& Context, 02220 std::string *ErrMsg) { 02221 BitcodeReader *R = new BitcodeReader(Buffer, Context); 02222 if (R->ParseBitcode()) { 02223 if (ErrMsg) 02224 *ErrMsg = R->getErrorString(); 02225 02226 // Don't let the BitcodeReader dtor delete 'Buffer'. 02227 R->releaseMemoryBuffer(); 02228 delete R; 02229 return 0; 02230 } 02231 return R; 02232 } 02233 02234 /// ParseBitcodeFile - Read the specified bitcode file, returning the module. 02235 /// If an error occurs, return null and fill in *ErrMsg if non-null. 02236 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, 02237 std::string *ErrMsg){ 02238 BitcodeReader *R; 02239 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context, 02240 ErrMsg)); 02241 if (!R) return 0; 02242 02243 // Read in the entire module. 02244 Module *M = R->materializeModule(ErrMsg); 02245 02246 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether 02247 // there was an error. 02248 R->releaseMemoryBuffer(); 02249 02250 // If there was no error, tell ModuleProvider not to delete it when its dtor 02251 // is run. 02252 if (M) 02253 M = R->releaseModule(ErrMsg); 02254 02255 delete R; 02256 return M; 02257 }