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