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