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