1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/Bitcode/ReaderWriter.h" 11 #include "BitcodeReader.h" 12 #include "llvm/ADT/SmallString.h" 13 #include "llvm/ADT/SmallVector.h" 14 #include "llvm/AutoUpgrade.h" 15 #include "llvm/Bitcode/LLVMBitCodes.h" 16 #include "llvm/IR/Constants.h" 17 #include "llvm/IR/DerivedTypes.h" 18 #include "llvm/IR/InlineAsm.h" 19 #include "llvm/IR/IntrinsicInst.h" 20 #include "llvm/IR/LLVMContext.h" 21 #include "llvm/IR/Module.h" 22 #include "llvm/IR/OperandTraits.h" 23 #include "llvm/IR/Operator.h" 24 #include "llvm/Support/DataStream.h" 25 #include "llvm/Support/MathExtras.h" 26 #include "llvm/Support/MemoryBuffer.h" 27 #include "llvm/Support/raw_ostream.h" 28 using namespace llvm; 29 30 enum { 31 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 32 }; 33 34 void BitcodeReader::materializeForwardReferencedFunctions() { 35 while (!BlockAddrFwdRefs.empty()) { 36 Function *F = BlockAddrFwdRefs.begin()->first; 37 F->Materialize(); 38 } 39 } 40 41 void BitcodeReader::FreeState() { 42 if (BufferOwned) 43 delete Buffer; 44 Buffer = 0; 45 std::vector<Type*>().swap(TypeList); 46 ValueList.clear(); 47 MDValueList.clear(); 48 49 std::vector<AttributeSet>().swap(MAttributes); 50 std::vector<BasicBlock*>().swap(FunctionBBs); 51 std::vector<Function*>().swap(FunctionsWithBodies); 52 DeferredFunctionInfo.clear(); 53 MDKindMap.clear(); 54 55 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references"); 56 } 57 58 //===----------------------------------------------------------------------===// 59 // Helper functions to implement forward reference resolution, etc. 60 //===----------------------------------------------------------------------===// 61 62 /// ConvertToString - Convert a string from a record into an std::string, return 63 /// true on failure. 64 template<typename StrTy> 65 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx, 66 StrTy &Result) { 67 if (Idx > Record.size()) 68 return true; 69 70 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 71 Result += (char)Record[i]; 72 return false; 73 } 74 75 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) { 76 switch (Val) { 77 default: // Map unknown/new linkages to external 78 case 0: return GlobalValue::ExternalLinkage; 79 case 1: return GlobalValue::WeakAnyLinkage; 80 case 2: return GlobalValue::AppendingLinkage; 81 case 3: return GlobalValue::InternalLinkage; 82 case 4: return GlobalValue::LinkOnceAnyLinkage; 83 case 5: return GlobalValue::DLLImportLinkage; 84 case 6: return GlobalValue::DLLExportLinkage; 85 case 7: return GlobalValue::ExternalWeakLinkage; 86 case 8: return GlobalValue::CommonLinkage; 87 case 9: return GlobalValue::PrivateLinkage; 88 case 10: return GlobalValue::WeakODRLinkage; 89 case 11: return GlobalValue::LinkOnceODRLinkage; 90 case 12: return GlobalValue::AvailableExternallyLinkage; 91 case 13: return GlobalValue::LinkerPrivateLinkage; 92 case 14: return GlobalValue::LinkerPrivateWeakLinkage; 93 } 94 } 95 96 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 97 switch (Val) { 98 default: // Map unknown visibilities to default. 99 case 0: return GlobalValue::DefaultVisibility; 100 case 1: return GlobalValue::HiddenVisibility; 101 case 2: return GlobalValue::ProtectedVisibility; 102 } 103 } 104 105 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) { 106 switch (Val) { 107 case 0: return GlobalVariable::NotThreadLocal; 108 default: // Map unknown non-zero value to general dynamic. 109 case 1: return GlobalVariable::GeneralDynamicTLSModel; 110 case 2: return GlobalVariable::LocalDynamicTLSModel; 111 case 3: return GlobalVariable::InitialExecTLSModel; 112 case 4: return GlobalVariable::LocalExecTLSModel; 113 } 114 } 115 116 static int GetDecodedCastOpcode(unsigned Val) { 117 switch (Val) { 118 default: return -1; 119 case bitc::CAST_TRUNC : return Instruction::Trunc; 120 case bitc::CAST_ZEXT : return Instruction::ZExt; 121 case bitc::CAST_SEXT : return Instruction::SExt; 122 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 123 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 124 case bitc::CAST_UITOFP : return Instruction::UIToFP; 125 case bitc::CAST_SITOFP : return Instruction::SIToFP; 126 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 127 case bitc::CAST_FPEXT : return Instruction::FPExt; 128 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 129 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 130 case bitc::CAST_BITCAST : return Instruction::BitCast; 131 } 132 } 133 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) { 134 switch (Val) { 135 default: return -1; 136 case bitc::BINOP_ADD: 137 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add; 138 case bitc::BINOP_SUB: 139 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub; 140 case bitc::BINOP_MUL: 141 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul; 142 case bitc::BINOP_UDIV: return Instruction::UDiv; 143 case bitc::BINOP_SDIV: 144 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv; 145 case bitc::BINOP_UREM: return Instruction::URem; 146 case bitc::BINOP_SREM: 147 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem; 148 case bitc::BINOP_SHL: return Instruction::Shl; 149 case bitc::BINOP_LSHR: return Instruction::LShr; 150 case bitc::BINOP_ASHR: return Instruction::AShr; 151 case bitc::BINOP_AND: return Instruction::And; 152 case bitc::BINOP_OR: return Instruction::Or; 153 case bitc::BINOP_XOR: return Instruction::Xor; 154 } 155 } 156 157 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) { 158 switch (Val) { 159 default: return AtomicRMWInst::BAD_BINOP; 160 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 161 case bitc::RMW_ADD: return AtomicRMWInst::Add; 162 case bitc::RMW_SUB: return AtomicRMWInst::Sub; 163 case bitc::RMW_AND: return AtomicRMWInst::And; 164 case bitc::RMW_NAND: return AtomicRMWInst::Nand; 165 case bitc::RMW_OR: return AtomicRMWInst::Or; 166 case bitc::RMW_XOR: return AtomicRMWInst::Xor; 167 case bitc::RMW_MAX: return AtomicRMWInst::Max; 168 case bitc::RMW_MIN: return AtomicRMWInst::Min; 169 case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 170 case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 171 } 172 } 173 174 static AtomicOrdering GetDecodedOrdering(unsigned Val) { 175 switch (Val) { 176 case bitc::ORDERING_NOTATOMIC: return NotAtomic; 177 case bitc::ORDERING_UNORDERED: return Unordered; 178 case bitc::ORDERING_MONOTONIC: return Monotonic; 179 case bitc::ORDERING_ACQUIRE: return Acquire; 180 case bitc::ORDERING_RELEASE: return Release; 181 case bitc::ORDERING_ACQREL: return AcquireRelease; 182 default: // Map unknown orderings to sequentially-consistent. 183 case bitc::ORDERING_SEQCST: return SequentiallyConsistent; 184 } 185 } 186 187 static SynchronizationScope GetDecodedSynchScope(unsigned Val) { 188 switch (Val) { 189 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread; 190 default: // Map unknown scopes to cross-thread. 191 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread; 192 } 193 } 194 195 namespace llvm { 196 namespace { 197 /// @brief A class for maintaining the slot number definition 198 /// as a placeholder for the actual definition for forward constants defs. 199 class ConstantPlaceHolder : public ConstantExpr { 200 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION; 201 public: 202 // allocate space for exactly one operand 203 void *operator new(size_t s) { 204 return User::operator new(s, 1); 205 } 206 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context) 207 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 208 Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 209 } 210 211 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast. 212 static bool classof(const Value *V) { 213 return isa<ConstantExpr>(V) && 214 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 215 } 216 217 218 /// Provide fast operand accessors 219 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 220 }; 221 } 222 223 // FIXME: can we inherit this from ConstantExpr? 224 template <> 225 struct OperandTraits<ConstantPlaceHolder> : 226 public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 227 }; 228 } 229 230 231 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { 232 if (Idx == size()) { 233 push_back(V); 234 return; 235 } 236 237 if (Idx >= size()) 238 resize(Idx+1); 239 240 WeakVH &OldV = ValuePtrs[Idx]; 241 if (OldV == 0) { 242 OldV = V; 243 return; 244 } 245 246 // Handle constants and non-constants (e.g. instrs) differently for 247 // efficiency. 248 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 249 ResolveConstants.push_back(std::make_pair(PHC, Idx)); 250 OldV = V; 251 } else { 252 // If there was a forward reference to this value, replace it. 253 Value *PrevVal = OldV; 254 OldV->replaceAllUsesWith(V); 255 delete PrevVal; 256 } 257 } 258 259 260 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 261 Type *Ty) { 262 if (Idx >= size()) 263 resize(Idx + 1); 264 265 if (Value *V = ValuePtrs[Idx]) { 266 assert(Ty == V->getType() && "Type mismatch in constant table!"); 267 return cast<Constant>(V); 268 } 269 270 // Create and return a placeholder, which will later be RAUW'd. 271 Constant *C = new ConstantPlaceHolder(Ty, Context); 272 ValuePtrs[Idx] = C; 273 return C; 274 } 275 276 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 277 if (Idx >= size()) 278 resize(Idx + 1); 279 280 if (Value *V = ValuePtrs[Idx]) { 281 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!"); 282 return V; 283 } 284 285 // No type specified, must be invalid reference. 286 if (Ty == 0) return 0; 287 288 // Create and return a placeholder, which will later be RAUW'd. 289 Value *V = new Argument(Ty); 290 ValuePtrs[Idx] = V; 291 return V; 292 } 293 294 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk 295 /// resolves any forward references. The idea behind this is that we sometimes 296 /// get constants (such as large arrays) which reference *many* forward ref 297 /// constants. Replacing each of these causes a lot of thrashing when 298 /// building/reuniquing the constant. Instead of doing this, we look at all the 299 /// uses and rewrite all the place holders at once for any constant that uses 300 /// a placeholder. 301 void BitcodeReaderValueList::ResolveConstantForwardRefs() { 302 // Sort the values by-pointer so that they are efficient to look up with a 303 // binary search. 304 std::sort(ResolveConstants.begin(), ResolveConstants.end()); 305 306 SmallVector<Constant*, 64> NewOps; 307 308 while (!ResolveConstants.empty()) { 309 Value *RealVal = operator[](ResolveConstants.back().second); 310 Constant *Placeholder = ResolveConstants.back().first; 311 ResolveConstants.pop_back(); 312 313 // Loop over all users of the placeholder, updating them to reference the 314 // new value. If they reference more than one placeholder, update them all 315 // at once. 316 while (!Placeholder->use_empty()) { 317 Value::use_iterator UI = Placeholder->use_begin(); 318 User *U = *UI; 319 320 // If the using object isn't uniqued, just update the operands. This 321 // handles instructions and initializers for global variables. 322 if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 323 UI.getUse().set(RealVal); 324 continue; 325 } 326 327 // Otherwise, we have a constant that uses the placeholder. Replace that 328 // constant with a new constant that has *all* placeholder uses updated. 329 Constant *UserC = cast<Constant>(U); 330 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 331 I != E; ++I) { 332 Value *NewOp; 333 if (!isa<ConstantPlaceHolder>(*I)) { 334 // Not a placeholder reference. 335 NewOp = *I; 336 } else if (*I == Placeholder) { 337 // Common case is that it just references this one placeholder. 338 NewOp = RealVal; 339 } else { 340 // Otherwise, look up the placeholder in ResolveConstants. 341 ResolveConstantsTy::iterator It = 342 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 343 std::pair<Constant*, unsigned>(cast<Constant>(*I), 344 0)); 345 assert(It != ResolveConstants.end() && It->first == *I); 346 NewOp = operator[](It->second); 347 } 348 349 NewOps.push_back(cast<Constant>(NewOp)); 350 } 351 352 // Make the new constant. 353 Constant *NewC; 354 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 355 NewC = ConstantArray::get(UserCA->getType(), NewOps); 356 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 357 NewC = ConstantStruct::get(UserCS->getType(), NewOps); 358 } else if (isa<ConstantVector>(UserC)) { 359 NewC = ConstantVector::get(NewOps); 360 } else { 361 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 362 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 363 } 364 365 UserC->replaceAllUsesWith(NewC); 366 UserC->destroyConstant(); 367 NewOps.clear(); 368 } 369 370 // Update all ValueHandles, they should be the only users at this point. 371 Placeholder->replaceAllUsesWith(RealVal); 372 delete Placeholder; 373 } 374 } 375 376 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) { 377 if (Idx == size()) { 378 push_back(V); 379 return; 380 } 381 382 if (Idx >= size()) 383 resize(Idx+1); 384 385 WeakVH &OldV = MDValuePtrs[Idx]; 386 if (OldV == 0) { 387 OldV = V; 388 return; 389 } 390 391 // If there was a forward reference to this value, replace it. 392 MDNode *PrevVal = cast<MDNode>(OldV); 393 OldV->replaceAllUsesWith(V); 394 MDNode::deleteTemporary(PrevVal); 395 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new 396 // value for Idx. 397 MDValuePtrs[Idx] = V; 398 } 399 400 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) { 401 if (Idx >= size()) 402 resize(Idx + 1); 403 404 if (Value *V = MDValuePtrs[Idx]) { 405 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!"); 406 return V; 407 } 408 409 // Create and return a placeholder, which will later be RAUW'd. 410 Value *V = MDNode::getTemporary(Context, None); 411 MDValuePtrs[Idx] = V; 412 return V; 413 } 414 415 Type *BitcodeReader::getTypeByID(unsigned ID) { 416 // The type table size is always specified correctly. 417 if (ID >= TypeList.size()) 418 return 0; 419 420 if (Type *Ty = TypeList[ID]) 421 return Ty; 422 423 // If we have a forward reference, the only possible case is when it is to a 424 // named struct. Just create a placeholder for now. 425 return TypeList[ID] = StructType::create(Context); 426 } 427 428 429 //===----------------------------------------------------------------------===// 430 // Functions for parsing blocks from the bitcode file 431 //===----------------------------------------------------------------------===// 432 433 434 /// \brief This fills an AttrBuilder object with the LLVM attributes that have 435 /// been decoded from the given integer. This function must stay in sync with 436 /// 'encodeLLVMAttributesForBitcode'. 437 static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 438 uint64_t EncodedAttrs) { 439 // FIXME: Remove in 4.0. 440 441 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 442 // the bits above 31 down by 11 bits. 443 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 444 assert((!Alignment || isPowerOf2_32(Alignment)) && 445 "Alignment must be a power of two."); 446 447 if (Alignment) 448 B.addAlignmentAttr(Alignment); 449 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 450 (EncodedAttrs & 0xffff)); 451 } 452 453 error_code BitcodeReader::ParseAttributeBlock() { 454 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 455 return Error(InvalidRecord); 456 457 if (!MAttributes.empty()) 458 return Error(InvalidMultipleBlocks); 459 460 SmallVector<uint64_t, 64> Record; 461 462 SmallVector<AttributeSet, 8> Attrs; 463 464 // Read all the records. 465 while (1) { 466 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 467 468 switch (Entry.Kind) { 469 case BitstreamEntry::SubBlock: // Handled for us already. 470 case BitstreamEntry::Error: 471 return Error(MalformedBlock); 472 case BitstreamEntry::EndBlock: 473 return error_code::success(); 474 case BitstreamEntry::Record: 475 // The interesting case. 476 break; 477 } 478 479 // Read a record. 480 Record.clear(); 481 switch (Stream.readRecord(Entry.ID, Record)) { 482 default: // Default behavior: ignore. 483 break; 484 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 485 // FIXME: Remove in 4.0. 486 if (Record.size() & 1) 487 return Error(InvalidRecord); 488 489 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 490 AttrBuilder B; 491 decodeLLVMAttributesForBitcode(B, Record[i+1]); 492 Attrs.push_back(AttributeSet::get(Context, Record[i], B)); 493 } 494 495 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 496 Attrs.clear(); 497 break; 498 } 499 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 500 for (unsigned i = 0, e = Record.size(); i != e; ++i) 501 Attrs.push_back(MAttributeGroups[Record[i]]); 502 503 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 504 Attrs.clear(); 505 break; 506 } 507 } 508 } 509 } 510 511 // Returns Attribute::None on unrecognized codes. 512 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) { 513 switch (Code) { 514 default: 515 return Attribute::None; 516 case bitc::ATTR_KIND_ALIGNMENT: 517 return Attribute::Alignment; 518 case bitc::ATTR_KIND_ALWAYS_INLINE: 519 return Attribute::AlwaysInline; 520 case bitc::ATTR_KIND_BUILTIN: 521 return Attribute::Builtin; 522 case bitc::ATTR_KIND_BY_VAL: 523 return Attribute::ByVal; 524 case bitc::ATTR_KIND_COLD: 525 return Attribute::Cold; 526 case bitc::ATTR_KIND_INLINE_HINT: 527 return Attribute::InlineHint; 528 case bitc::ATTR_KIND_IN_REG: 529 return Attribute::InReg; 530 case bitc::ATTR_KIND_MIN_SIZE: 531 return Attribute::MinSize; 532 case bitc::ATTR_KIND_NAKED: 533 return Attribute::Naked; 534 case bitc::ATTR_KIND_NEST: 535 return Attribute::Nest; 536 case bitc::ATTR_KIND_NO_ALIAS: 537 return Attribute::NoAlias; 538 case bitc::ATTR_KIND_NO_BUILTIN: 539 return Attribute::NoBuiltin; 540 case bitc::ATTR_KIND_NO_CAPTURE: 541 return Attribute::NoCapture; 542 case bitc::ATTR_KIND_NO_DUPLICATE: 543 return Attribute::NoDuplicate; 544 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 545 return Attribute::NoImplicitFloat; 546 case bitc::ATTR_KIND_NO_INLINE: 547 return Attribute::NoInline; 548 case bitc::ATTR_KIND_NON_LAZY_BIND: 549 return Attribute::NonLazyBind; 550 case bitc::ATTR_KIND_NO_RED_ZONE: 551 return Attribute::NoRedZone; 552 case bitc::ATTR_KIND_NO_RETURN: 553 return Attribute::NoReturn; 554 case bitc::ATTR_KIND_NO_UNWIND: 555 return Attribute::NoUnwind; 556 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 557 return Attribute::OptimizeForSize; 558 case bitc::ATTR_KIND_OPTIMIZE_NONE: 559 return Attribute::OptimizeNone; 560 case bitc::ATTR_KIND_READ_NONE: 561 return Attribute::ReadNone; 562 case bitc::ATTR_KIND_READ_ONLY: 563 return Attribute::ReadOnly; 564 case bitc::ATTR_KIND_RETURNED: 565 return Attribute::Returned; 566 case bitc::ATTR_KIND_RETURNS_TWICE: 567 return Attribute::ReturnsTwice; 568 case bitc::ATTR_KIND_S_EXT: 569 return Attribute::SExt; 570 case bitc::ATTR_KIND_STACK_ALIGNMENT: 571 return Attribute::StackAlignment; 572 case bitc::ATTR_KIND_STACK_PROTECT: 573 return Attribute::StackProtect; 574 case bitc::ATTR_KIND_STACK_PROTECT_REQ: 575 return Attribute::StackProtectReq; 576 case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 577 return Attribute::StackProtectStrong; 578 case bitc::ATTR_KIND_STRUCT_RET: 579 return Attribute::StructRet; 580 case bitc::ATTR_KIND_SANITIZE_ADDRESS: 581 return Attribute::SanitizeAddress; 582 case bitc::ATTR_KIND_SANITIZE_THREAD: 583 return Attribute::SanitizeThread; 584 case bitc::ATTR_KIND_SANITIZE_MEMORY: 585 return Attribute::SanitizeMemory; 586 case bitc::ATTR_KIND_UW_TABLE: 587 return Attribute::UWTable; 588 case bitc::ATTR_KIND_Z_EXT: 589 return Attribute::ZExt; 590 } 591 } 592 593 error_code BitcodeReader::ParseAttrKind(uint64_t Code, 594 Attribute::AttrKind *Kind) { 595 *Kind = GetAttrFromCode(Code); 596 if (*Kind == Attribute::None) 597 return Error(InvalidValue); 598 return error_code::success(); 599 } 600 601 error_code BitcodeReader::ParseAttributeGroupBlock() { 602 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 603 return Error(InvalidRecord); 604 605 if (!MAttributeGroups.empty()) 606 return Error(InvalidMultipleBlocks); 607 608 SmallVector<uint64_t, 64> Record; 609 610 // Read all the records. 611 while (1) { 612 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 613 614 switch (Entry.Kind) { 615 case BitstreamEntry::SubBlock: // Handled for us already. 616 case BitstreamEntry::Error: 617 return Error(MalformedBlock); 618 case BitstreamEntry::EndBlock: 619 return error_code::success(); 620 case BitstreamEntry::Record: 621 // The interesting case. 622 break; 623 } 624 625 // Read a record. 626 Record.clear(); 627 switch (Stream.readRecord(Entry.ID, Record)) { 628 default: // Default behavior: ignore. 629 break; 630 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 631 if (Record.size() < 3) 632 return Error(InvalidRecord); 633 634 uint64_t GrpID = Record[0]; 635 uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 636 637 AttrBuilder B; 638 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 639 if (Record[i] == 0) { // Enum attribute 640 Attribute::AttrKind Kind; 641 if (error_code EC = ParseAttrKind(Record[++i], &Kind)) 642 return EC; 643 644 B.addAttribute(Kind); 645 } else if (Record[i] == 1) { // Align attribute 646 Attribute::AttrKind Kind; 647 if (error_code EC = ParseAttrKind(Record[++i], &Kind)) 648 return EC; 649 if (Kind == Attribute::Alignment) 650 B.addAlignmentAttr(Record[++i]); 651 else 652 B.addStackAlignmentAttr(Record[++i]); 653 } else { // String attribute 654 assert((Record[i] == 3 || Record[i] == 4) && 655 "Invalid attribute group entry"); 656 bool HasValue = (Record[i++] == 4); 657 SmallString<64> KindStr; 658 SmallString<64> ValStr; 659 660 while (Record[i] != 0 && i != e) 661 KindStr += Record[i++]; 662 assert(Record[i] == 0 && "Kind string not null terminated"); 663 664 if (HasValue) { 665 // Has a value associated with it. 666 ++i; // Skip the '0' that terminates the "kind" string. 667 while (Record[i] != 0 && i != e) 668 ValStr += Record[i++]; 669 assert(Record[i] == 0 && "Value string not null terminated"); 670 } 671 672 B.addAttribute(KindStr.str(), ValStr.str()); 673 } 674 } 675 676 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B); 677 break; 678 } 679 } 680 } 681 } 682 683 error_code BitcodeReader::ParseTypeTable() { 684 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 685 return Error(InvalidRecord); 686 687 return ParseTypeTableBody(); 688 } 689 690 error_code BitcodeReader::ParseTypeTableBody() { 691 if (!TypeList.empty()) 692 return Error(InvalidMultipleBlocks); 693 694 SmallVector<uint64_t, 64> Record; 695 unsigned NumRecords = 0; 696 697 SmallString<64> TypeName; 698 699 // Read all the records for this type table. 700 while (1) { 701 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 702 703 switch (Entry.Kind) { 704 case BitstreamEntry::SubBlock: // Handled for us already. 705 case BitstreamEntry::Error: 706 return Error(MalformedBlock); 707 case BitstreamEntry::EndBlock: 708 if (NumRecords != TypeList.size()) 709 return Error(MalformedBlock); 710 return error_code::success(); 711 case BitstreamEntry::Record: 712 // The interesting case. 713 break; 714 } 715 716 // Read a record. 717 Record.clear(); 718 Type *ResultTy = 0; 719 switch (Stream.readRecord(Entry.ID, Record)) { 720 default: 721 return Error(InvalidValue); 722 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 723 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 724 // type list. This allows us to reserve space. 725 if (Record.size() < 1) 726 return Error(InvalidRecord); 727 TypeList.resize(Record[0]); 728 continue; 729 case bitc::TYPE_CODE_VOID: // VOID 730 ResultTy = Type::getVoidTy(Context); 731 break; 732 case bitc::TYPE_CODE_HALF: // HALF 733 ResultTy = Type::getHalfTy(Context); 734 break; 735 case bitc::TYPE_CODE_FLOAT: // FLOAT 736 ResultTy = Type::getFloatTy(Context); 737 break; 738 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 739 ResultTy = Type::getDoubleTy(Context); 740 break; 741 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 742 ResultTy = Type::getX86_FP80Ty(Context); 743 break; 744 case bitc::TYPE_CODE_FP128: // FP128 745 ResultTy = Type::getFP128Ty(Context); 746 break; 747 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 748 ResultTy = Type::getPPC_FP128Ty(Context); 749 break; 750 case bitc::TYPE_CODE_LABEL: // LABEL 751 ResultTy = Type::getLabelTy(Context); 752 break; 753 case bitc::TYPE_CODE_METADATA: // METADATA 754 ResultTy = Type::getMetadataTy(Context); 755 break; 756 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 757 ResultTy = Type::getX86_MMXTy(Context); 758 break; 759 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 760 if (Record.size() < 1) 761 return Error(InvalidRecord); 762 763 ResultTy = IntegerType::get(Context, Record[0]); 764 break; 765 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 766 // [pointee type, address space] 767 if (Record.size() < 1) 768 return Error(InvalidRecord); 769 unsigned AddressSpace = 0; 770 if (Record.size() == 2) 771 AddressSpace = Record[1]; 772 ResultTy = getTypeByID(Record[0]); 773 if (ResultTy == 0) 774 return Error(InvalidType); 775 ResultTy = PointerType::get(ResultTy, AddressSpace); 776 break; 777 } 778 case bitc::TYPE_CODE_FUNCTION_OLD: { 779 // FIXME: attrid is dead, remove it in LLVM 4.0 780 // FUNCTION: [vararg, attrid, retty, paramty x N] 781 if (Record.size() < 3) 782 return Error(InvalidRecord); 783 SmallVector<Type*, 8> ArgTys; 784 for (unsigned i = 3, e = Record.size(); i != e; ++i) { 785 if (Type *T = getTypeByID(Record[i])) 786 ArgTys.push_back(T); 787 else 788 break; 789 } 790 791 ResultTy = getTypeByID(Record[2]); 792 if (ResultTy == 0 || ArgTys.size() < Record.size()-3) 793 return Error(InvalidType); 794 795 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 796 break; 797 } 798 case bitc::TYPE_CODE_FUNCTION: { 799 // FUNCTION: [vararg, retty, paramty x N] 800 if (Record.size() < 2) 801 return Error(InvalidRecord); 802 SmallVector<Type*, 8> ArgTys; 803 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 804 if (Type *T = getTypeByID(Record[i])) 805 ArgTys.push_back(T); 806 else 807 break; 808 } 809 810 ResultTy = getTypeByID(Record[1]); 811 if (ResultTy == 0 || ArgTys.size() < Record.size()-2) 812 return Error(InvalidType); 813 814 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 815 break; 816 } 817 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 818 if (Record.size() < 1) 819 return Error(InvalidRecord); 820 SmallVector<Type*, 8> EltTys; 821 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 822 if (Type *T = getTypeByID(Record[i])) 823 EltTys.push_back(T); 824 else 825 break; 826 } 827 if (EltTys.size() != Record.size()-1) 828 return Error(InvalidType); 829 ResultTy = StructType::get(Context, EltTys, Record[0]); 830 break; 831 } 832 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 833 if (ConvertToString(Record, 0, TypeName)) 834 return Error(InvalidRecord); 835 continue; 836 837 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 838 if (Record.size() < 1) 839 return Error(InvalidRecord); 840 841 if (NumRecords >= TypeList.size()) 842 return Error(InvalidTYPETable); 843 844 // Check to see if this was forward referenced, if so fill in the temp. 845 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 846 if (Res) { 847 Res->setName(TypeName); 848 TypeList[NumRecords] = 0; 849 } else // Otherwise, create a new struct. 850 Res = StructType::create(Context, TypeName); 851 TypeName.clear(); 852 853 SmallVector<Type*, 8> EltTys; 854 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 855 if (Type *T = getTypeByID(Record[i])) 856 EltTys.push_back(T); 857 else 858 break; 859 } 860 if (EltTys.size() != Record.size()-1) 861 return Error(InvalidRecord); 862 Res->setBody(EltTys, Record[0]); 863 ResultTy = Res; 864 break; 865 } 866 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 867 if (Record.size() != 1) 868 return Error(InvalidRecord); 869 870 if (NumRecords >= TypeList.size()) 871 return Error(InvalidTYPETable); 872 873 // Check to see if this was forward referenced, if so fill in the temp. 874 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 875 if (Res) { 876 Res->setName(TypeName); 877 TypeList[NumRecords] = 0; 878 } else // Otherwise, create a new struct with no body. 879 Res = StructType::create(Context, TypeName); 880 TypeName.clear(); 881 ResultTy = Res; 882 break; 883 } 884 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 885 if (Record.size() < 2) 886 return Error(InvalidRecord); 887 if ((ResultTy = getTypeByID(Record[1]))) 888 ResultTy = ArrayType::get(ResultTy, Record[0]); 889 else 890 return Error(InvalidType); 891 break; 892 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 893 if (Record.size() < 2) 894 return Error(InvalidRecord); 895 if ((ResultTy = getTypeByID(Record[1]))) 896 ResultTy = VectorType::get(ResultTy, Record[0]); 897 else 898 return Error(InvalidType); 899 break; 900 } 901 902 if (NumRecords >= TypeList.size()) 903 return Error(InvalidTYPETable); 904 assert(ResultTy && "Didn't read a type?"); 905 assert(TypeList[NumRecords] == 0 && "Already read type?"); 906 TypeList[NumRecords++] = ResultTy; 907 } 908 } 909 910 error_code BitcodeReader::ParseValueSymbolTable() { 911 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 912 return Error(InvalidRecord); 913 914 SmallVector<uint64_t, 64> Record; 915 916 // Read all the records for this value table. 917 SmallString<128> ValueName; 918 while (1) { 919 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 920 921 switch (Entry.Kind) { 922 case BitstreamEntry::SubBlock: // Handled for us already. 923 case BitstreamEntry::Error: 924 return Error(MalformedBlock); 925 case BitstreamEntry::EndBlock: 926 return error_code::success(); 927 case BitstreamEntry::Record: 928 // The interesting case. 929 break; 930 } 931 932 // Read a record. 933 Record.clear(); 934 switch (Stream.readRecord(Entry.ID, Record)) { 935 default: // Default behavior: unknown type. 936 break; 937 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 938 if (ConvertToString(Record, 1, ValueName)) 939 return Error(InvalidRecord); 940 unsigned ValueID = Record[0]; 941 if (ValueID >= ValueList.size()) 942 return Error(InvalidRecord); 943 Value *V = ValueList[ValueID]; 944 945 V->setName(StringRef(ValueName.data(), ValueName.size())); 946 ValueName.clear(); 947 break; 948 } 949 case bitc::VST_CODE_BBENTRY: { 950 if (ConvertToString(Record, 1, ValueName)) 951 return Error(InvalidRecord); 952 BasicBlock *BB = getBasicBlock(Record[0]); 953 if (BB == 0) 954 return Error(InvalidRecord); 955 956 BB->setName(StringRef(ValueName.data(), ValueName.size())); 957 ValueName.clear(); 958 break; 959 } 960 } 961 } 962 } 963 964 error_code BitcodeReader::ParseMetadata() { 965 unsigned NextMDValueNo = MDValueList.size(); 966 967 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 968 return Error(InvalidRecord); 969 970 SmallVector<uint64_t, 64> Record; 971 972 // Read all the records. 973 while (1) { 974 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 975 976 switch (Entry.Kind) { 977 case BitstreamEntry::SubBlock: // Handled for us already. 978 case BitstreamEntry::Error: 979 return Error(MalformedBlock); 980 case BitstreamEntry::EndBlock: 981 return error_code::success(); 982 case BitstreamEntry::Record: 983 // The interesting case. 984 break; 985 } 986 987 bool IsFunctionLocal = false; 988 // Read a record. 989 Record.clear(); 990 unsigned Code = Stream.readRecord(Entry.ID, Record); 991 switch (Code) { 992 default: // Default behavior: ignore. 993 break; 994 case bitc::METADATA_NAME: { 995 // Read name of the named metadata. 996 SmallString<8> Name(Record.begin(), Record.end()); 997 Record.clear(); 998 Code = Stream.ReadCode(); 999 1000 // METADATA_NAME is always followed by METADATA_NAMED_NODE. 1001 unsigned NextBitCode = Stream.readRecord(Code, Record); 1002 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode; 1003 1004 // Read named metadata elements. 1005 unsigned Size = Record.size(); 1006 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 1007 for (unsigned i = 0; i != Size; ++i) { 1008 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i])); 1009 if (MD == 0) 1010 return Error(InvalidRecord); 1011 NMD->addOperand(MD); 1012 } 1013 break; 1014 } 1015 case bitc::METADATA_FN_NODE: 1016 IsFunctionLocal = true; 1017 // fall-through 1018 case bitc::METADATA_NODE: { 1019 if (Record.size() % 2 == 1) 1020 return Error(InvalidRecord); 1021 1022 unsigned Size = Record.size(); 1023 SmallVector<Value*, 8> Elts; 1024 for (unsigned i = 0; i != Size; i += 2) { 1025 Type *Ty = getTypeByID(Record[i]); 1026 if (!Ty) 1027 return Error(InvalidRecord); 1028 if (Ty->isMetadataTy()) 1029 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1])); 1030 else if (!Ty->isVoidTy()) 1031 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty)); 1032 else 1033 Elts.push_back(NULL); 1034 } 1035 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal); 1036 IsFunctionLocal = false; 1037 MDValueList.AssignValue(V, NextMDValueNo++); 1038 break; 1039 } 1040 case bitc::METADATA_STRING: { 1041 SmallString<8> String(Record.begin(), Record.end()); 1042 Value *V = MDString::get(Context, String); 1043 MDValueList.AssignValue(V, NextMDValueNo++); 1044 break; 1045 } 1046 case bitc::METADATA_KIND: { 1047 if (Record.size() < 2) 1048 return Error(InvalidRecord); 1049 1050 unsigned Kind = Record[0]; 1051 SmallString<8> Name(Record.begin()+1, Record.end()); 1052 1053 unsigned NewKind = TheModule->getMDKindID(Name.str()); 1054 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1055 return Error(ConflictingMETADATA_KINDRecords); 1056 break; 1057 } 1058 } 1059 } 1060 } 1061 1062 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in 1063 /// the LSB for dense VBR encoding. 1064 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 1065 if ((V & 1) == 0) 1066 return V >> 1; 1067 if (V != 1) 1068 return -(V >> 1); 1069 // There is no such thing as -0 with integers. "-0" really means MININT. 1070 return 1ULL << 63; 1071 } 1072 1073 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 1074 /// values and aliases that we can. 1075 error_code BitcodeReader::ResolveGlobalAndAliasInits() { 1076 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 1077 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 1078 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 1079 1080 GlobalInitWorklist.swap(GlobalInits); 1081 AliasInitWorklist.swap(AliasInits); 1082 FunctionPrefixWorklist.swap(FunctionPrefixes); 1083 1084 while (!GlobalInitWorklist.empty()) { 1085 unsigned ValID = GlobalInitWorklist.back().second; 1086 if (ValID >= ValueList.size()) { 1087 // Not ready to resolve this yet, it requires something later in the file. 1088 GlobalInits.push_back(GlobalInitWorklist.back()); 1089 } else { 1090 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 1091 GlobalInitWorklist.back().first->setInitializer(C); 1092 else 1093 return Error(ExpectedConstant); 1094 } 1095 GlobalInitWorklist.pop_back(); 1096 } 1097 1098 while (!AliasInitWorklist.empty()) { 1099 unsigned ValID = AliasInitWorklist.back().second; 1100 if (ValID >= ValueList.size()) { 1101 AliasInits.push_back(AliasInitWorklist.back()); 1102 } else { 1103 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 1104 AliasInitWorklist.back().first->setAliasee(C); 1105 else 1106 return Error(ExpectedConstant); 1107 } 1108 AliasInitWorklist.pop_back(); 1109 } 1110 1111 while (!FunctionPrefixWorklist.empty()) { 1112 unsigned ValID = FunctionPrefixWorklist.back().second; 1113 if (ValID >= ValueList.size()) { 1114 FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 1115 } else { 1116 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 1117 FunctionPrefixWorklist.back().first->setPrefixData(C); 1118 else 1119 return Error(ExpectedConstant); 1120 } 1121 FunctionPrefixWorklist.pop_back(); 1122 } 1123 1124 return error_code::success(); 1125 } 1126 1127 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 1128 SmallVector<uint64_t, 8> Words(Vals.size()); 1129 std::transform(Vals.begin(), Vals.end(), Words.begin(), 1130 BitcodeReader::decodeSignRotatedValue); 1131 1132 return APInt(TypeBits, Words); 1133 } 1134 1135 error_code BitcodeReader::ParseConstants() { 1136 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 1137 return Error(InvalidRecord); 1138 1139 SmallVector<uint64_t, 64> Record; 1140 1141 // Read all the records for this value table. 1142 Type *CurTy = Type::getInt32Ty(Context); 1143 unsigned NextCstNo = ValueList.size(); 1144 while (1) { 1145 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1146 1147 switch (Entry.Kind) { 1148 case BitstreamEntry::SubBlock: // Handled for us already. 1149 case BitstreamEntry::Error: 1150 return Error(MalformedBlock); 1151 case BitstreamEntry::EndBlock: 1152 if (NextCstNo != ValueList.size()) 1153 return Error(InvalidConstantReference); 1154 1155 // Once all the constants have been read, go through and resolve forward 1156 // references. 1157 ValueList.ResolveConstantForwardRefs(); 1158 return error_code::success(); 1159 case BitstreamEntry::Record: 1160 // The interesting case. 1161 break; 1162 } 1163 1164 // Read a record. 1165 Record.clear(); 1166 Value *V = 0; 1167 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 1168 switch (BitCode) { 1169 default: // Default behavior: unknown constant 1170 case bitc::CST_CODE_UNDEF: // UNDEF 1171 V = UndefValue::get(CurTy); 1172 break; 1173 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 1174 if (Record.empty()) 1175 return Error(InvalidRecord); 1176 if (Record[0] >= TypeList.size()) 1177 return Error(InvalidRecord); 1178 CurTy = TypeList[Record[0]]; 1179 continue; // Skip the ValueList manipulation. 1180 case bitc::CST_CODE_NULL: // NULL 1181 V = Constant::getNullValue(CurTy); 1182 break; 1183 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 1184 if (!CurTy->isIntegerTy() || Record.empty()) 1185 return Error(InvalidRecord); 1186 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 1187 break; 1188 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 1189 if (!CurTy->isIntegerTy() || Record.empty()) 1190 return Error(InvalidRecord); 1191 1192 APInt VInt = ReadWideAPInt(Record, 1193 cast<IntegerType>(CurTy)->getBitWidth()); 1194 V = ConstantInt::get(Context, VInt); 1195 1196 break; 1197 } 1198 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 1199 if (Record.empty()) 1200 return Error(InvalidRecord); 1201 if (CurTy->isHalfTy()) 1202 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 1203 APInt(16, (uint16_t)Record[0]))); 1204 else if (CurTy->isFloatTy()) 1205 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 1206 APInt(32, (uint32_t)Record[0]))); 1207 else if (CurTy->isDoubleTy()) 1208 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 1209 APInt(64, Record[0]))); 1210 else if (CurTy->isX86_FP80Ty()) { 1211 // Bits are not stored the same way as a normal i80 APInt, compensate. 1212 uint64_t Rearrange[2]; 1213 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 1214 Rearrange[1] = Record[0] >> 48; 1215 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 1216 APInt(80, Rearrange))); 1217 } else if (CurTy->isFP128Ty()) 1218 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 1219 APInt(128, Record))); 1220 else if (CurTy->isPPC_FP128Ty()) 1221 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 1222 APInt(128, Record))); 1223 else 1224 V = UndefValue::get(CurTy); 1225 break; 1226 } 1227 1228 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 1229 if (Record.empty()) 1230 return Error(InvalidRecord); 1231 1232 unsigned Size = Record.size(); 1233 SmallVector<Constant*, 16> Elts; 1234 1235 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 1236 for (unsigned i = 0; i != Size; ++i) 1237 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 1238 STy->getElementType(i))); 1239 V = ConstantStruct::get(STy, Elts); 1240 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 1241 Type *EltTy = ATy->getElementType(); 1242 for (unsigned i = 0; i != Size; ++i) 1243 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1244 V = ConstantArray::get(ATy, Elts); 1245 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 1246 Type *EltTy = VTy->getElementType(); 1247 for (unsigned i = 0; i != Size; ++i) 1248 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1249 V = ConstantVector::get(Elts); 1250 } else { 1251 V = UndefValue::get(CurTy); 1252 } 1253 break; 1254 } 1255 case bitc::CST_CODE_STRING: // STRING: [values] 1256 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 1257 if (Record.empty()) 1258 return Error(InvalidRecord); 1259 1260 SmallString<16> Elts(Record.begin(), Record.end()); 1261 V = ConstantDataArray::getString(Context, Elts, 1262 BitCode == bitc::CST_CODE_CSTRING); 1263 break; 1264 } 1265 case bitc::CST_CODE_DATA: {// DATA: [n x value] 1266 if (Record.empty()) 1267 return Error(InvalidRecord); 1268 1269 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 1270 unsigned Size = Record.size(); 1271 1272 if (EltTy->isIntegerTy(8)) { 1273 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 1274 if (isa<VectorType>(CurTy)) 1275 V = ConstantDataVector::get(Context, Elts); 1276 else 1277 V = ConstantDataArray::get(Context, Elts); 1278 } else if (EltTy->isIntegerTy(16)) { 1279 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 1280 if (isa<VectorType>(CurTy)) 1281 V = ConstantDataVector::get(Context, Elts); 1282 else 1283 V = ConstantDataArray::get(Context, Elts); 1284 } else if (EltTy->isIntegerTy(32)) { 1285 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 1286 if (isa<VectorType>(CurTy)) 1287 V = ConstantDataVector::get(Context, Elts); 1288 else 1289 V = ConstantDataArray::get(Context, Elts); 1290 } else if (EltTy->isIntegerTy(64)) { 1291 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 1292 if (isa<VectorType>(CurTy)) 1293 V = ConstantDataVector::get(Context, Elts); 1294 else 1295 V = ConstantDataArray::get(Context, Elts); 1296 } else if (EltTy->isFloatTy()) { 1297 SmallVector<float, 16> Elts(Size); 1298 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); 1299 if (isa<VectorType>(CurTy)) 1300 V = ConstantDataVector::get(Context, Elts); 1301 else 1302 V = ConstantDataArray::get(Context, Elts); 1303 } else if (EltTy->isDoubleTy()) { 1304 SmallVector<double, 16> Elts(Size); 1305 std::transform(Record.begin(), Record.end(), Elts.begin(), 1306 BitsToDouble); 1307 if (isa<VectorType>(CurTy)) 1308 V = ConstantDataVector::get(Context, Elts); 1309 else 1310 V = ConstantDataArray::get(Context, Elts); 1311 } else { 1312 return Error(InvalidTypeForValue); 1313 } 1314 break; 1315 } 1316 1317 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 1318 if (Record.size() < 3) 1319 return Error(InvalidRecord); 1320 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 1321 if (Opc < 0) { 1322 V = UndefValue::get(CurTy); // Unknown binop. 1323 } else { 1324 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 1325 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 1326 unsigned Flags = 0; 1327 if (Record.size() >= 4) { 1328 if (Opc == Instruction::Add || 1329 Opc == Instruction::Sub || 1330 Opc == Instruction::Mul || 1331 Opc == Instruction::Shl) { 1332 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 1333 Flags |= OverflowingBinaryOperator::NoSignedWrap; 1334 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 1335 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 1336 } else if (Opc == Instruction::SDiv || 1337 Opc == Instruction::UDiv || 1338 Opc == Instruction::LShr || 1339 Opc == Instruction::AShr) { 1340 if (Record[3] & (1 << bitc::PEO_EXACT)) 1341 Flags |= SDivOperator::IsExact; 1342 } 1343 } 1344 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 1345 } 1346 break; 1347 } 1348 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 1349 if (Record.size() < 3) 1350 return Error(InvalidRecord); 1351 int Opc = GetDecodedCastOpcode(Record[0]); 1352 if (Opc < 0) { 1353 V = UndefValue::get(CurTy); // Unknown cast. 1354 } else { 1355 Type *OpTy = getTypeByID(Record[1]); 1356 if (!OpTy) 1357 return Error(InvalidRecord); 1358 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 1359 V = ConstantExpr::getCast(Opc, Op, CurTy); 1360 } 1361 break; 1362 } 1363 case bitc::CST_CODE_CE_INBOUNDS_GEP: 1364 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 1365 if (Record.size() & 1) 1366 return Error(InvalidRecord); 1367 SmallVector<Constant*, 16> Elts; 1368 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1369 Type *ElTy = getTypeByID(Record[i]); 1370 if (!ElTy) 1371 return Error(InvalidRecord); 1372 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 1373 } 1374 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 1375 V = ConstantExpr::getGetElementPtr(Elts[0], Indices, 1376 BitCode == 1377 bitc::CST_CODE_CE_INBOUNDS_GEP); 1378 break; 1379 } 1380 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 1381 if (Record.size() < 3) 1382 return Error(InvalidRecord); 1383 1384 Type *SelectorTy = Type::getInt1Ty(Context); 1385 1386 // If CurTy is a vector of length n, then Record[0] must be a <n x i1> 1387 // vector. Otherwise, it must be a single bit. 1388 if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 1389 SelectorTy = VectorType::get(Type::getInt1Ty(Context), 1390 VTy->getNumElements()); 1391 1392 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 1393 SelectorTy), 1394 ValueList.getConstantFwdRef(Record[1],CurTy), 1395 ValueList.getConstantFwdRef(Record[2],CurTy)); 1396 break; 1397 } 1398 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] 1399 if (Record.size() < 3) 1400 return Error(InvalidRecord); 1401 VectorType *OpTy = 1402 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1403 if (OpTy == 0) 1404 return Error(InvalidRecord); 1405 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1406 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], 1407 Type::getInt32Ty(Context)); 1408 V = ConstantExpr::getExtractElement(Op0, Op1); 1409 break; 1410 } 1411 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval] 1412 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1413 if (Record.size() < 3 || OpTy == 0) 1414 return Error(InvalidRecord); 1415 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1416 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 1417 OpTy->getElementType()); 1418 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], 1419 Type::getInt32Ty(Context)); 1420 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 1421 break; 1422 } 1423 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 1424 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1425 if (Record.size() < 3 || OpTy == 0) 1426 return Error(InvalidRecord); 1427 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1428 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 1429 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1430 OpTy->getNumElements()); 1431 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 1432 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1433 break; 1434 } 1435 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 1436 VectorType *RTy = dyn_cast<VectorType>(CurTy); 1437 VectorType *OpTy = 1438 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1439 if (Record.size() < 4 || RTy == 0 || OpTy == 0) 1440 return Error(InvalidRecord); 1441 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1442 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1443 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1444 RTy->getNumElements()); 1445 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 1446 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1447 break; 1448 } 1449 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 1450 if (Record.size() < 4) 1451 return Error(InvalidRecord); 1452 Type *OpTy = getTypeByID(Record[0]); 1453 if (OpTy == 0) 1454 return Error(InvalidRecord); 1455 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1456 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1457 1458 if (OpTy->isFPOrFPVectorTy()) 1459 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 1460 else 1461 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 1462 break; 1463 } 1464 // This maintains backward compatibility, pre-asm dialect keywords. 1465 // FIXME: Remove with the 4.0 release. 1466 case bitc::CST_CODE_INLINEASM_OLD: { 1467 if (Record.size() < 2) 1468 return Error(InvalidRecord); 1469 std::string AsmStr, ConstrStr; 1470 bool HasSideEffects = Record[0] & 1; 1471 bool IsAlignStack = Record[0] >> 1; 1472 unsigned AsmStrSize = Record[1]; 1473 if (2+AsmStrSize >= Record.size()) 1474 return Error(InvalidRecord); 1475 unsigned ConstStrSize = Record[2+AsmStrSize]; 1476 if (3+AsmStrSize+ConstStrSize > Record.size()) 1477 return Error(InvalidRecord); 1478 1479 for (unsigned i = 0; i != AsmStrSize; ++i) 1480 AsmStr += (char)Record[2+i]; 1481 for (unsigned i = 0; i != ConstStrSize; ++i) 1482 ConstrStr += (char)Record[3+AsmStrSize+i]; 1483 PointerType *PTy = cast<PointerType>(CurTy); 1484 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1485 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 1486 break; 1487 } 1488 // This version adds support for the asm dialect keywords (e.g., 1489 // inteldialect). 1490 case bitc::CST_CODE_INLINEASM: { 1491 if (Record.size() < 2) 1492 return Error(InvalidRecord); 1493 std::string AsmStr, ConstrStr; 1494 bool HasSideEffects = Record[0] & 1; 1495 bool IsAlignStack = (Record[0] >> 1) & 1; 1496 unsigned AsmDialect = Record[0] >> 2; 1497 unsigned AsmStrSize = Record[1]; 1498 if (2+AsmStrSize >= Record.size()) 1499 return Error(InvalidRecord); 1500 unsigned ConstStrSize = Record[2+AsmStrSize]; 1501 if (3+AsmStrSize+ConstStrSize > Record.size()) 1502 return Error(InvalidRecord); 1503 1504 for (unsigned i = 0; i != AsmStrSize; ++i) 1505 AsmStr += (char)Record[2+i]; 1506 for (unsigned i = 0; i != ConstStrSize; ++i) 1507 ConstrStr += (char)Record[3+AsmStrSize+i]; 1508 PointerType *PTy = cast<PointerType>(CurTy); 1509 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1510 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 1511 InlineAsm::AsmDialect(AsmDialect)); 1512 break; 1513 } 1514 case bitc::CST_CODE_BLOCKADDRESS:{ 1515 if (Record.size() < 3) 1516 return Error(InvalidRecord); 1517 Type *FnTy = getTypeByID(Record[0]); 1518 if (FnTy == 0) 1519 return Error(InvalidRecord); 1520 Function *Fn = 1521 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 1522 if (Fn == 0) 1523 return Error(InvalidRecord); 1524 1525 // If the function is already parsed we can insert the block address right 1526 // away. 1527 if (!Fn->empty()) { 1528 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 1529 for (size_t I = 0, E = Record[2]; I != E; ++I) { 1530 if (BBI == BBE) 1531 return Error(InvalidID); 1532 ++BBI; 1533 } 1534 V = BlockAddress::get(Fn, BBI); 1535 } else { 1536 // Otherwise insert a placeholder and remember it so it can be inserted 1537 // when the function is parsed. 1538 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(), 1539 Type::getInt8Ty(Context), 1540 false, GlobalValue::InternalLinkage, 1541 0, ""); 1542 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef)); 1543 V = FwdRef; 1544 } 1545 break; 1546 } 1547 } 1548 1549 ValueList.AssignValue(V, NextCstNo); 1550 ++NextCstNo; 1551 } 1552 } 1553 1554 error_code BitcodeReader::ParseUseLists() { 1555 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 1556 return Error(InvalidRecord); 1557 1558 SmallVector<uint64_t, 64> Record; 1559 1560 // Read all the records. 1561 while (1) { 1562 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1563 1564 switch (Entry.Kind) { 1565 case BitstreamEntry::SubBlock: // Handled for us already. 1566 case BitstreamEntry::Error: 1567 return Error(MalformedBlock); 1568 case BitstreamEntry::EndBlock: 1569 return error_code::success(); 1570 case BitstreamEntry::Record: 1571 // The interesting case. 1572 break; 1573 } 1574 1575 // Read a use list record. 1576 Record.clear(); 1577 switch (Stream.readRecord(Entry.ID, Record)) { 1578 default: // Default behavior: unknown type. 1579 break; 1580 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD. 1581 unsigned RecordLength = Record.size(); 1582 if (RecordLength < 1) 1583 return Error(InvalidRecord); 1584 UseListRecords.push_back(Record); 1585 break; 1586 } 1587 } 1588 } 1589 } 1590 1591 /// RememberAndSkipFunctionBody - When we see the block for a function body, 1592 /// remember where it is and then skip it. This lets us lazily deserialize the 1593 /// functions. 1594 error_code BitcodeReader::RememberAndSkipFunctionBody() { 1595 // Get the function we are talking about. 1596 if (FunctionsWithBodies.empty()) 1597 return Error(InsufficientFunctionProtos); 1598 1599 Function *Fn = FunctionsWithBodies.back(); 1600 FunctionsWithBodies.pop_back(); 1601 1602 // Save the current stream state. 1603 uint64_t CurBit = Stream.GetCurrentBitNo(); 1604 DeferredFunctionInfo[Fn] = CurBit; 1605 1606 // Skip over the function block for now. 1607 if (Stream.SkipBlock()) 1608 return Error(InvalidRecord); 1609 return error_code::success(); 1610 } 1611 1612 error_code BitcodeReader::GlobalCleanup() { 1613 // Patch the initializers for globals and aliases up. 1614 ResolveGlobalAndAliasInits(); 1615 if (!GlobalInits.empty() || !AliasInits.empty()) 1616 return Error(MalformedGlobalInitializerSet); 1617 1618 // Look for intrinsic functions which need to be upgraded at some point 1619 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 1620 FI != FE; ++FI) { 1621 Function *NewFn; 1622 if (UpgradeIntrinsicFunction(FI, NewFn)) 1623 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 1624 } 1625 1626 // Look for global variables which need to be renamed. 1627 for (Module::global_iterator 1628 GI = TheModule->global_begin(), GE = TheModule->global_end(); 1629 GI != GE; ++GI) 1630 UpgradeGlobalVariable(GI); 1631 // Force deallocation of memory for these vectors to favor the client that 1632 // want lazy deserialization. 1633 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 1634 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 1635 return error_code::success(); 1636 } 1637 1638 error_code BitcodeReader::ParseModule(bool Resume) { 1639 if (Resume) 1640 Stream.JumpToBit(NextUnreadBit); 1641 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 1642 return Error(InvalidRecord); 1643 1644 SmallVector<uint64_t, 64> Record; 1645 std::vector<std::string> SectionTable; 1646 std::vector<std::string> GCTable; 1647 1648 // Read all the records for this module. 1649 while (1) { 1650 BitstreamEntry Entry = Stream.advance(); 1651 1652 switch (Entry.Kind) { 1653 case BitstreamEntry::Error: 1654 return Error(MalformedBlock); 1655 case BitstreamEntry::EndBlock: 1656 return GlobalCleanup(); 1657 1658 case BitstreamEntry::SubBlock: 1659 switch (Entry.ID) { 1660 default: // Skip unknown content. 1661 if (Stream.SkipBlock()) 1662 return Error(InvalidRecord); 1663 break; 1664 case bitc::BLOCKINFO_BLOCK_ID: 1665 if (Stream.ReadBlockInfoBlock()) 1666 return Error(MalformedBlock); 1667 break; 1668 case bitc::PARAMATTR_BLOCK_ID: 1669 if (error_code EC = ParseAttributeBlock()) 1670 return EC; 1671 break; 1672 case bitc::PARAMATTR_GROUP_BLOCK_ID: 1673 if (error_code EC = ParseAttributeGroupBlock()) 1674 return EC; 1675 break; 1676 case bitc::TYPE_BLOCK_ID_NEW: 1677 if (error_code EC = ParseTypeTable()) 1678 return EC; 1679 break; 1680 case bitc::VALUE_SYMTAB_BLOCK_ID: 1681 if (error_code EC = ParseValueSymbolTable()) 1682 return EC; 1683 SeenValueSymbolTable = true; 1684 break; 1685 case bitc::CONSTANTS_BLOCK_ID: 1686 if (error_code EC = ParseConstants()) 1687 return EC; 1688 if (error_code EC = ResolveGlobalAndAliasInits()) 1689 return EC; 1690 break; 1691 case bitc::METADATA_BLOCK_ID: 1692 if (error_code EC = ParseMetadata()) 1693 return EC; 1694 break; 1695 case bitc::FUNCTION_BLOCK_ID: 1696 // If this is the first function body we've seen, reverse the 1697 // FunctionsWithBodies list. 1698 if (!SeenFirstFunctionBody) { 1699 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 1700 if (error_code EC = GlobalCleanup()) 1701 return EC; 1702 SeenFirstFunctionBody = true; 1703 } 1704 1705 if (error_code EC = RememberAndSkipFunctionBody()) 1706 return EC; 1707 // For streaming bitcode, suspend parsing when we reach the function 1708 // bodies. Subsequent materialization calls will resume it when 1709 // necessary. For streaming, the function bodies must be at the end of 1710 // the bitcode. If the bitcode file is old, the symbol table will be 1711 // at the end instead and will not have been seen yet. In this case, 1712 // just finish the parse now. 1713 if (LazyStreamer && SeenValueSymbolTable) { 1714 NextUnreadBit = Stream.GetCurrentBitNo(); 1715 return error_code::success(); 1716 } 1717 break; 1718 case bitc::USELIST_BLOCK_ID: 1719 if (error_code EC = ParseUseLists()) 1720 return EC; 1721 break; 1722 } 1723 continue; 1724 1725 case BitstreamEntry::Record: 1726 // The interesting case. 1727 break; 1728 } 1729 1730 1731 // Read a record. 1732 switch (Stream.readRecord(Entry.ID, Record)) { 1733 default: break; // Default behavior, ignore unknown content. 1734 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 1735 if (Record.size() < 1) 1736 return Error(InvalidRecord); 1737 // Only version #0 and #1 are supported so far. 1738 unsigned module_version = Record[0]; 1739 switch (module_version) { 1740 default: 1741 return Error(InvalidValue); 1742 case 0: 1743 UseRelativeIDs = false; 1744 break; 1745 case 1: 1746 UseRelativeIDs = true; 1747 break; 1748 } 1749 break; 1750 } 1751 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 1752 std::string S; 1753 if (ConvertToString(Record, 0, S)) 1754 return Error(InvalidRecord); 1755 TheModule->setTargetTriple(S); 1756 break; 1757 } 1758 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 1759 std::string S; 1760 if (ConvertToString(Record, 0, S)) 1761 return Error(InvalidRecord); 1762 TheModule->setDataLayout(S); 1763 break; 1764 } 1765 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 1766 std::string S; 1767 if (ConvertToString(Record, 0, S)) 1768 return Error(InvalidRecord); 1769 TheModule->setModuleInlineAsm(S); 1770 break; 1771 } 1772 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 1773 // FIXME: Remove in 4.0. 1774 std::string S; 1775 if (ConvertToString(Record, 0, S)) 1776 return Error(InvalidRecord); 1777 // Ignore value. 1778 break; 1779 } 1780 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 1781 std::string S; 1782 if (ConvertToString(Record, 0, S)) 1783 return Error(InvalidRecord); 1784 SectionTable.push_back(S); 1785 break; 1786 } 1787 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 1788 std::string S; 1789 if (ConvertToString(Record, 0, S)) 1790 return Error(InvalidRecord); 1791 GCTable.push_back(S); 1792 break; 1793 } 1794 // GLOBALVAR: [pointer type, isconst, initid, 1795 // linkage, alignment, section, visibility, threadlocal, 1796 // unnamed_addr] 1797 case bitc::MODULE_CODE_GLOBALVAR: { 1798 if (Record.size() < 6) 1799 return Error(InvalidRecord); 1800 Type *Ty = getTypeByID(Record[0]); 1801 if (!Ty) 1802 return Error(InvalidRecord); 1803 if (!Ty->isPointerTy()) 1804 return Error(InvalidTypeForValue); 1805 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 1806 Ty = cast<PointerType>(Ty)->getElementType(); 1807 1808 bool isConstant = Record[1]; 1809 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 1810 unsigned Alignment = (1 << Record[4]) >> 1; 1811 std::string Section; 1812 if (Record[5]) { 1813 if (Record[5]-1 >= SectionTable.size()) 1814 return Error(InvalidID); 1815 Section = SectionTable[Record[5]-1]; 1816 } 1817 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 1818 if (Record.size() > 6) 1819 Visibility = GetDecodedVisibility(Record[6]); 1820 1821 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 1822 if (Record.size() > 7) 1823 TLM = GetDecodedThreadLocalMode(Record[7]); 1824 1825 bool UnnamedAddr = false; 1826 if (Record.size() > 8) 1827 UnnamedAddr = Record[8]; 1828 1829 bool ExternallyInitialized = false; 1830 if (Record.size() > 9) 1831 ExternallyInitialized = Record[9]; 1832 1833 GlobalVariable *NewGV = 1834 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0, 1835 TLM, AddressSpace, ExternallyInitialized); 1836 NewGV->setAlignment(Alignment); 1837 if (!Section.empty()) 1838 NewGV->setSection(Section); 1839 NewGV->setVisibility(Visibility); 1840 NewGV->setUnnamedAddr(UnnamedAddr); 1841 1842 ValueList.push_back(NewGV); 1843 1844 // Remember which value to use for the global initializer. 1845 if (unsigned InitID = Record[2]) 1846 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 1847 break; 1848 } 1849 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 1850 // alignment, section, visibility, gc, unnamed_addr] 1851 case bitc::MODULE_CODE_FUNCTION: { 1852 if (Record.size() < 8) 1853 return Error(InvalidRecord); 1854 Type *Ty = getTypeByID(Record[0]); 1855 if (!Ty) 1856 return Error(InvalidRecord); 1857 if (!Ty->isPointerTy()) 1858 return Error(InvalidTypeForValue); 1859 FunctionType *FTy = 1860 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 1861 if (!FTy) 1862 return Error(InvalidTypeForValue); 1863 1864 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 1865 "", TheModule); 1866 1867 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 1868 bool isProto = Record[2]; 1869 Func->setLinkage(GetDecodedLinkage(Record[3])); 1870 Func->setAttributes(getAttributes(Record[4])); 1871 1872 Func->setAlignment((1 << Record[5]) >> 1); 1873 if (Record[6]) { 1874 if (Record[6]-1 >= SectionTable.size()) 1875 return Error(InvalidID); 1876 Func->setSection(SectionTable[Record[6]-1]); 1877 } 1878 Func->setVisibility(GetDecodedVisibility(Record[7])); 1879 if (Record.size() > 8 && Record[8]) { 1880 if (Record[8]-1 > GCTable.size()) 1881 return Error(InvalidID); 1882 Func->setGC(GCTable[Record[8]-1].c_str()); 1883 } 1884 bool UnnamedAddr = false; 1885 if (Record.size() > 9) 1886 UnnamedAddr = Record[9]; 1887 Func->setUnnamedAddr(UnnamedAddr); 1888 if (Record.size() > 10 && Record[10] != 0) 1889 FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1)); 1890 ValueList.push_back(Func); 1891 1892 // If this is a function with a body, remember the prototype we are 1893 // creating now, so that we can match up the body with them later. 1894 if (!isProto) { 1895 FunctionsWithBodies.push_back(Func); 1896 if (LazyStreamer) DeferredFunctionInfo[Func] = 0; 1897 } 1898 break; 1899 } 1900 // ALIAS: [alias type, aliasee val#, linkage] 1901 // ALIAS: [alias type, aliasee val#, linkage, visibility] 1902 case bitc::MODULE_CODE_ALIAS: { 1903 if (Record.size() < 3) 1904 return Error(InvalidRecord); 1905 Type *Ty = getTypeByID(Record[0]); 1906 if (!Ty) 1907 return Error(InvalidRecord); 1908 if (!Ty->isPointerTy()) 1909 return Error(InvalidTypeForValue); 1910 1911 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]), 1912 "", 0, TheModule); 1913 // Old bitcode files didn't have visibility field. 1914 if (Record.size() > 3) 1915 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 1916 ValueList.push_back(NewGA); 1917 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 1918 break; 1919 } 1920 /// MODULE_CODE_PURGEVALS: [numvals] 1921 case bitc::MODULE_CODE_PURGEVALS: 1922 // Trim down the value list to the specified size. 1923 if (Record.size() < 1 || Record[0] > ValueList.size()) 1924 return Error(InvalidRecord); 1925 ValueList.shrinkTo(Record[0]); 1926 break; 1927 } 1928 Record.clear(); 1929 } 1930 } 1931 1932 error_code BitcodeReader::ParseBitcodeInto(Module *M) { 1933 TheModule = 0; 1934 1935 if (error_code EC = InitStream()) 1936 return EC; 1937 1938 // Sniff for the signature. 1939 if (Stream.Read(8) != 'B' || 1940 Stream.Read(8) != 'C' || 1941 Stream.Read(4) != 0x0 || 1942 Stream.Read(4) != 0xC || 1943 Stream.Read(4) != 0xE || 1944 Stream.Read(4) != 0xD) 1945 return Error(InvalidBitcodeSignature); 1946 1947 // We expect a number of well-defined blocks, though we don't necessarily 1948 // need to understand them all. 1949 while (1) { 1950 if (Stream.AtEndOfStream()) 1951 return error_code::success(); 1952 1953 BitstreamEntry Entry = 1954 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 1955 1956 switch (Entry.Kind) { 1957 case BitstreamEntry::Error: 1958 return Error(MalformedBlock); 1959 case BitstreamEntry::EndBlock: 1960 return error_code::success(); 1961 1962 case BitstreamEntry::SubBlock: 1963 switch (Entry.ID) { 1964 case bitc::BLOCKINFO_BLOCK_ID: 1965 if (Stream.ReadBlockInfoBlock()) 1966 return Error(MalformedBlock); 1967 break; 1968 case bitc::MODULE_BLOCK_ID: 1969 // Reject multiple MODULE_BLOCK's in a single bitstream. 1970 if (TheModule) 1971 return Error(InvalidMultipleBlocks); 1972 TheModule = M; 1973 if (error_code EC = ParseModule(false)) 1974 return EC; 1975 if (LazyStreamer) 1976 return error_code::success(); 1977 break; 1978 default: 1979 if (Stream.SkipBlock()) 1980 return Error(InvalidRecord); 1981 break; 1982 } 1983 continue; 1984 case BitstreamEntry::Record: 1985 // There should be no records in the top-level of blocks. 1986 1987 // The ranlib in Xcode 4 will align archive members by appending newlines 1988 // to the end of them. If this file size is a multiple of 4 but not 8, we 1989 // have to read and ignore these final 4 bytes :-( 1990 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 && 1991 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a && 1992 Stream.AtEndOfStream()) 1993 return error_code::success(); 1994 1995 return Error(InvalidRecord); 1996 } 1997 } 1998 } 1999 2000 error_code BitcodeReader::ParseModuleTriple(std::string &Triple) { 2001 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2002 return Error(InvalidRecord); 2003 2004 SmallVector<uint64_t, 64> Record; 2005 2006 // Read all the records for this module. 2007 while (1) { 2008 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2009 2010 switch (Entry.Kind) { 2011 case BitstreamEntry::SubBlock: // Handled for us already. 2012 case BitstreamEntry::Error: 2013 return Error(MalformedBlock); 2014 case BitstreamEntry::EndBlock: 2015 return error_code::success(); 2016 case BitstreamEntry::Record: 2017 // The interesting case. 2018 break; 2019 } 2020 2021 // Read a record. 2022 switch (Stream.readRecord(Entry.ID, Record)) { 2023 default: break; // Default behavior, ignore unknown content. 2024 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2025 std::string S; 2026 if (ConvertToString(Record, 0, S)) 2027 return Error(InvalidRecord); 2028 Triple = S; 2029 break; 2030 } 2031 } 2032 Record.clear(); 2033 } 2034 } 2035 2036 error_code BitcodeReader::ParseTriple(std::string &Triple) { 2037 if (error_code EC = InitStream()) 2038 return EC; 2039 2040 // Sniff for the signature. 2041 if (Stream.Read(8) != 'B' || 2042 Stream.Read(8) != 'C' || 2043 Stream.Read(4) != 0x0 || 2044 Stream.Read(4) != 0xC || 2045 Stream.Read(4) != 0xE || 2046 Stream.Read(4) != 0xD) 2047 return Error(InvalidBitcodeSignature); 2048 2049 // We expect a number of well-defined blocks, though we don't necessarily 2050 // need to understand them all. 2051 while (1) { 2052 BitstreamEntry Entry = Stream.advance(); 2053 2054 switch (Entry.Kind) { 2055 case BitstreamEntry::Error: 2056 return Error(MalformedBlock); 2057 case BitstreamEntry::EndBlock: 2058 return error_code::success(); 2059 2060 case BitstreamEntry::SubBlock: 2061 if (Entry.ID == bitc::MODULE_BLOCK_ID) 2062 return ParseModuleTriple(Triple); 2063 2064 // Ignore other sub-blocks. 2065 if (Stream.SkipBlock()) 2066 return Error(MalformedBlock); 2067 continue; 2068 2069 case BitstreamEntry::Record: 2070 Stream.skipRecord(Entry.ID); 2071 continue; 2072 } 2073 } 2074 } 2075 2076 /// ParseMetadataAttachment - Parse metadata attachments. 2077 error_code BitcodeReader::ParseMetadataAttachment() { 2078 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 2079 return Error(InvalidRecord); 2080 2081 SmallVector<uint64_t, 64> Record; 2082 while (1) { 2083 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2084 2085 switch (Entry.Kind) { 2086 case BitstreamEntry::SubBlock: // Handled for us already. 2087 case BitstreamEntry::Error: 2088 return Error(MalformedBlock); 2089 case BitstreamEntry::EndBlock: 2090 return error_code::success(); 2091 case BitstreamEntry::Record: 2092 // The interesting case. 2093 break; 2094 } 2095 2096 // Read a metadata attachment record. 2097 Record.clear(); 2098 switch (Stream.readRecord(Entry.ID, Record)) { 2099 default: // Default behavior: ignore. 2100 break; 2101 case bitc::METADATA_ATTACHMENT: { 2102 unsigned RecordLength = Record.size(); 2103 if (Record.empty() || (RecordLength - 1) % 2 == 1) 2104 return Error(InvalidRecord); 2105 Instruction *Inst = InstructionList[Record[0]]; 2106 for (unsigned i = 1; i != RecordLength; i = i+2) { 2107 unsigned Kind = Record[i]; 2108 DenseMap<unsigned, unsigned>::iterator I = 2109 MDKindMap.find(Kind); 2110 if (I == MDKindMap.end()) 2111 return Error(InvalidID); 2112 Value *Node = MDValueList.getValueFwdRef(Record[i+1]); 2113 Inst->setMetadata(I->second, cast<MDNode>(Node)); 2114 if (I->second == LLVMContext::MD_tbaa) 2115 InstsWithTBAATag.push_back(Inst); 2116 } 2117 break; 2118 } 2119 } 2120 } 2121 } 2122 2123 /// ParseFunctionBody - Lazily parse the specified function body block. 2124 error_code BitcodeReader::ParseFunctionBody(Function *F) { 2125 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 2126 return Error(InvalidRecord); 2127 2128 InstructionList.clear(); 2129 unsigned ModuleValueListSize = ValueList.size(); 2130 unsigned ModuleMDValueListSize = MDValueList.size(); 2131 2132 // Add all the function arguments to the value table. 2133 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 2134 ValueList.push_back(I); 2135 2136 unsigned NextValueNo = ValueList.size(); 2137 BasicBlock *CurBB = 0; 2138 unsigned CurBBNo = 0; 2139 2140 DebugLoc LastLoc; 2141 2142 // Read all the records. 2143 SmallVector<uint64_t, 64> Record; 2144 while (1) { 2145 BitstreamEntry Entry = Stream.advance(); 2146 2147 switch (Entry.Kind) { 2148 case BitstreamEntry::Error: 2149 return Error(MalformedBlock); 2150 case BitstreamEntry::EndBlock: 2151 goto OutOfRecordLoop; 2152 2153 case BitstreamEntry::SubBlock: 2154 switch (Entry.ID) { 2155 default: // Skip unknown content. 2156 if (Stream.SkipBlock()) 2157 return Error(InvalidRecord); 2158 break; 2159 case bitc::CONSTANTS_BLOCK_ID: 2160 if (error_code EC = ParseConstants()) 2161 return EC; 2162 NextValueNo = ValueList.size(); 2163 break; 2164 case bitc::VALUE_SYMTAB_BLOCK_ID: 2165 if (error_code EC = ParseValueSymbolTable()) 2166 return EC; 2167 break; 2168 case bitc::METADATA_ATTACHMENT_ID: 2169 if (error_code EC = ParseMetadataAttachment()) 2170 return EC; 2171 break; 2172 case bitc::METADATA_BLOCK_ID: 2173 if (error_code EC = ParseMetadata()) 2174 return EC; 2175 break; 2176 } 2177 continue; 2178 2179 case BitstreamEntry::Record: 2180 // The interesting case. 2181 break; 2182 } 2183 2184 // Read a record. 2185 Record.clear(); 2186 Instruction *I = 0; 2187 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2188 switch (BitCode) { 2189 default: // Default behavior: reject 2190 return Error(InvalidValue); 2191 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 2192 if (Record.size() < 1 || Record[0] == 0) 2193 return Error(InvalidRecord); 2194 // Create all the basic blocks for the function. 2195 FunctionBBs.resize(Record[0]); 2196 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 2197 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 2198 CurBB = FunctionBBs[0]; 2199 continue; 2200 2201 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 2202 // This record indicates that the last instruction is at the same 2203 // location as the previous instruction with a location. 2204 I = 0; 2205 2206 // Get the last instruction emitted. 2207 if (CurBB && !CurBB->empty()) 2208 I = &CurBB->back(); 2209 else if (CurBBNo && FunctionBBs[CurBBNo-1] && 2210 !FunctionBBs[CurBBNo-1]->empty()) 2211 I = &FunctionBBs[CurBBNo-1]->back(); 2212 2213 if (I == 0) 2214 return Error(InvalidRecord); 2215 I->setDebugLoc(LastLoc); 2216 I = 0; 2217 continue; 2218 2219 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 2220 I = 0; // Get the last instruction emitted. 2221 if (CurBB && !CurBB->empty()) 2222 I = &CurBB->back(); 2223 else if (CurBBNo && FunctionBBs[CurBBNo-1] && 2224 !FunctionBBs[CurBBNo-1]->empty()) 2225 I = &FunctionBBs[CurBBNo-1]->back(); 2226 if (I == 0 || Record.size() < 4) 2227 return Error(InvalidRecord); 2228 2229 unsigned Line = Record[0], Col = Record[1]; 2230 unsigned ScopeID = Record[2], IAID = Record[3]; 2231 2232 MDNode *Scope = 0, *IA = 0; 2233 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1)); 2234 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1)); 2235 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 2236 I->setDebugLoc(LastLoc); 2237 I = 0; 2238 continue; 2239 } 2240 2241 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 2242 unsigned OpNum = 0; 2243 Value *LHS, *RHS; 2244 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2245 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2246 OpNum+1 > Record.size()) 2247 return Error(InvalidRecord); 2248 2249 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 2250 if (Opc == -1) 2251 return Error(InvalidRecord); 2252 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 2253 InstructionList.push_back(I); 2254 if (OpNum < Record.size()) { 2255 if (Opc == Instruction::Add || 2256 Opc == Instruction::Sub || 2257 Opc == Instruction::Mul || 2258 Opc == Instruction::Shl) { 2259 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2260 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 2261 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2262 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 2263 } else if (Opc == Instruction::SDiv || 2264 Opc == Instruction::UDiv || 2265 Opc == Instruction::LShr || 2266 Opc == Instruction::AShr) { 2267 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 2268 cast<BinaryOperator>(I)->setIsExact(true); 2269 } else if (isa<FPMathOperator>(I)) { 2270 FastMathFlags FMF; 2271 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra)) 2272 FMF.setUnsafeAlgebra(); 2273 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs)) 2274 FMF.setNoNaNs(); 2275 if (0 != (Record[OpNum] & FastMathFlags::NoInfs)) 2276 FMF.setNoInfs(); 2277 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros)) 2278 FMF.setNoSignedZeros(); 2279 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal)) 2280 FMF.setAllowReciprocal(); 2281 if (FMF.any()) 2282 I->setFastMathFlags(FMF); 2283 } 2284 2285 } 2286 break; 2287 } 2288 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 2289 unsigned OpNum = 0; 2290 Value *Op; 2291 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2292 OpNum+2 != Record.size()) 2293 return Error(InvalidRecord); 2294 2295 Type *ResTy = getTypeByID(Record[OpNum]); 2296 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 2297 if (Opc == -1 || ResTy == 0) 2298 return Error(InvalidRecord); 2299 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 2300 InstructionList.push_back(I); 2301 break; 2302 } 2303 case bitc::FUNC_CODE_INST_INBOUNDS_GEP: 2304 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 2305 unsigned OpNum = 0; 2306 Value *BasePtr; 2307 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 2308 return Error(InvalidRecord); 2309 2310 SmallVector<Value*, 16> GEPIdx; 2311 while (OpNum != Record.size()) { 2312 Value *Op; 2313 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2314 return Error(InvalidRecord); 2315 GEPIdx.push_back(Op); 2316 } 2317 2318 I = GetElementPtrInst::Create(BasePtr, GEPIdx); 2319 InstructionList.push_back(I); 2320 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP) 2321 cast<GetElementPtrInst>(I)->setIsInBounds(true); 2322 break; 2323 } 2324 2325 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 2326 // EXTRACTVAL: [opty, opval, n x indices] 2327 unsigned OpNum = 0; 2328 Value *Agg; 2329 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2330 return Error(InvalidRecord); 2331 2332 SmallVector<unsigned, 4> EXTRACTVALIdx; 2333 for (unsigned RecSize = Record.size(); 2334 OpNum != RecSize; ++OpNum) { 2335 uint64_t Index = Record[OpNum]; 2336 if ((unsigned)Index != Index) 2337 return Error(InvalidValue); 2338 EXTRACTVALIdx.push_back((unsigned)Index); 2339 } 2340 2341 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 2342 InstructionList.push_back(I); 2343 break; 2344 } 2345 2346 case bitc::FUNC_CODE_INST_INSERTVAL: { 2347 // INSERTVAL: [opty, opval, opty, opval, n x indices] 2348 unsigned OpNum = 0; 2349 Value *Agg; 2350 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2351 return Error(InvalidRecord); 2352 Value *Val; 2353 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 2354 return Error(InvalidRecord); 2355 2356 SmallVector<unsigned, 4> INSERTVALIdx; 2357 for (unsigned RecSize = Record.size(); 2358 OpNum != RecSize; ++OpNum) { 2359 uint64_t Index = Record[OpNum]; 2360 if ((unsigned)Index != Index) 2361 return Error(InvalidValue); 2362 INSERTVALIdx.push_back((unsigned)Index); 2363 } 2364 2365 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 2366 InstructionList.push_back(I); 2367 break; 2368 } 2369 2370 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 2371 // obsolete form of select 2372 // handles select i1 ... in old bitcode 2373 unsigned OpNum = 0; 2374 Value *TrueVal, *FalseVal, *Cond; 2375 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2376 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 2377 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 2378 return Error(InvalidRecord); 2379 2380 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2381 InstructionList.push_back(I); 2382 break; 2383 } 2384 2385 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 2386 // new form of select 2387 // handles select i1 or select [N x i1] 2388 unsigned OpNum = 0; 2389 Value *TrueVal, *FalseVal, *Cond; 2390 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2391 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 2392 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 2393 return Error(InvalidRecord); 2394 2395 // select condition can be either i1 or [N x i1] 2396 if (VectorType* vector_type = 2397 dyn_cast<VectorType>(Cond->getType())) { 2398 // expect <n x i1> 2399 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 2400 return Error(InvalidTypeForValue); 2401 } else { 2402 // expect i1 2403 if (Cond->getType() != Type::getInt1Ty(Context)) 2404 return Error(InvalidTypeForValue); 2405 } 2406 2407 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2408 InstructionList.push_back(I); 2409 break; 2410 } 2411 2412 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 2413 unsigned OpNum = 0; 2414 Value *Vec, *Idx; 2415 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2416 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx)) 2417 return Error(InvalidRecord); 2418 I = ExtractElementInst::Create(Vec, Idx); 2419 InstructionList.push_back(I); 2420 break; 2421 } 2422 2423 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 2424 unsigned OpNum = 0; 2425 Value *Vec, *Elt, *Idx; 2426 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2427 popValue(Record, OpNum, NextValueNo, 2428 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 2429 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx)) 2430 return Error(InvalidRecord); 2431 I = InsertElementInst::Create(Vec, Elt, Idx); 2432 InstructionList.push_back(I); 2433 break; 2434 } 2435 2436 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 2437 unsigned OpNum = 0; 2438 Value *Vec1, *Vec2, *Mask; 2439 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 2440 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 2441 return Error(InvalidRecord); 2442 2443 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 2444 return Error(InvalidRecord); 2445 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 2446 InstructionList.push_back(I); 2447 break; 2448 } 2449 2450 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 2451 // Old form of ICmp/FCmp returning bool 2452 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 2453 // both legal on vectors but had different behaviour. 2454 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 2455 // FCmp/ICmp returning bool or vector of bool 2456 2457 unsigned OpNum = 0; 2458 Value *LHS, *RHS; 2459 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2460 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2461 OpNum+1 != Record.size()) 2462 return Error(InvalidRecord); 2463 2464 if (LHS->getType()->isFPOrFPVectorTy()) 2465 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 2466 else 2467 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 2468 InstructionList.push_back(I); 2469 break; 2470 } 2471 2472 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 2473 { 2474 unsigned Size = Record.size(); 2475 if (Size == 0) { 2476 I = ReturnInst::Create(Context); 2477 InstructionList.push_back(I); 2478 break; 2479 } 2480 2481 unsigned OpNum = 0; 2482 Value *Op = NULL; 2483 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2484 return Error(InvalidRecord); 2485 if (OpNum != Record.size()) 2486 return Error(InvalidRecord); 2487 2488 I = ReturnInst::Create(Context, Op); 2489 InstructionList.push_back(I); 2490 break; 2491 } 2492 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 2493 if (Record.size() != 1 && Record.size() != 3) 2494 return Error(InvalidRecord); 2495 BasicBlock *TrueDest = getBasicBlock(Record[0]); 2496 if (TrueDest == 0) 2497 return Error(InvalidRecord); 2498 2499 if (Record.size() == 1) { 2500 I = BranchInst::Create(TrueDest); 2501 InstructionList.push_back(I); 2502 } 2503 else { 2504 BasicBlock *FalseDest = getBasicBlock(Record[1]); 2505 Value *Cond = getValue(Record, 2, NextValueNo, 2506 Type::getInt1Ty(Context)); 2507 if (FalseDest == 0 || Cond == 0) 2508 return Error(InvalidRecord); 2509 I = BranchInst::Create(TrueDest, FalseDest, Cond); 2510 InstructionList.push_back(I); 2511 } 2512 break; 2513 } 2514 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 2515 // Check magic 2516 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 2517 // "New" SwitchInst format with case ranges. The changes to write this 2518 // format were reverted but we still recognize bitcode that uses it. 2519 // Hopefully someday we will have support for case ranges and can use 2520 // this format again. 2521 2522 Type *OpTy = getTypeByID(Record[1]); 2523 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 2524 2525 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 2526 BasicBlock *Default = getBasicBlock(Record[3]); 2527 if (OpTy == 0 || Cond == 0 || Default == 0) 2528 return Error(InvalidRecord); 2529 2530 unsigned NumCases = Record[4]; 2531 2532 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 2533 InstructionList.push_back(SI); 2534 2535 unsigned CurIdx = 5; 2536 for (unsigned i = 0; i != NumCases; ++i) { 2537 SmallVector<ConstantInt*, 1> CaseVals; 2538 unsigned NumItems = Record[CurIdx++]; 2539 for (unsigned ci = 0; ci != NumItems; ++ci) { 2540 bool isSingleNumber = Record[CurIdx++]; 2541 2542 APInt Low; 2543 unsigned ActiveWords = 1; 2544 if (ValueBitWidth > 64) 2545 ActiveWords = Record[CurIdx++]; 2546 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 2547 ValueBitWidth); 2548 CurIdx += ActiveWords; 2549 2550 if (!isSingleNumber) { 2551 ActiveWords = 1; 2552 if (ValueBitWidth > 64) 2553 ActiveWords = Record[CurIdx++]; 2554 APInt High = 2555 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 2556 ValueBitWidth); 2557 CurIdx += ActiveWords; 2558 2559 // FIXME: It is not clear whether values in the range should be 2560 // compared as signed or unsigned values. The partially 2561 // implemented changes that used this format in the past used 2562 // unsigned comparisons. 2563 for ( ; Low.ule(High); ++Low) 2564 CaseVals.push_back(ConstantInt::get(Context, Low)); 2565 } else 2566 CaseVals.push_back(ConstantInt::get(Context, Low)); 2567 } 2568 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 2569 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 2570 cve = CaseVals.end(); cvi != cve; ++cvi) 2571 SI->addCase(*cvi, DestBB); 2572 } 2573 I = SI; 2574 break; 2575 } 2576 2577 // Old SwitchInst format without case ranges. 2578 2579 if (Record.size() < 3 || (Record.size() & 1) == 0) 2580 return Error(InvalidRecord); 2581 Type *OpTy = getTypeByID(Record[0]); 2582 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 2583 BasicBlock *Default = getBasicBlock(Record[2]); 2584 if (OpTy == 0 || Cond == 0 || Default == 0) 2585 return Error(InvalidRecord); 2586 unsigned NumCases = (Record.size()-3)/2; 2587 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 2588 InstructionList.push_back(SI); 2589 for (unsigned i = 0, e = NumCases; i != e; ++i) { 2590 ConstantInt *CaseVal = 2591 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 2592 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 2593 if (CaseVal == 0 || DestBB == 0) { 2594 delete SI; 2595 return Error(InvalidRecord); 2596 } 2597 SI->addCase(CaseVal, DestBB); 2598 } 2599 I = SI; 2600 break; 2601 } 2602 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 2603 if (Record.size() < 2) 2604 return Error(InvalidRecord); 2605 Type *OpTy = getTypeByID(Record[0]); 2606 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 2607 if (OpTy == 0 || Address == 0) 2608 return Error(InvalidRecord); 2609 unsigned NumDests = Record.size()-2; 2610 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 2611 InstructionList.push_back(IBI); 2612 for (unsigned i = 0, e = NumDests; i != e; ++i) { 2613 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 2614 IBI->addDestination(DestBB); 2615 } else { 2616 delete IBI; 2617 return Error(InvalidRecord); 2618 } 2619 } 2620 I = IBI; 2621 break; 2622 } 2623 2624 case bitc::FUNC_CODE_INST_INVOKE: { 2625 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 2626 if (Record.size() < 4) 2627 return Error(InvalidRecord); 2628 AttributeSet PAL = getAttributes(Record[0]); 2629 unsigned CCInfo = Record[1]; 2630 BasicBlock *NormalBB = getBasicBlock(Record[2]); 2631 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 2632 2633 unsigned OpNum = 4; 2634 Value *Callee; 2635 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 2636 return Error(InvalidRecord); 2637 2638 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 2639 FunctionType *FTy = !CalleeTy ? 0 : 2640 dyn_cast<FunctionType>(CalleeTy->getElementType()); 2641 2642 // Check that the right number of fixed parameters are here. 2643 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 || 2644 Record.size() < OpNum+FTy->getNumParams()) 2645 return Error(InvalidRecord); 2646 2647 SmallVector<Value*, 16> Ops; 2648 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 2649 Ops.push_back(getValue(Record, OpNum, NextValueNo, 2650 FTy->getParamType(i))); 2651 if (Ops.back() == 0) 2652 return Error(InvalidRecord); 2653 } 2654 2655 if (!FTy->isVarArg()) { 2656 if (Record.size() != OpNum) 2657 return Error(InvalidRecord); 2658 } else { 2659 // Read type/value pairs for varargs params. 2660 while (OpNum != Record.size()) { 2661 Value *Op; 2662 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2663 return Error(InvalidRecord); 2664 Ops.push_back(Op); 2665 } 2666 } 2667 2668 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops); 2669 InstructionList.push_back(I); 2670 cast<InvokeInst>(I)->setCallingConv( 2671 static_cast<CallingConv::ID>(CCInfo)); 2672 cast<InvokeInst>(I)->setAttributes(PAL); 2673 break; 2674 } 2675 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 2676 unsigned Idx = 0; 2677 Value *Val = 0; 2678 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 2679 return Error(InvalidRecord); 2680 I = ResumeInst::Create(Val); 2681 InstructionList.push_back(I); 2682 break; 2683 } 2684 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 2685 I = new UnreachableInst(Context); 2686 InstructionList.push_back(I); 2687 break; 2688 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 2689 if (Record.size() < 1 || ((Record.size()-1)&1)) 2690 return Error(InvalidRecord); 2691 Type *Ty = getTypeByID(Record[0]); 2692 if (!Ty) 2693 return Error(InvalidRecord); 2694 2695 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 2696 InstructionList.push_back(PN); 2697 2698 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 2699 Value *V; 2700 // With the new function encoding, it is possible that operands have 2701 // negative IDs (for forward references). Use a signed VBR 2702 // representation to keep the encoding small. 2703 if (UseRelativeIDs) 2704 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 2705 else 2706 V = getValue(Record, 1+i, NextValueNo, Ty); 2707 BasicBlock *BB = getBasicBlock(Record[2+i]); 2708 if (!V || !BB) 2709 return Error(InvalidRecord); 2710 PN->addIncoming(V, BB); 2711 } 2712 I = PN; 2713 break; 2714 } 2715 2716 case bitc::FUNC_CODE_INST_LANDINGPAD: { 2717 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 2718 unsigned Idx = 0; 2719 if (Record.size() < 4) 2720 return Error(InvalidRecord); 2721 Type *Ty = getTypeByID(Record[Idx++]); 2722 if (!Ty) 2723 return Error(InvalidRecord); 2724 Value *PersFn = 0; 2725 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 2726 return Error(InvalidRecord); 2727 2728 bool IsCleanup = !!Record[Idx++]; 2729 unsigned NumClauses = Record[Idx++]; 2730 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses); 2731 LP->setCleanup(IsCleanup); 2732 for (unsigned J = 0; J != NumClauses; ++J) { 2733 LandingPadInst::ClauseType CT = 2734 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 2735 Value *Val; 2736 2737 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 2738 delete LP; 2739 return Error(InvalidRecord); 2740 } 2741 2742 assert((CT != LandingPadInst::Catch || 2743 !isa<ArrayType>(Val->getType())) && 2744 "Catch clause has a invalid type!"); 2745 assert((CT != LandingPadInst::Filter || 2746 isa<ArrayType>(Val->getType())) && 2747 "Filter clause has invalid type!"); 2748 LP->addClause(Val); 2749 } 2750 2751 I = LP; 2752 InstructionList.push_back(I); 2753 break; 2754 } 2755 2756 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 2757 if (Record.size() != 4) 2758 return Error(InvalidRecord); 2759 PointerType *Ty = 2760 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 2761 Type *OpTy = getTypeByID(Record[1]); 2762 Value *Size = getFnValueByID(Record[2], OpTy); 2763 unsigned Align = Record[3]; 2764 if (!Ty || !Size) 2765 return Error(InvalidRecord); 2766 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 2767 InstructionList.push_back(I); 2768 break; 2769 } 2770 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 2771 unsigned OpNum = 0; 2772 Value *Op; 2773 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2774 OpNum+2 != Record.size()) 2775 return Error(InvalidRecord); 2776 2777 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 2778 InstructionList.push_back(I); 2779 break; 2780 } 2781 case bitc::FUNC_CODE_INST_LOADATOMIC: { 2782 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 2783 unsigned OpNum = 0; 2784 Value *Op; 2785 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2786 OpNum+4 != Record.size()) 2787 return Error(InvalidRecord); 2788 2789 2790 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2791 if (Ordering == NotAtomic || Ordering == Release || 2792 Ordering == AcquireRelease) 2793 return Error(InvalidRecord); 2794 if (Ordering != NotAtomic && Record[OpNum] == 0) 2795 return Error(InvalidRecord); 2796 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2797 2798 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1, 2799 Ordering, SynchScope); 2800 InstructionList.push_back(I); 2801 break; 2802 } 2803 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol] 2804 unsigned OpNum = 0; 2805 Value *Val, *Ptr; 2806 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2807 popValue(Record, OpNum, NextValueNo, 2808 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2809 OpNum+2 != Record.size()) 2810 return Error(InvalidRecord); 2811 2812 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 2813 InstructionList.push_back(I); 2814 break; 2815 } 2816 case bitc::FUNC_CODE_INST_STOREATOMIC: { 2817 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 2818 unsigned OpNum = 0; 2819 Value *Val, *Ptr; 2820 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2821 popValue(Record, OpNum, NextValueNo, 2822 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2823 OpNum+4 != Record.size()) 2824 return Error(InvalidRecord); 2825 2826 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2827 if (Ordering == NotAtomic || Ordering == Acquire || 2828 Ordering == AcquireRelease) 2829 return Error(InvalidRecord); 2830 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2831 if (Ordering != NotAtomic && Record[OpNum] == 0) 2832 return Error(InvalidRecord); 2833 2834 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1, 2835 Ordering, SynchScope); 2836 InstructionList.push_back(I); 2837 break; 2838 } 2839 case bitc::FUNC_CODE_INST_CMPXCHG: { 2840 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope] 2841 unsigned OpNum = 0; 2842 Value *Ptr, *Cmp, *New; 2843 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2844 popValue(Record, OpNum, NextValueNo, 2845 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) || 2846 popValue(Record, OpNum, NextValueNo, 2847 cast<PointerType>(Ptr->getType())->getElementType(), New) || 2848 OpNum+3 != Record.size()) 2849 return Error(InvalidRecord); 2850 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]); 2851 if (Ordering == NotAtomic || Ordering == Unordered) 2852 return Error(InvalidRecord); 2853 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]); 2854 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope); 2855 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 2856 InstructionList.push_back(I); 2857 break; 2858 } 2859 case bitc::FUNC_CODE_INST_ATOMICRMW: { 2860 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 2861 unsigned OpNum = 0; 2862 Value *Ptr, *Val; 2863 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 2864 popValue(Record, OpNum, NextValueNo, 2865 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 2866 OpNum+4 != Record.size()) 2867 return Error(InvalidRecord); 2868 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]); 2869 if (Operation < AtomicRMWInst::FIRST_BINOP || 2870 Operation > AtomicRMWInst::LAST_BINOP) 2871 return Error(InvalidRecord); 2872 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 2873 if (Ordering == NotAtomic || Ordering == Unordered) 2874 return Error(InvalidRecord); 2875 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 2876 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 2877 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 2878 InstructionList.push_back(I); 2879 break; 2880 } 2881 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 2882 if (2 != Record.size()) 2883 return Error(InvalidRecord); 2884 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]); 2885 if (Ordering == NotAtomic || Ordering == Unordered || 2886 Ordering == Monotonic) 2887 return Error(InvalidRecord); 2888 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]); 2889 I = new FenceInst(Context, Ordering, SynchScope); 2890 InstructionList.push_back(I); 2891 break; 2892 } 2893 case bitc::FUNC_CODE_INST_CALL: { 2894 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 2895 if (Record.size() < 3) 2896 return Error(InvalidRecord); 2897 2898 AttributeSet PAL = getAttributes(Record[0]); 2899 unsigned CCInfo = Record[1]; 2900 2901 unsigned OpNum = 2; 2902 Value *Callee; 2903 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 2904 return Error(InvalidRecord); 2905 2906 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 2907 FunctionType *FTy = 0; 2908 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 2909 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 2910 return Error(InvalidRecord); 2911 2912 SmallVector<Value*, 16> Args; 2913 // Read the fixed params. 2914 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 2915 if (FTy->getParamType(i)->isLabelTy()) 2916 Args.push_back(getBasicBlock(Record[OpNum])); 2917 else 2918 Args.push_back(getValue(Record, OpNum, NextValueNo, 2919 FTy->getParamType(i))); 2920 if (Args.back() == 0) 2921 return Error(InvalidRecord); 2922 } 2923 2924 // Read type/value pairs for varargs params. 2925 if (!FTy->isVarArg()) { 2926 if (OpNum != Record.size()) 2927 return Error(InvalidRecord); 2928 } else { 2929 while (OpNum != Record.size()) { 2930 Value *Op; 2931 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2932 return Error(InvalidRecord); 2933 Args.push_back(Op); 2934 } 2935 } 2936 2937 I = CallInst::Create(Callee, Args); 2938 InstructionList.push_back(I); 2939 cast<CallInst>(I)->setCallingConv( 2940 static_cast<CallingConv::ID>(CCInfo>>1)); 2941 cast<CallInst>(I)->setTailCall(CCInfo & 1); 2942 cast<CallInst>(I)->setAttributes(PAL); 2943 break; 2944 } 2945 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 2946 if (Record.size() < 3) 2947 return Error(InvalidRecord); 2948 Type *OpTy = getTypeByID(Record[0]); 2949 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 2950 Type *ResTy = getTypeByID(Record[2]); 2951 if (!OpTy || !Op || !ResTy) 2952 return Error(InvalidRecord); 2953 I = new VAArgInst(Op, ResTy); 2954 InstructionList.push_back(I); 2955 break; 2956 } 2957 } 2958 2959 // Add instruction to end of current BB. If there is no current BB, reject 2960 // this file. 2961 if (CurBB == 0) { 2962 delete I; 2963 return Error(InvalidInstructionWithNoBB); 2964 } 2965 CurBB->getInstList().push_back(I); 2966 2967 // If this was a terminator instruction, move to the next block. 2968 if (isa<TerminatorInst>(I)) { 2969 ++CurBBNo; 2970 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0; 2971 } 2972 2973 // Non-void values get registered in the value table for future use. 2974 if (I && !I->getType()->isVoidTy()) 2975 ValueList.AssignValue(I, NextValueNo++); 2976 } 2977 2978 OutOfRecordLoop: 2979 2980 // Check the function list for unresolved values. 2981 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 2982 if (A->getParent() == 0) { 2983 // We found at least one unresolved value. Nuke them all to avoid leaks. 2984 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 2985 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) { 2986 A->replaceAllUsesWith(UndefValue::get(A->getType())); 2987 delete A; 2988 } 2989 } 2990 return Error(NeverResolvedValueFoundInFunction); 2991 } 2992 } 2993 2994 // FIXME: Check for unresolved forward-declared metadata references 2995 // and clean up leaks. 2996 2997 // See if anything took the address of blocks in this function. If so, 2998 // resolve them now. 2999 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI = 3000 BlockAddrFwdRefs.find(F); 3001 if (BAFRI != BlockAddrFwdRefs.end()) { 3002 std::vector<BlockAddrRefTy> &RefList = BAFRI->second; 3003 for (unsigned i = 0, e = RefList.size(); i != e; ++i) { 3004 unsigned BlockIdx = RefList[i].first; 3005 if (BlockIdx >= FunctionBBs.size()) 3006 return Error(InvalidID); 3007 3008 GlobalVariable *FwdRef = RefList[i].second; 3009 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx])); 3010 FwdRef->eraseFromParent(); 3011 } 3012 3013 BlockAddrFwdRefs.erase(BAFRI); 3014 } 3015 3016 // Trim the value list down to the size it was before we parsed this function. 3017 ValueList.shrinkTo(ModuleValueListSize); 3018 MDValueList.shrinkTo(ModuleMDValueListSize); 3019 std::vector<BasicBlock*>().swap(FunctionBBs); 3020 return error_code::success(); 3021 } 3022 3023 /// Find the function body in the bitcode stream 3024 error_code BitcodeReader::FindFunctionInStream(Function *F, 3025 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) { 3026 while (DeferredFunctionInfoIterator->second == 0) { 3027 if (Stream.AtEndOfStream()) 3028 return Error(CouldNotFindFunctionInStream); 3029 // ParseModule will parse the next body in the stream and set its 3030 // position in the DeferredFunctionInfo map. 3031 if (error_code EC = ParseModule(true)) 3032 return EC; 3033 } 3034 return error_code::success(); 3035 } 3036 3037 //===----------------------------------------------------------------------===// 3038 // GVMaterializer implementation 3039 //===----------------------------------------------------------------------===// 3040 3041 3042 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const { 3043 if (const Function *F = dyn_cast<Function>(GV)) { 3044 return F->isDeclaration() && 3045 DeferredFunctionInfo.count(const_cast<Function*>(F)); 3046 } 3047 return false; 3048 } 3049 3050 error_code BitcodeReader::Materialize(GlobalValue *GV) { 3051 Function *F = dyn_cast<Function>(GV); 3052 // If it's not a function or is already material, ignore the request. 3053 if (!F || !F->isMaterializable()) 3054 return error_code::success(); 3055 3056 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 3057 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 3058 // If its position is recorded as 0, its body is somewhere in the stream 3059 // but we haven't seen it yet. 3060 if (DFII->second == 0 && LazyStreamer) 3061 if (error_code EC = FindFunctionInStream(F, DFII)) 3062 return EC; 3063 3064 // Move the bit stream to the saved position of the deferred function body. 3065 Stream.JumpToBit(DFII->second); 3066 3067 if (error_code EC = ParseFunctionBody(F)) 3068 return EC; 3069 3070 // Upgrade any old intrinsic calls in the function. 3071 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 3072 E = UpgradedIntrinsics.end(); I != E; ++I) { 3073 if (I->first != I->second) { 3074 for (Value::use_iterator UI = I->first->use_begin(), 3075 UE = I->first->use_end(); UI != UE; ) { 3076 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3077 UpgradeIntrinsicCall(CI, I->second); 3078 } 3079 } 3080 } 3081 3082 return error_code::success(); 3083 } 3084 3085 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 3086 const Function *F = dyn_cast<Function>(GV); 3087 if (!F || F->isDeclaration()) 3088 return false; 3089 return DeferredFunctionInfo.count(const_cast<Function*>(F)); 3090 } 3091 3092 void BitcodeReader::Dematerialize(GlobalValue *GV) { 3093 Function *F = dyn_cast<Function>(GV); 3094 // If this function isn't dematerializable, this is a noop. 3095 if (!F || !isDematerializable(F)) 3096 return; 3097 3098 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 3099 3100 // Just forget the function body, we can remat it later. 3101 F->deleteBody(); 3102 } 3103 3104 3105 error_code BitcodeReader::MaterializeModule(Module *M) { 3106 assert(M == TheModule && 3107 "Can only Materialize the Module this BitcodeReader is attached to."); 3108 // Iterate over the module, deserializing any functions that are still on 3109 // disk. 3110 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 3111 F != E; ++F) { 3112 if (F->isMaterializable()) { 3113 if (error_code EC = Materialize(F)) 3114 return EC; 3115 } 3116 } 3117 // At this point, if there are any function bodies, the current bit is 3118 // pointing to the END_BLOCK record after them. Now make sure the rest 3119 // of the bits in the module have been read. 3120 if (NextUnreadBit) 3121 ParseModule(true); 3122 3123 // Upgrade any intrinsic calls that slipped through (should not happen!) and 3124 // delete the old functions to clean up. We can't do this unless the entire 3125 // module is materialized because there could always be another function body 3126 // with calls to the old function. 3127 for (std::vector<std::pair<Function*, Function*> >::iterator I = 3128 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 3129 if (I->first != I->second) { 3130 for (Value::use_iterator UI = I->first->use_begin(), 3131 UE = I->first->use_end(); UI != UE; ) { 3132 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3133 UpgradeIntrinsicCall(CI, I->second); 3134 } 3135 if (!I->first->use_empty()) 3136 I->first->replaceAllUsesWith(I->second); 3137 I->first->eraseFromParent(); 3138 } 3139 } 3140 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 3141 3142 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 3143 UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 3144 3145 return error_code::success(); 3146 } 3147 3148 error_code BitcodeReader::InitStream() { 3149 if (LazyStreamer) 3150 return InitLazyStream(); 3151 return InitStreamFromBuffer(); 3152 } 3153 3154 error_code BitcodeReader::InitStreamFromBuffer() { 3155 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 3156 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 3157 3158 if (Buffer->getBufferSize() & 3) { 3159 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd)) 3160 return Error(InvalidBitcodeSignature); 3161 else 3162 return Error(BitcodeStreamInvalidSize); 3163 } 3164 3165 // If we have a wrapper header, parse it and ignore the non-bc file contents. 3166 // The magic number is 0x0B17C0DE stored in little endian. 3167 if (isBitcodeWrapper(BufPtr, BufEnd)) 3168 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 3169 return Error(InvalidBitcodeWrapperHeader); 3170 3171 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 3172 Stream.init(*StreamFile); 3173 3174 return error_code::success(); 3175 } 3176 3177 error_code BitcodeReader::InitLazyStream() { 3178 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 3179 // see it. 3180 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer); 3181 StreamFile.reset(new BitstreamReader(Bytes)); 3182 Stream.init(*StreamFile); 3183 3184 unsigned char buf[16]; 3185 if (Bytes->readBytes(0, 16, buf) == -1) 3186 return Error(BitcodeStreamInvalidSize); 3187 3188 if (!isBitcode(buf, buf + 16)) 3189 return Error(InvalidBitcodeSignature); 3190 3191 if (isBitcodeWrapper(buf, buf + 4)) { 3192 const unsigned char *bitcodeStart = buf; 3193 const unsigned char *bitcodeEnd = buf + 16; 3194 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 3195 Bytes->dropLeadingBytes(bitcodeStart - buf); 3196 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart); 3197 } 3198 return error_code::success(); 3199 } 3200 3201 namespace { 3202 class BitcodeErrorCategoryType : public _do_message { 3203 const char *name() const LLVM_OVERRIDE { 3204 return "llvm.bitcode"; 3205 } 3206 std::string message(int IE) const LLVM_OVERRIDE { 3207 BitcodeReader::ErrorType E = static_cast<BitcodeReader::ErrorType>(IE); 3208 switch (E) { 3209 case BitcodeReader::BitcodeStreamInvalidSize: 3210 return "Bitcode stream length should be >= 16 bytes and a multiple of 4"; 3211 case BitcodeReader::ConflictingMETADATA_KINDRecords: 3212 return "Conflicting METADATA_KIND records"; 3213 case BitcodeReader::CouldNotFindFunctionInStream: 3214 return "Could not find function in stream"; 3215 case BitcodeReader::ExpectedConstant: 3216 return "Expected a constant"; 3217 case BitcodeReader::InsufficientFunctionProtos: 3218 return "Insufficient function protos"; 3219 case BitcodeReader::InvalidBitcodeSignature: 3220 return "Invalid bitcode signature"; 3221 case BitcodeReader::InvalidBitcodeWrapperHeader: 3222 return "Invalid bitcode wrapper header"; 3223 case BitcodeReader::InvalidConstantReference: 3224 return "Invalid ronstant reference"; 3225 case BitcodeReader::InvalidID: 3226 return "Invalid ID"; 3227 case BitcodeReader::InvalidInstructionWithNoBB: 3228 return "Invalid instruction with no BB"; 3229 case BitcodeReader::InvalidRecord: 3230 return "Invalid record"; 3231 case BitcodeReader::InvalidTypeForValue: 3232 return "Invalid type for value"; 3233 case BitcodeReader::InvalidTYPETable: 3234 return "Invalid TYPE table"; 3235 case BitcodeReader::InvalidType: 3236 return "Invalid type"; 3237 case BitcodeReader::MalformedBlock: 3238 return "Malformed block"; 3239 case BitcodeReader::MalformedGlobalInitializerSet: 3240 return "Malformed global initializer set"; 3241 case BitcodeReader::InvalidMultipleBlocks: 3242 return "Invalid multiple blocks"; 3243 case BitcodeReader::NeverResolvedValueFoundInFunction: 3244 return "Never resolved value found in function"; 3245 case BitcodeReader::InvalidValue: 3246 return "Invalid value"; 3247 } 3248 llvm_unreachable("Unknown error type!"); 3249 } 3250 }; 3251 } 3252 3253 const error_category &BitcodeReader::BitcodeErrorCategory() { 3254 static BitcodeErrorCategoryType O; 3255 return O; 3256 } 3257 3258 //===----------------------------------------------------------------------===// 3259 // External interface 3260 //===----------------------------------------------------------------------===// 3261 3262 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file. 3263 /// 3264 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer, 3265 LLVMContext& Context, 3266 std::string *ErrMsg) { 3267 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 3268 BitcodeReader *R = new BitcodeReader(Buffer, Context); 3269 M->setMaterializer(R); 3270 if (error_code EC = R->ParseBitcodeInto(M)) { 3271 if (ErrMsg) 3272 *ErrMsg = EC.message(); 3273 3274 delete M; // Also deletes R. 3275 return 0; 3276 } 3277 // Have the BitcodeReader dtor delete 'Buffer'. 3278 R->setBufferOwned(true); 3279 3280 R->materializeForwardReferencedFunctions(); 3281 3282 return M; 3283 } 3284 3285 3286 Module *llvm::getStreamedBitcodeModule(const std::string &name, 3287 DataStreamer *streamer, 3288 LLVMContext &Context, 3289 std::string *ErrMsg) { 3290 Module *M = new Module(name, Context); 3291 BitcodeReader *R = new BitcodeReader(streamer, Context); 3292 M->setMaterializer(R); 3293 if (error_code EC = R->ParseBitcodeInto(M)) { 3294 if (ErrMsg) 3295 *ErrMsg = EC.message(); 3296 delete M; // Also deletes R. 3297 return 0; 3298 } 3299 R->setBufferOwned(false); // no buffer to delete 3300 return M; 3301 } 3302 3303 /// ParseBitcodeFile - Read the specified bitcode file, returning the module. 3304 /// If an error occurs, return null and fill in *ErrMsg if non-null. 3305 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, 3306 std::string *ErrMsg){ 3307 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg); 3308 if (!M) return 0; 3309 3310 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether 3311 // there was an error. 3312 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false); 3313 3314 // Read in the entire module, and destroy the BitcodeReader. 3315 if (M->MaterializeAllPermanently(ErrMsg)) { 3316 delete M; 3317 return 0; 3318 } 3319 3320 // TODO: Restore the use-lists to the in-memory state when the bitcode was 3321 // written. We must defer until the Module has been fully materialized. 3322 3323 return M; 3324 } 3325 3326 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer, 3327 LLVMContext& Context, 3328 std::string *ErrMsg) { 3329 BitcodeReader *R = new BitcodeReader(Buffer, Context); 3330 // Don't let the BitcodeReader dtor delete 'Buffer'. 3331 R->setBufferOwned(false); 3332 3333 std::string Triple(""); 3334 if (error_code EC = R->ParseTriple(Triple)) 3335 if (ErrMsg) 3336 *ErrMsg = EC.message(); 3337 3338 delete R; 3339 return Triple; 3340 } 3341