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