BitcodeReader.cpp revision 084a844d6d3c4176a8137c7cf980c2b6c7731e34
1//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by Chris Lattner and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This header defines the BitcodeReader class. 11// 12//===----------------------------------------------------------------------===// 13 14#include "BitcodeReader.h" 15#include "llvm/Bitcode/BitstreamReader.h" 16#include "llvm/Constants.h" 17#include "llvm/DerivedTypes.h" 18#include "llvm/Module.h" 19#include "llvm/ADT/SmallString.h" 20#include "llvm/Support/MathExtras.h" 21using namespace llvm; 22 23/// ConvertToString - Convert a string from a record into an std::string, return 24/// true on failure. 25template<typename StrTy> 26static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx, 27 StrTy &Result) { 28 if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1) 29 return true; 30 31 for (unsigned i = 0, e = Record[Idx]; i != e; ++i) 32 Result += (char)Record[Idx+i+1]; 33 return false; 34} 35 36static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) { 37 switch (Val) { 38 default: // Map unknown/new linkages to external 39 case 0: return GlobalValue::ExternalLinkage; 40 case 1: return GlobalValue::WeakLinkage; 41 case 2: return GlobalValue::AppendingLinkage; 42 case 3: return GlobalValue::InternalLinkage; 43 case 4: return GlobalValue::LinkOnceLinkage; 44 case 5: return GlobalValue::DLLImportLinkage; 45 case 6: return GlobalValue::DLLExportLinkage; 46 case 7: return GlobalValue::ExternalWeakLinkage; 47 } 48} 49 50static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 51 switch (Val) { 52 default: // Map unknown visibilities to default. 53 case 0: return GlobalValue::DefaultVisibility; 54 case 1: return GlobalValue::HiddenVisibility; 55 } 56} 57 58static int GetDecodedCastOpcode(unsigned Val) { 59 switch (Val) { 60 default: return -1; 61 case bitc::CAST_TRUNC : return Instruction::Trunc; 62 case bitc::CAST_ZEXT : return Instruction::ZExt; 63 case bitc::CAST_SEXT : return Instruction::SExt; 64 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 65 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 66 case bitc::CAST_UITOFP : return Instruction::UIToFP; 67 case bitc::CAST_SITOFP : return Instruction::SIToFP; 68 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 69 case bitc::CAST_FPEXT : return Instruction::FPExt; 70 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 71 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 72 case bitc::CAST_BITCAST : return Instruction::BitCast; 73 } 74} 75static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) { 76 switch (Val) { 77 default: return -1; 78 case bitc::BINOP_ADD: return Instruction::Add; 79 case bitc::BINOP_SUB: return Instruction::Sub; 80 case bitc::BINOP_MUL: return Instruction::Mul; 81 case bitc::BINOP_UDIV: return Instruction::UDiv; 82 case bitc::BINOP_SDIV: 83 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv; 84 case bitc::BINOP_UREM: return Instruction::URem; 85 case bitc::BINOP_SREM: 86 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem; 87 case bitc::BINOP_SHL: return Instruction::Shl; 88 case bitc::BINOP_LSHR: return Instruction::LShr; 89 case bitc::BINOP_ASHR: return Instruction::AShr; 90 case bitc::BINOP_AND: return Instruction::And; 91 case bitc::BINOP_OR: return Instruction::Or; 92 case bitc::BINOP_XOR: return Instruction::Xor; 93 } 94} 95 96 97namespace { 98 /// @brief A class for maintaining the slot number definition 99 /// as a placeholder for the actual definition for forward constants defs. 100 class ConstantPlaceHolder : public ConstantExpr { 101 ConstantPlaceHolder(); // DO NOT IMPLEMENT 102 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT 103 public: 104 Use Op; 105 ConstantPlaceHolder(const Type *Ty) 106 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1), 107 Op(UndefValue::get(Type::Int32Ty), this) { 108 } 109 }; 110} 111 112Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 113 const Type *Ty) { 114 if (Idx >= size()) { 115 // Insert a bunch of null values. 116 Uses.resize(Idx+1); 117 OperandList = &Uses[0]; 118 NumOperands = Idx+1; 119 } 120 121 if (Uses[Idx]) { 122 assert(Ty == getOperand(Idx)->getType() && 123 "Type mismatch in constant table!"); 124 return cast<Constant>(getOperand(Idx)); 125 } 126 127 // Create and return a placeholder, which will later be RAUW'd. 128 Constant *C = new ConstantPlaceHolder(Ty); 129 Uses[Idx].init(C, this); 130 return C; 131} 132 133 134const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) { 135 // If the TypeID is in range, return it. 136 if (ID < TypeList.size()) 137 return TypeList[ID].get(); 138 if (!isTypeTable) return 0; 139 140 // The type table allows forward references. Push as many Opaque types as 141 // needed to get up to ID. 142 while (TypeList.size() <= ID) 143 TypeList.push_back(OpaqueType::get()); 144 return TypeList.back().get(); 145} 146 147 148bool BitcodeReader::ParseTypeTable(BitstreamReader &Stream) { 149 if (Stream.EnterSubBlock()) 150 return Error("Malformed block record"); 151 152 if (!TypeList.empty()) 153 return Error("Multiple TYPE_BLOCKs found!"); 154 155 SmallVector<uint64_t, 64> Record; 156 unsigned NumRecords = 0; 157 158 // Read all the records for this type table. 159 while (1) { 160 unsigned Code = Stream.ReadCode(); 161 if (Code == bitc::END_BLOCK) { 162 if (NumRecords != TypeList.size()) 163 return Error("Invalid type forward reference in TYPE_BLOCK"); 164 return Stream.ReadBlockEnd(); 165 } 166 167 if (Code == bitc::ENTER_SUBBLOCK) { 168 // No known subblocks, always skip them. 169 Stream.ReadSubBlockID(); 170 if (Stream.SkipBlock()) 171 return Error("Malformed block record"); 172 continue; 173 } 174 175 if (Code == bitc::DEFINE_ABBREV) { 176 Stream.ReadAbbrevRecord(); 177 continue; 178 } 179 180 // Read a record. 181 Record.clear(); 182 const Type *ResultTy = 0; 183 switch (Stream.ReadRecord(Code, Record)) { 184 default: // Default behavior: unknown type. 185 ResultTy = 0; 186 break; 187 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 188 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 189 // type list. This allows us to reserve space. 190 if (Record.size() < 1) 191 return Error("Invalid TYPE_CODE_NUMENTRY record"); 192 TypeList.reserve(Record[0]); 193 continue; 194 case bitc::TYPE_CODE_META: // TYPE_CODE_META: [metacode]... 195 // No metadata supported yet. 196 if (Record.size() < 1) 197 return Error("Invalid TYPE_CODE_META record"); 198 continue; 199 200 case bitc::TYPE_CODE_VOID: // VOID 201 ResultTy = Type::VoidTy; 202 break; 203 case bitc::TYPE_CODE_FLOAT: // FLOAT 204 ResultTy = Type::FloatTy; 205 break; 206 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 207 ResultTy = Type::DoubleTy; 208 break; 209 case bitc::TYPE_CODE_LABEL: // LABEL 210 ResultTy = Type::LabelTy; 211 break; 212 case bitc::TYPE_CODE_OPAQUE: // OPAQUE 213 ResultTy = 0; 214 break; 215 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 216 if (Record.size() < 1) 217 return Error("Invalid Integer type record"); 218 219 ResultTy = IntegerType::get(Record[0]); 220 break; 221 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type] 222 if (Record.size() < 1) 223 return Error("Invalid POINTER type record"); 224 ResultTy = PointerType::get(getTypeByID(Record[0], true)); 225 break; 226 case bitc::TYPE_CODE_FUNCTION: { 227 // FUNCTION: [vararg, retty, #pararms, paramty N] 228 if (Record.size() < 3 || Record.size() < Record[2]+3) 229 return Error("Invalid FUNCTION type record"); 230 std::vector<const Type*> ArgTys; 231 for (unsigned i = 0, e = Record[2]; i != e; ++i) 232 ArgTys.push_back(getTypeByID(Record[3+i], true)); 233 234 // FIXME: PARAM TYS. 235 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys, 236 Record[0]); 237 break; 238 } 239 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N] 240 if (Record.size() < 2 || Record.size() < Record[1]+2) 241 return Error("Invalid STRUCT type record"); 242 std::vector<const Type*> EltTys; 243 for (unsigned i = 0, e = Record[1]; i != e; ++i) 244 EltTys.push_back(getTypeByID(Record[2+i], true)); 245 ResultTy = StructType::get(EltTys, Record[0]); 246 break; 247 } 248 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 249 if (Record.size() < 2) 250 return Error("Invalid ARRAY type record"); 251 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]); 252 break; 253 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 254 if (Record.size() < 2) 255 return Error("Invalid VECTOR type record"); 256 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]); 257 break; 258 } 259 260 if (NumRecords == TypeList.size()) { 261 // If this is a new type slot, just append it. 262 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get()); 263 ++NumRecords; 264 } else if (ResultTy == 0) { 265 // Otherwise, this was forward referenced, so an opaque type was created, 266 // but the result type is actually just an opaque. Leave the one we 267 // created previously. 268 ++NumRecords; 269 } else { 270 // Otherwise, this was forward referenced, so an opaque type was created. 271 // Resolve the opaque type to the real type now. 272 assert(NumRecords < TypeList.size() && "Typelist imbalance"); 273 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get()); 274 275 // Don't directly push the new type on the Tab. Instead we want to replace 276 // the opaque type we previously inserted with the new concrete value. The 277 // refinement from the abstract (opaque) type to the new type causes all 278 // uses of the abstract type to use the concrete type (NewTy). This will 279 // also cause the opaque type to be deleted. 280 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy); 281 282 // This should have replaced the old opaque type with the new type in the 283 // value table... or with a preexisting type that was already in the 284 // system. Let's just make sure it did. 285 assert(TypeList[NumRecords-1].get() != OldTy && 286 "refineAbstractType didn't work!"); 287 } 288 } 289} 290 291 292bool BitcodeReader::ParseTypeSymbolTable(BitstreamReader &Stream) { 293 if (Stream.EnterSubBlock()) 294 return Error("Malformed block record"); 295 296 SmallVector<uint64_t, 64> Record; 297 298 // Read all the records for this type table. 299 std::string TypeName; 300 while (1) { 301 unsigned Code = Stream.ReadCode(); 302 if (Code == bitc::END_BLOCK) 303 return Stream.ReadBlockEnd(); 304 305 if (Code == bitc::ENTER_SUBBLOCK) { 306 // No known subblocks, always skip them. 307 Stream.ReadSubBlockID(); 308 if (Stream.SkipBlock()) 309 return Error("Malformed block record"); 310 continue; 311 } 312 313 if (Code == bitc::DEFINE_ABBREV) { 314 Stream.ReadAbbrevRecord(); 315 continue; 316 } 317 318 // Read a record. 319 Record.clear(); 320 switch (Stream.ReadRecord(Code, Record)) { 321 default: // Default behavior: unknown type. 322 break; 323 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N] 324 if (ConvertToString(Record, 1, TypeName)) 325 return Error("Invalid TST_ENTRY record"); 326 unsigned TypeID = Record[0]; 327 if (TypeID >= TypeList.size()) 328 return Error("Invalid Type ID in TST_ENTRY record"); 329 330 TheModule->addTypeName(TypeName, TypeList[TypeID].get()); 331 TypeName.clear(); 332 break; 333 } 334 } 335} 336 337bool BitcodeReader::ParseValueSymbolTable(BitstreamReader &Stream) { 338 if (Stream.EnterSubBlock()) 339 return Error("Malformed block record"); 340 341 SmallVector<uint64_t, 64> Record; 342 343 // Read all the records for this value table. 344 SmallString<128> ValueName; 345 while (1) { 346 unsigned Code = Stream.ReadCode(); 347 if (Code == bitc::END_BLOCK) 348 return Stream.ReadBlockEnd(); 349 350 if (Code == bitc::ENTER_SUBBLOCK) { 351 // No known subblocks, always skip them. 352 Stream.ReadSubBlockID(); 353 if (Stream.SkipBlock()) 354 return Error("Malformed block record"); 355 continue; 356 } 357 358 if (Code == bitc::DEFINE_ABBREV) { 359 Stream.ReadAbbrevRecord(); 360 continue; 361 } 362 363 // Read a record. 364 Record.clear(); 365 switch (Stream.ReadRecord(Code, Record)) { 366 default: // Default behavior: unknown type. 367 break; 368 case bitc::TST_CODE_ENTRY: // VST_ENTRY: [valueid, namelen, namechar x N] 369 if (ConvertToString(Record, 1, ValueName)) 370 return Error("Invalid TST_ENTRY record"); 371 unsigned ValueID = Record[0]; 372 if (ValueID >= ValueList.size()) 373 return Error("Invalid Value ID in VST_ENTRY record"); 374 Value *V = ValueList[ValueID]; 375 376 V->setName(&ValueName[0], ValueName.size()); 377 ValueName.clear(); 378 break; 379 } 380 } 381} 382 383/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in 384/// the LSB for dense VBR encoding. 385static uint64_t DecodeSignRotatedValue(uint64_t V) { 386 if ((V & 1) == 0) 387 return V >> 1; 388 if (V != 1) 389 return -(V >> 1); 390 // There is no such thing as -0 with integers. "-0" really means MININT. 391 return 1ULL << 63; 392} 393 394bool BitcodeReader::ParseConstants(BitstreamReader &Stream) { 395 if (Stream.EnterSubBlock()) 396 return Error("Malformed block record"); 397 398 SmallVector<uint64_t, 64> Record; 399 400 // Read all the records for this value table. 401 const Type *CurTy = Type::Int32Ty; 402 unsigned NextCstNo = ValueList.size(); 403 while (1) { 404 unsigned Code = Stream.ReadCode(); 405 if (Code == bitc::END_BLOCK) { 406 // If there are global var inits to process, do so now. 407 if (!GlobalInits.empty()) { 408 while (!GlobalInits.empty()) { 409 unsigned ValID = GlobalInits.back().second; 410 if (ValID >= ValueList.size()) 411 return Error("Invalid value ID for global var init!"); 412 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 413 GlobalInits.back().first->setInitializer(C); 414 else 415 return Error("Global variable initializer is not a constant!"); 416 GlobalInits.pop_back(); 417 } 418 } 419 420 if (NextCstNo != ValueList.size()) 421 return Error("Invalid constant reference!"); 422 423 return Stream.ReadBlockEnd(); 424 } 425 426 if (Code == bitc::ENTER_SUBBLOCK) { 427 // No known subblocks, always skip them. 428 Stream.ReadSubBlockID(); 429 if (Stream.SkipBlock()) 430 return Error("Malformed block record"); 431 continue; 432 } 433 434 if (Code == bitc::DEFINE_ABBREV) { 435 Stream.ReadAbbrevRecord(); 436 continue; 437 } 438 439 // Read a record. 440 Record.clear(); 441 Value *V = 0; 442 switch (Stream.ReadRecord(Code, Record)) { 443 default: // Default behavior: unknown constant 444 case bitc::CST_CODE_UNDEF: // UNDEF 445 V = UndefValue::get(CurTy); 446 break; 447 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 448 if (Record.empty()) 449 return Error("Malformed CST_SETTYPE record"); 450 if (Record[0] >= TypeList.size()) 451 return Error("Invalid Type ID in CST_SETTYPE record"); 452 CurTy = TypeList[Record[0]]; 453 continue; // Skip the ValueList manipulation. 454 case bitc::CST_CODE_NULL: // NULL 455 V = Constant::getNullValue(CurTy); 456 break; 457 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 458 if (!isa<IntegerType>(CurTy) || Record.empty()) 459 return Error("Invalid CST_INTEGER record"); 460 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0])); 461 break; 462 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval] 463 if (!isa<IntegerType>(CurTy) || Record.empty() || 464 Record.size() < Record[0]+1) 465 return Error("Invalid WIDE_INTEGER record"); 466 467 unsigned NumWords = Record[0]; 468 SmallVector<uint64_t, 8> Words; 469 Words.resize(NumWords); 470 for (unsigned i = 0; i != NumWords; ++i) 471 Words[i] = DecodeSignRotatedValue(Record[i+1]); 472 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(), 473 NumWords, &Words[0])); 474 break; 475 } 476 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval] 477 if (Record.empty()) 478 return Error("Invalid FLOAT record"); 479 if (CurTy == Type::FloatTy) 480 V = ConstantFP::get(CurTy, BitsToFloat(Record[0])); 481 else if (CurTy == Type::DoubleTy) 482 V = ConstantFP::get(CurTy, BitsToDouble(Record[0])); 483 else 484 V = UndefValue::get(CurTy); 485 break; 486 487 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number] 488 if (Record.empty() || Record.size() < Record[0]+1) 489 return Error("Invalid CST_AGGREGATE record"); 490 491 unsigned Size = Record[0]; 492 std::vector<Constant*> Elts; 493 494 if (const StructType *STy = dyn_cast<StructType>(CurTy)) { 495 for (unsigned i = 0; i != Size; ++i) 496 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], 497 STy->getElementType(i))); 498 V = ConstantStruct::get(STy, Elts); 499 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 500 const Type *EltTy = ATy->getElementType(); 501 for (unsigned i = 0; i != Size; ++i) 502 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy)); 503 V = ConstantArray::get(ATy, Elts); 504 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 505 const Type *EltTy = VTy->getElementType(); 506 for (unsigned i = 0; i != Size; ++i) 507 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy)); 508 V = ConstantVector::get(Elts); 509 } else { 510 V = UndefValue::get(CurTy); 511 } 512 break; 513 } 514 515 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 516 if (Record.size() < 3) return Error("Invalid CE_BINOP record"); 517 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 518 if (Opc < 0) return UndefValue::get(CurTy); // Unknown binop. 519 520 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 521 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 522 V = ConstantExpr::get(Opc, LHS, RHS); 523 break; 524 } 525 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 526 if (Record.size() < 3) return Error("Invalid CE_CAST record"); 527 int Opc = GetDecodedCastOpcode(Record[0]); 528 if (Opc < 0) return UndefValue::get(CurTy); // Unknown cast. 529 530 const Type *OpTy = getTypeByID(Record[1]); 531 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 532 V = ConstantExpr::getCast(Opc, Op, CurTy); 533 break; 534 } 535 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 536 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record"); 537 SmallVector<Constant*, 16> Elts; 538 for (unsigned i = 1, e = Record.size(); i != e; i += 2) { 539 const Type *ElTy = getTypeByID(Record[i]); 540 if (!ElTy) return Error("Invalid CE_GEP record"); 541 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 542 } 543 return ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1); 544 } 545 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#] 546 if (Record.size() < 3) return Error("Invalid CE_SELECT record"); 547 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 548 Type::Int1Ty), 549 ValueList.getConstantFwdRef(Record[1],CurTy), 550 ValueList.getConstantFwdRef(Record[2],CurTy)); 551 break; 552 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] 553 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record"); 554 const VectorType *OpTy = 555 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 556 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record"); 557 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 558 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], 559 OpTy->getElementType()); 560 V = ConstantExpr::getExtractElement(Op0, Op1); 561 break; 562 } 563 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval] 564 const VectorType *OpTy = dyn_cast<VectorType>(CurTy); 565 if (Record.size() < 3 || OpTy == 0) 566 return Error("Invalid CE_INSERTELT record"); 567 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 568 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 569 OpTy->getElementType()); 570 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty); 571 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 572 break; 573 } 574 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 575 const VectorType *OpTy = dyn_cast<VectorType>(CurTy); 576 if (Record.size() < 3 || OpTy == 0) 577 return Error("Invalid CE_INSERTELT record"); 578 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 579 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 580 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements()); 581 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 582 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 583 break; 584 } 585 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 586 if (Record.size() < 4) return Error("Invalid CE_CMP record"); 587 const Type *OpTy = getTypeByID(Record[0]); 588 if (OpTy == 0) return Error("Invalid CE_CMP record"); 589 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 590 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 591 592 if (OpTy->isFloatingPoint()) 593 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 594 else 595 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 596 break; 597 } 598 } 599 600 if (NextCstNo == ValueList.size()) 601 ValueList.push_back(V); 602 else if (ValueList[NextCstNo] == 0) 603 ValueList.initVal(NextCstNo, V); 604 else { 605 // If there was a forward reference to this constant, 606 Value *OldV = ValueList[NextCstNo]; 607 ValueList.setOperand(NextCstNo, V); 608 OldV->replaceAllUsesWith(V); 609 delete OldV; 610 } 611 612 ++NextCstNo; 613 } 614} 615 616bool BitcodeReader::ParseModule(BitstreamReader &Stream, 617 const std::string &ModuleID) { 618 // Reject multiple MODULE_BLOCK's in a single bitstream. 619 if (TheModule) 620 return Error("Multiple MODULE_BLOCKs in same stream"); 621 622 if (Stream.EnterSubBlock()) 623 return Error("Malformed block record"); 624 625 // Otherwise, create the module. 626 TheModule = new Module(ModuleID); 627 628 SmallVector<uint64_t, 64> Record; 629 std::vector<std::string> SectionTable; 630 631 // Read all the records for this module. 632 while (!Stream.AtEndOfStream()) { 633 unsigned Code = Stream.ReadCode(); 634 if (Code == bitc::END_BLOCK) { 635 if (!GlobalInits.empty()) 636 return Error("Malformed global initializer set"); 637 return Stream.ReadBlockEnd(); 638 } 639 640 if (Code == bitc::ENTER_SUBBLOCK) { 641 switch (Stream.ReadSubBlockID()) { 642 default: // Skip unknown content. 643 if (Stream.SkipBlock()) 644 return Error("Malformed block record"); 645 break; 646 case bitc::TYPE_BLOCK_ID: 647 if (ParseTypeTable(Stream)) 648 return true; 649 break; 650 case bitc::TYPE_SYMTAB_BLOCK_ID: 651 if (ParseTypeSymbolTable(Stream)) 652 return true; 653 break; 654 case bitc::VALUE_SYMTAB_BLOCK_ID: 655 if (ParseValueSymbolTable(Stream)) 656 return true; 657 break; 658 case bitc::CONSTANTS_BLOCK_ID: 659 if (ParseConstants(Stream)) 660 return true; 661 break; 662 } 663 continue; 664 } 665 666 if (Code == bitc::DEFINE_ABBREV) { 667 Stream.ReadAbbrevRecord(); 668 continue; 669 } 670 671 // Read a record. 672 switch (Stream.ReadRecord(Code, Record)) { 673 default: break; // Default behavior, ignore unknown content. 674 case bitc::MODULE_CODE_VERSION: // VERSION: [version#] 675 if (Record.size() < 1) 676 return Error("Malformed MODULE_CODE_VERSION"); 677 // Only version #0 is supported so far. 678 if (Record[0] != 0) 679 return Error("Unknown bitstream version!"); 680 break; 681 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N] 682 std::string S; 683 if (ConvertToString(Record, 0, S)) 684 return Error("Invalid MODULE_CODE_TRIPLE record"); 685 TheModule->setTargetTriple(S); 686 break; 687 } 688 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N] 689 std::string S; 690 if (ConvertToString(Record, 0, S)) 691 return Error("Invalid MODULE_CODE_DATALAYOUT record"); 692 TheModule->setDataLayout(S); 693 break; 694 } 695 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N] 696 std::string S; 697 if (ConvertToString(Record, 0, S)) 698 return Error("Invalid MODULE_CODE_ASM record"); 699 TheModule->setModuleInlineAsm(S); 700 break; 701 } 702 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N] 703 std::string S; 704 if (ConvertToString(Record, 0, S)) 705 return Error("Invalid MODULE_CODE_DEPLIB record"); 706 TheModule->addLibrary(S); 707 break; 708 } 709 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N] 710 std::string S; 711 if (ConvertToString(Record, 0, S)) 712 return Error("Invalid MODULE_CODE_SECTIONNAME record"); 713 SectionTable.push_back(S); 714 break; 715 } 716 // GLOBALVAR: [type, isconst, initid, 717 // linkage, alignment, section, visibility, threadlocal] 718 case bitc::MODULE_CODE_GLOBALVAR: { 719 if (Record.size() < 6) 720 return Error("Invalid MODULE_CODE_GLOBALVAR record"); 721 const Type *Ty = getTypeByID(Record[0]); 722 if (!isa<PointerType>(Ty)) 723 return Error("Global not a pointer type!"); 724 Ty = cast<PointerType>(Ty)->getElementType(); 725 726 bool isConstant = Record[1]; 727 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 728 unsigned Alignment = (1 << Record[4]) >> 1; 729 std::string Section; 730 if (Record[5]) { 731 if (Record[5]-1 >= SectionTable.size()) 732 return Error("Invalid section ID"); 733 Section = SectionTable[Record[5]-1]; 734 } 735 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 736 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]); 737 bool isThreadLocal = false; 738 if (Record.size() >= 7) isThreadLocal = Record[7]; 739 740 GlobalVariable *NewGV = 741 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule); 742 NewGV->setAlignment(Alignment); 743 if (!Section.empty()) 744 NewGV->setSection(Section); 745 NewGV->setVisibility(Visibility); 746 NewGV->setThreadLocal(isThreadLocal); 747 748 ValueList.push_back(NewGV); 749 750 // Remember which value to use for the global initializer. 751 if (unsigned InitID = Record[2]) 752 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 753 break; 754 } 755 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section, 756 // visibility] 757 case bitc::MODULE_CODE_FUNCTION: { 758 if (Record.size() < 7) 759 return Error("Invalid MODULE_CODE_FUNCTION record"); 760 const Type *Ty = getTypeByID(Record[0]); 761 if (!isa<PointerType>(Ty)) 762 return Error("Function not a pointer type!"); 763 const FunctionType *FTy = 764 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 765 if (!FTy) 766 return Error("Function not a pointer to function type!"); 767 768 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage, 769 "", TheModule); 770 771 Func->setCallingConv(Record[1]); 772 Func->setLinkage(GetDecodedLinkage(Record[3])); 773 Func->setAlignment((1 << Record[4]) >> 1); 774 if (Record[5]) { 775 if (Record[5]-1 >= SectionTable.size()) 776 return Error("Invalid section ID"); 777 Func->setSection(SectionTable[Record[5]-1]); 778 } 779 Func->setVisibility(GetDecodedVisibility(Record[6])); 780 781 ValueList.push_back(Func); 782 // TODO: remember initializer/global pair for later substitution. 783 break; 784 } 785 } 786 Record.clear(); 787 } 788 789 return Error("Premature end of bitstream"); 790} 791 792 793bool BitcodeReader::ParseBitcode(unsigned char *Buf, unsigned Length, 794 const std::string &ModuleID) { 795 TheModule = 0; 796 797 if (Length & 3) 798 return Error("Bitcode stream should be a multiple of 4 bytes in length"); 799 800 BitstreamReader Stream(Buf, Buf+Length); 801 802 // Sniff for the signature. 803 if (Stream.Read(8) != 'B' || 804 Stream.Read(8) != 'C' || 805 Stream.Read(4) != 0x0 || 806 Stream.Read(4) != 0xC || 807 Stream.Read(4) != 0xE || 808 Stream.Read(4) != 0xD) 809 return Error("Invalid bitcode signature"); 810 811 // We expect a number of well-defined blocks, though we don't necessarily 812 // need to understand them all. 813 while (!Stream.AtEndOfStream()) { 814 unsigned Code = Stream.ReadCode(); 815 816 if (Code != bitc::ENTER_SUBBLOCK) 817 return Error("Invalid record at top-level"); 818 819 unsigned BlockID = Stream.ReadSubBlockID(); 820 821 // We only know the MODULE subblock ID. 822 if (BlockID == bitc::MODULE_BLOCK_ID) { 823 if (ParseModule(Stream, ModuleID)) 824 return true; 825 } else if (Stream.SkipBlock()) { 826 return Error("Malformed block record"); 827 } 828 } 829 830 return false; 831} 832