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