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