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