1 //===- Instructions.cpp - Implement the LLVM instructions -----------------===// 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 // This file implements all of the non-inline methods for the LLVM instruction 11 // classes. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/IR/Instructions.h" 16 #include "LLVMContextImpl.h" 17 #include "llvm/ADT/None.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/Twine.h" 20 #include "llvm/IR/Attributes.h" 21 #include "llvm/IR/BasicBlock.h" 22 #include "llvm/IR/CallSite.h" 23 #include "llvm/IR/Constant.h" 24 #include "llvm/IR/Constants.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/InstrTypes.h" 29 #include "llvm/IR/Instruction.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/Operator.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/IR/Value.h" 36 #include "llvm/Support/AtomicOrdering.h" 37 #include "llvm/Support/Casting.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/MathExtras.h" 40 #include <algorithm> 41 #include <cassert> 42 #include <cstdint> 43 #include <vector> 44 45 using namespace llvm; 46 47 //===----------------------------------------------------------------------===// 48 // CallSite Class 49 //===----------------------------------------------------------------------===// 50 51 User::op_iterator CallSite::getCallee() const { 52 Instruction *II(getInstruction()); 53 return isCall() 54 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee 55 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee 56 } 57 58 //===----------------------------------------------------------------------===// 59 // TerminatorInst Class 60 //===----------------------------------------------------------------------===// 61 62 unsigned TerminatorInst::getNumSuccessors() const { 63 switch (getOpcode()) { 64 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 65 case Instruction::OPC: \ 66 return static_cast<const CLASS *>(this)->getNumSuccessors(); 67 #include "llvm/IR/Instruction.def" 68 default: 69 break; 70 } 71 llvm_unreachable("not a terminator"); 72 } 73 74 BasicBlock *TerminatorInst::getSuccessor(unsigned idx) const { 75 switch (getOpcode()) { 76 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 77 case Instruction::OPC: \ 78 return static_cast<const CLASS *>(this)->getSuccessor(idx); 79 #include "llvm/IR/Instruction.def" 80 default: 81 break; 82 } 83 llvm_unreachable("not a terminator"); 84 } 85 86 void TerminatorInst::setSuccessor(unsigned idx, BasicBlock *B) { 87 switch (getOpcode()) { 88 #define HANDLE_TERM_INST(N, OPC, CLASS) \ 89 case Instruction::OPC: \ 90 return static_cast<CLASS *>(this)->setSuccessor(idx, B); 91 #include "llvm/IR/Instruction.def" 92 default: 93 break; 94 } 95 llvm_unreachable("not a terminator"); 96 } 97 98 //===----------------------------------------------------------------------===// 99 // SelectInst Class 100 //===----------------------------------------------------------------------===// 101 102 /// areInvalidOperands - Return a string if the specified operands are invalid 103 /// for a select operation, otherwise return null. 104 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { 105 if (Op1->getType() != Op2->getType()) 106 return "both values to select must have same type"; 107 108 if (Op1->getType()->isTokenTy()) 109 return "select values cannot have token type"; 110 111 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) { 112 // Vector select. 113 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext())) 114 return "vector select condition element type must be i1"; 115 VectorType *ET = dyn_cast<VectorType>(Op1->getType()); 116 if (!ET) 117 return "selected values for vector select must be vectors"; 118 if (ET->getNumElements() != VT->getNumElements()) 119 return "vector select requires selected vectors to have " 120 "the same vector length as select condition"; 121 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) { 122 return "select condition must be i1 or <n x i1>"; 123 } 124 return nullptr; 125 } 126 127 //===----------------------------------------------------------------------===// 128 // PHINode Class 129 //===----------------------------------------------------------------------===// 130 131 PHINode::PHINode(const PHINode &PN) 132 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()), 133 ReservedSpace(PN.getNumOperands()) { 134 allocHungoffUses(PN.getNumOperands()); 135 std::copy(PN.op_begin(), PN.op_end(), op_begin()); 136 std::copy(PN.block_begin(), PN.block_end(), block_begin()); 137 SubclassOptionalData = PN.SubclassOptionalData; 138 } 139 140 // removeIncomingValue - Remove an incoming value. This is useful if a 141 // predecessor basic block is deleted. 142 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) { 143 Value *Removed = getIncomingValue(Idx); 144 145 // Move everything after this operand down. 146 // 147 // FIXME: we could just swap with the end of the list, then erase. However, 148 // clients might not expect this to happen. The code as it is thrashes the 149 // use/def lists, which is kinda lame. 150 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx); 151 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx); 152 153 // Nuke the last value. 154 Op<-1>().set(nullptr); 155 setNumHungOffUseOperands(getNumOperands() - 1); 156 157 // If the PHI node is dead, because it has zero entries, nuke it now. 158 if (getNumOperands() == 0 && DeletePHIIfEmpty) { 159 // If anyone is using this PHI, make them use a dummy value instead... 160 replaceAllUsesWith(UndefValue::get(getType())); 161 eraseFromParent(); 162 } 163 return Removed; 164 } 165 166 /// growOperands - grow operands - This grows the operand list in response 167 /// to a push_back style of operation. This grows the number of ops by 1.5 168 /// times. 169 /// 170 void PHINode::growOperands() { 171 unsigned e = getNumOperands(); 172 unsigned NumOps = e + e / 2; 173 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common. 174 175 ReservedSpace = NumOps; 176 growHungoffUses(ReservedSpace, /* IsPhi */ true); 177 } 178 179 /// hasConstantValue - If the specified PHI node always merges together the same 180 /// value, return the value, otherwise return null. 181 Value *PHINode::hasConstantValue() const { 182 // Exploit the fact that phi nodes always have at least one entry. 183 Value *ConstantValue = getIncomingValue(0); 184 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i) 185 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) { 186 if (ConstantValue != this) 187 return nullptr; // Incoming values not all the same. 188 // The case where the first value is this PHI. 189 ConstantValue = getIncomingValue(i); 190 } 191 if (ConstantValue == this) 192 return UndefValue::get(getType()); 193 return ConstantValue; 194 } 195 196 /// hasConstantOrUndefValue - Whether the specified PHI node always merges 197 /// together the same value, assuming that undefs result in the same value as 198 /// non-undefs. 199 /// Unlike \ref hasConstantValue, this does not return a value because the 200 /// unique non-undef incoming value need not dominate the PHI node. 201 bool PHINode::hasConstantOrUndefValue() const { 202 Value *ConstantValue = nullptr; 203 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) { 204 Value *Incoming = getIncomingValue(i); 205 if (Incoming != this && !isa<UndefValue>(Incoming)) { 206 if (ConstantValue && ConstantValue != Incoming) 207 return false; 208 ConstantValue = Incoming; 209 } 210 } 211 return true; 212 } 213 214 //===----------------------------------------------------------------------===// 215 // LandingPadInst Implementation 216 //===----------------------------------------------------------------------===// 217 218 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 219 const Twine &NameStr, Instruction *InsertBefore) 220 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) { 221 init(NumReservedValues, NameStr); 222 } 223 224 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues, 225 const Twine &NameStr, BasicBlock *InsertAtEnd) 226 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) { 227 init(NumReservedValues, NameStr); 228 } 229 230 LandingPadInst::LandingPadInst(const LandingPadInst &LP) 231 : Instruction(LP.getType(), Instruction::LandingPad, nullptr, 232 LP.getNumOperands()), 233 ReservedSpace(LP.getNumOperands()) { 234 allocHungoffUses(LP.getNumOperands()); 235 Use *OL = getOperandList(); 236 const Use *InOL = LP.getOperandList(); 237 for (unsigned I = 0, E = ReservedSpace; I != E; ++I) 238 OL[I] = InOL[I]; 239 240 setCleanup(LP.isCleanup()); 241 } 242 243 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 244 const Twine &NameStr, 245 Instruction *InsertBefore) { 246 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore); 247 } 248 249 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses, 250 const Twine &NameStr, 251 BasicBlock *InsertAtEnd) { 252 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd); 253 } 254 255 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) { 256 ReservedSpace = NumReservedValues; 257 setNumHungOffUseOperands(0); 258 allocHungoffUses(ReservedSpace); 259 setName(NameStr); 260 setCleanup(false); 261 } 262 263 /// growOperands - grow operands - This grows the operand list in response to a 264 /// push_back style of operation. This grows the number of ops by 2 times. 265 void LandingPadInst::growOperands(unsigned Size) { 266 unsigned e = getNumOperands(); 267 if (ReservedSpace >= e + Size) return; 268 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2; 269 growHungoffUses(ReservedSpace); 270 } 271 272 void LandingPadInst::addClause(Constant *Val) { 273 unsigned OpNo = getNumOperands(); 274 growOperands(1); 275 assert(OpNo < ReservedSpace && "Growing didn't work!"); 276 setNumHungOffUseOperands(getNumOperands() + 1); 277 getOperandList()[OpNo] = Val; 278 } 279 280 //===----------------------------------------------------------------------===// 281 // CallInst Implementation 282 //===----------------------------------------------------------------------===// 283 284 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args, 285 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) { 286 this->FTy = FTy; 287 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 && 288 "NumOperands not set up?"); 289 Op<-1>() = Func; 290 291 #ifndef NDEBUG 292 assert((Args.size() == FTy->getNumParams() || 293 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 294 "Calling a function with bad signature!"); 295 296 for (unsigned i = 0; i != Args.size(); ++i) 297 assert((i >= FTy->getNumParams() || 298 FTy->getParamType(i) == Args[i]->getType()) && 299 "Calling a function with a bad signature!"); 300 #endif 301 302 std::copy(Args.begin(), Args.end(), op_begin()); 303 304 auto It = populateBundleOperandInfos(Bundles, Args.size()); 305 (void)It; 306 assert(It + 1 == op_end() && "Should add up!"); 307 308 setName(NameStr); 309 } 310 311 void CallInst::init(Value *Func, const Twine &NameStr) { 312 FTy = 313 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); 314 assert(getNumOperands() == 1 && "NumOperands not set up?"); 315 Op<-1>() = Func; 316 317 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature"); 318 319 setName(NameStr); 320 } 321 322 CallInst::CallInst(Value *Func, const Twine &Name, 323 Instruction *InsertBefore) 324 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 325 ->getElementType())->getReturnType(), 326 Instruction::Call, 327 OperandTraits<CallInst>::op_end(this) - 1, 328 1, InsertBefore) { 329 init(Func, Name); 330 } 331 332 CallInst::CallInst(Value *Func, const Twine &Name, 333 BasicBlock *InsertAtEnd) 334 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 335 ->getElementType())->getReturnType(), 336 Instruction::Call, 337 OperandTraits<CallInst>::op_end(this) - 1, 338 1, InsertAtEnd) { 339 init(Func, Name); 340 } 341 342 CallInst::CallInst(const CallInst &CI) 343 : Instruction(CI.getType(), Instruction::Call, 344 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(), 345 CI.getNumOperands()), 346 Attrs(CI.Attrs), FTy(CI.FTy) { 347 setTailCallKind(CI.getTailCallKind()); 348 setCallingConv(CI.getCallingConv()); 349 350 std::copy(CI.op_begin(), CI.op_end(), op_begin()); 351 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(), 352 bundle_op_info_begin()); 353 SubclassOptionalData = CI.SubclassOptionalData; 354 } 355 356 CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB, 357 Instruction *InsertPt) { 358 std::vector<Value *> Args(CI->arg_begin(), CI->arg_end()); 359 360 auto *NewCI = CallInst::Create(CI->getCalledValue(), Args, OpB, CI->getName(), 361 InsertPt); 362 NewCI->setTailCallKind(CI->getTailCallKind()); 363 NewCI->setCallingConv(CI->getCallingConv()); 364 NewCI->SubclassOptionalData = CI->SubclassOptionalData; 365 NewCI->setAttributes(CI->getAttributes()); 366 NewCI->setDebugLoc(CI->getDebugLoc()); 367 return NewCI; 368 } 369 370 Value *CallInst::getReturnedArgOperand() const { 371 unsigned Index; 372 373 if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index) 374 return getArgOperand(Index - AttributeList::FirstArgIndex); 375 if (const Function *F = getCalledFunction()) 376 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) && 377 Index) 378 return getArgOperand(Index - AttributeList::FirstArgIndex); 379 380 return nullptr; 381 } 382 383 void CallInst::addAttribute(unsigned i, Attribute::AttrKind Kind) { 384 AttributeList PAL = getAttributes(); 385 PAL = PAL.addAttribute(getContext(), i, Kind); 386 setAttributes(PAL); 387 } 388 389 void CallInst::addAttribute(unsigned i, Attribute Attr) { 390 AttributeList PAL = getAttributes(); 391 PAL = PAL.addAttribute(getContext(), i, Attr); 392 setAttributes(PAL); 393 } 394 395 void CallInst::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 396 assert(ArgNo < getNumArgOperands() && "Out of bounds"); 397 AttributeList PAL = getAttributes(); 398 PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind); 399 setAttributes(PAL); 400 } 401 402 void CallInst::addParamAttr(unsigned ArgNo, Attribute Attr) { 403 assert(ArgNo < getNumArgOperands() && "Out of bounds"); 404 AttributeList PAL = getAttributes(); 405 PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr); 406 setAttributes(PAL); 407 } 408 409 void CallInst::removeAttribute(unsigned i, Attribute::AttrKind Kind) { 410 AttributeList PAL = getAttributes(); 411 PAL = PAL.removeAttribute(getContext(), i, Kind); 412 setAttributes(PAL); 413 } 414 415 void CallInst::removeAttribute(unsigned i, StringRef Kind) { 416 AttributeList PAL = getAttributes(); 417 PAL = PAL.removeAttribute(getContext(), i, Kind); 418 setAttributes(PAL); 419 } 420 421 void CallInst::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 422 assert(ArgNo < getNumArgOperands() && "Out of bounds"); 423 AttributeList PAL = getAttributes(); 424 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind); 425 setAttributes(PAL); 426 } 427 428 void CallInst::removeParamAttr(unsigned ArgNo, StringRef Kind) { 429 assert(ArgNo < getNumArgOperands() && "Out of bounds"); 430 AttributeList PAL = getAttributes(); 431 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind); 432 setAttributes(PAL); 433 } 434 435 void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) { 436 AttributeList PAL = getAttributes(); 437 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); 438 setAttributes(PAL); 439 } 440 441 void CallInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { 442 AttributeList PAL = getAttributes(); 443 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); 444 setAttributes(PAL); 445 } 446 447 bool CallInst::hasRetAttr(Attribute::AttrKind Kind) const { 448 if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind)) 449 return true; 450 451 // Look at the callee, if available. 452 if (const Function *F = getCalledFunction()) 453 return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind); 454 return false; 455 } 456 457 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind Kind) const { 458 assert(i < getNumArgOperands() && "Param index out of bounds!"); 459 460 if (Attrs.hasParamAttribute(i, Kind)) 461 return true; 462 if (const Function *F = getCalledFunction()) 463 return F->getAttributes().hasParamAttribute(i, Kind); 464 return false; 465 } 466 467 bool CallInst::dataOperandHasImpliedAttr(unsigned i, 468 Attribute::AttrKind Kind) const { 469 // There are getNumOperands() - 1 data operands. The last operand is the 470 // callee. 471 assert(i < getNumOperands() && "Data operand index out of bounds!"); 472 473 // The attribute A can either be directly specified, if the operand in 474 // question is a call argument; or be indirectly implied by the kind of its 475 // containing operand bundle, if the operand is a bundle operand. 476 477 if (i == AttributeList::ReturnIndex) 478 return hasRetAttr(Kind); 479 480 // FIXME: Avoid these i - 1 calculations and update the API to use zero-based 481 // indices. 482 if (i < (getNumArgOperands() + 1)) 483 return paramHasAttr(i - 1, Kind); 484 485 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) && 486 "Must be either a call argument or an operand bundle!"); 487 return bundleOperandHasAttr(i - 1, Kind); 488 } 489 490 /// IsConstantOne - Return true only if val is constant int 1 491 static bool IsConstantOne(Value *val) { 492 assert(val && "IsConstantOne does not work with nullptr val"); 493 const ConstantInt *CVal = dyn_cast<ConstantInt>(val); 494 return CVal && CVal->isOne(); 495 } 496 497 static Instruction *createMalloc(Instruction *InsertBefore, 498 BasicBlock *InsertAtEnd, Type *IntPtrTy, 499 Type *AllocTy, Value *AllocSize, 500 Value *ArraySize, 501 ArrayRef<OperandBundleDef> OpB, 502 Function *MallocF, const Twine &Name) { 503 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 504 "createMalloc needs either InsertBefore or InsertAtEnd"); 505 506 // malloc(type) becomes: 507 // bitcast (i8* malloc(typeSize)) to type* 508 // malloc(type, arraySize) becomes: 509 // bitcast (i8* malloc(typeSize*arraySize)) to type* 510 if (!ArraySize) 511 ArraySize = ConstantInt::get(IntPtrTy, 1); 512 else if (ArraySize->getType() != IntPtrTy) { 513 if (InsertBefore) 514 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, 515 "", InsertBefore); 516 else 517 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false, 518 "", InsertAtEnd); 519 } 520 521 if (!IsConstantOne(ArraySize)) { 522 if (IsConstantOne(AllocSize)) { 523 AllocSize = ArraySize; // Operand * 1 = Operand 524 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) { 525 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy, 526 false /*ZExt*/); 527 // Malloc arg is constant product of type size and array size 528 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize)); 529 } else { 530 // Multiply type size by the array size... 531 if (InsertBefore) 532 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 533 "mallocsize", InsertBefore); 534 else 535 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 536 "mallocsize", InsertAtEnd); 537 } 538 } 539 540 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size"); 541 // Create the call to Malloc. 542 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 543 Module *M = BB->getParent()->getParent(); 544 Type *BPTy = Type::getInt8PtrTy(BB->getContext()); 545 Value *MallocFunc = MallocF; 546 if (!MallocFunc) 547 // prototype malloc as "void *malloc(size_t)" 548 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy); 549 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy); 550 CallInst *MCall = nullptr; 551 Instruction *Result = nullptr; 552 if (InsertBefore) { 553 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall", 554 InsertBefore); 555 Result = MCall; 556 if (Result->getType() != AllocPtrType) 557 // Create a cast instruction to convert to the right type... 558 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore); 559 } else { 560 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall"); 561 Result = MCall; 562 if (Result->getType() != AllocPtrType) { 563 InsertAtEnd->getInstList().push_back(MCall); 564 // Create a cast instruction to convert to the right type... 565 Result = new BitCastInst(MCall, AllocPtrType, Name); 566 } 567 } 568 MCall->setTailCall(); 569 if (Function *F = dyn_cast<Function>(MallocFunc)) { 570 MCall->setCallingConv(F->getCallingConv()); 571 if (!F->returnDoesNotAlias()) 572 F->setReturnDoesNotAlias(); 573 } 574 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type"); 575 576 return Result; 577 } 578 579 /// CreateMalloc - Generate the IR for a call to malloc: 580 /// 1. Compute the malloc call's argument as the specified type's size, 581 /// possibly multiplied by the array size if the array size is not 582 /// constant 1. 583 /// 2. Call malloc with that argument. 584 /// 3. Bitcast the result of the malloc call to the specified type. 585 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, 586 Type *IntPtrTy, Type *AllocTy, 587 Value *AllocSize, Value *ArraySize, 588 Function *MallocF, 589 const Twine &Name) { 590 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, 591 ArraySize, None, MallocF, Name); 592 } 593 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore, 594 Type *IntPtrTy, Type *AllocTy, 595 Value *AllocSize, Value *ArraySize, 596 ArrayRef<OperandBundleDef> OpB, 597 Function *MallocF, 598 const Twine &Name) { 599 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize, 600 ArraySize, OpB, MallocF, Name); 601 } 602 603 /// CreateMalloc - Generate the IR for a call to malloc: 604 /// 1. Compute the malloc call's argument as the specified type's size, 605 /// possibly multiplied by the array size if the array size is not 606 /// constant 1. 607 /// 2. Call malloc with that argument. 608 /// 3. Bitcast the result of the malloc call to the specified type. 609 /// Note: This function does not add the bitcast to the basic block, that is the 610 /// responsibility of the caller. 611 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, 612 Type *IntPtrTy, Type *AllocTy, 613 Value *AllocSize, Value *ArraySize, 614 Function *MallocF, const Twine &Name) { 615 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, 616 ArraySize, None, MallocF, Name); 617 } 618 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, 619 Type *IntPtrTy, Type *AllocTy, 620 Value *AllocSize, Value *ArraySize, 621 ArrayRef<OperandBundleDef> OpB, 622 Function *MallocF, const Twine &Name) { 623 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize, 624 ArraySize, OpB, MallocF, Name); 625 } 626 627 static Instruction *createFree(Value *Source, 628 ArrayRef<OperandBundleDef> Bundles, 629 Instruction *InsertBefore, 630 BasicBlock *InsertAtEnd) { 631 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 632 "createFree needs either InsertBefore or InsertAtEnd"); 633 assert(Source->getType()->isPointerTy() && 634 "Can not free something of nonpointer type!"); 635 636 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 637 Module *M = BB->getParent()->getParent(); 638 639 Type *VoidTy = Type::getVoidTy(M->getContext()); 640 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext()); 641 // prototype free as "void free(void*)" 642 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy); 643 CallInst *Result = nullptr; 644 Value *PtrCast = Source; 645 if (InsertBefore) { 646 if (Source->getType() != IntPtrTy) 647 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore); 648 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore); 649 } else { 650 if (Source->getType() != IntPtrTy) 651 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd); 652 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, ""); 653 } 654 Result->setTailCall(); 655 if (Function *F = dyn_cast<Function>(FreeFunc)) 656 Result->setCallingConv(F->getCallingConv()); 657 658 return Result; 659 } 660 661 /// CreateFree - Generate the IR for a call to the builtin free function. 662 Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) { 663 return createFree(Source, None, InsertBefore, nullptr); 664 } 665 Instruction *CallInst::CreateFree(Value *Source, 666 ArrayRef<OperandBundleDef> Bundles, 667 Instruction *InsertBefore) { 668 return createFree(Source, Bundles, InsertBefore, nullptr); 669 } 670 671 /// CreateFree - Generate the IR for a call to the builtin free function. 672 /// Note: This function does not add the call to the basic block, that is the 673 /// responsibility of the caller. 674 Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) { 675 Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd); 676 assert(FreeCall && "CreateFree did not create a CallInst"); 677 return FreeCall; 678 } 679 Instruction *CallInst::CreateFree(Value *Source, 680 ArrayRef<OperandBundleDef> Bundles, 681 BasicBlock *InsertAtEnd) { 682 Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd); 683 assert(FreeCall && "CreateFree did not create a CallInst"); 684 return FreeCall; 685 } 686 687 //===----------------------------------------------------------------------===// 688 // InvokeInst Implementation 689 //===----------------------------------------------------------------------===// 690 691 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal, 692 BasicBlock *IfException, ArrayRef<Value *> Args, 693 ArrayRef<OperandBundleDef> Bundles, 694 const Twine &NameStr) { 695 this->FTy = FTy; 696 697 assert(getNumOperands() == 3 + Args.size() + CountBundleInputs(Bundles) && 698 "NumOperands not set up?"); 699 Op<-3>() = Fn; 700 Op<-2>() = IfNormal; 701 Op<-1>() = IfException; 702 703 #ifndef NDEBUG 704 assert(((Args.size() == FTy->getNumParams()) || 705 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) && 706 "Invoking a function with bad signature"); 707 708 for (unsigned i = 0, e = Args.size(); i != e; i++) 709 assert((i >= FTy->getNumParams() || 710 FTy->getParamType(i) == Args[i]->getType()) && 711 "Invoking a function with a bad signature!"); 712 #endif 713 714 std::copy(Args.begin(), Args.end(), op_begin()); 715 716 auto It = populateBundleOperandInfos(Bundles, Args.size()); 717 (void)It; 718 assert(It + 3 == op_end() && "Should add up!"); 719 720 setName(NameStr); 721 } 722 723 InvokeInst::InvokeInst(const InvokeInst &II) 724 : TerminatorInst(II.getType(), Instruction::Invoke, 725 OperandTraits<InvokeInst>::op_end(this) - 726 II.getNumOperands(), 727 II.getNumOperands()), 728 Attrs(II.Attrs), FTy(II.FTy) { 729 setCallingConv(II.getCallingConv()); 730 std::copy(II.op_begin(), II.op_end(), op_begin()); 731 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(), 732 bundle_op_info_begin()); 733 SubclassOptionalData = II.SubclassOptionalData; 734 } 735 736 InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB, 737 Instruction *InsertPt) { 738 std::vector<Value *> Args(II->arg_begin(), II->arg_end()); 739 740 auto *NewII = InvokeInst::Create(II->getCalledValue(), II->getNormalDest(), 741 II->getUnwindDest(), Args, OpB, 742 II->getName(), InsertPt); 743 NewII->setCallingConv(II->getCallingConv()); 744 NewII->SubclassOptionalData = II->SubclassOptionalData; 745 NewII->setAttributes(II->getAttributes()); 746 NewII->setDebugLoc(II->getDebugLoc()); 747 return NewII; 748 } 749 750 Value *InvokeInst::getReturnedArgOperand() const { 751 unsigned Index; 752 753 if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index) 754 return getArgOperand(Index - AttributeList::FirstArgIndex); 755 if (const Function *F = getCalledFunction()) 756 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) && 757 Index) 758 return getArgOperand(Index - AttributeList::FirstArgIndex); 759 760 return nullptr; 761 } 762 763 bool InvokeInst::hasRetAttr(Attribute::AttrKind Kind) const { 764 if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind)) 765 return true; 766 767 // Look at the callee, if available. 768 if (const Function *F = getCalledFunction()) 769 return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind); 770 return false; 771 } 772 773 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind Kind) const { 774 assert(i < getNumArgOperands() && "Param index out of bounds!"); 775 776 if (Attrs.hasParamAttribute(i, Kind)) 777 return true; 778 if (const Function *F = getCalledFunction()) 779 return F->getAttributes().hasParamAttribute(i, Kind); 780 return false; 781 } 782 783 bool InvokeInst::dataOperandHasImpliedAttr(unsigned i, 784 Attribute::AttrKind Kind) const { 785 // There are getNumOperands() - 3 data operands. The last three operands are 786 // the callee and the two successor basic blocks. 787 assert(i < (getNumOperands() - 2) && "Data operand index out of bounds!"); 788 789 // The attribute A can either be directly specified, if the operand in 790 // question is an invoke argument; or be indirectly implied by the kind of its 791 // containing operand bundle, if the operand is a bundle operand. 792 793 if (i == AttributeList::ReturnIndex) 794 return hasRetAttr(Kind); 795 796 // FIXME: Avoid these i - 1 calculations and update the API to use zero-based 797 // indices. 798 if (i < (getNumArgOperands() + 1)) 799 return paramHasAttr(i - 1, Kind); 800 801 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) && 802 "Must be either an invoke argument or an operand bundle!"); 803 return bundleOperandHasAttr(i - 1, Kind); 804 } 805 806 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind Kind) { 807 AttributeList PAL = getAttributes(); 808 PAL = PAL.addAttribute(getContext(), i, Kind); 809 setAttributes(PAL); 810 } 811 812 void InvokeInst::addAttribute(unsigned i, Attribute Attr) { 813 AttributeList PAL = getAttributes(); 814 PAL = PAL.addAttribute(getContext(), i, Attr); 815 setAttributes(PAL); 816 } 817 818 void InvokeInst::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 819 AttributeList PAL = getAttributes(); 820 PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind); 821 setAttributes(PAL); 822 } 823 824 void InvokeInst::removeAttribute(unsigned i, Attribute::AttrKind Kind) { 825 AttributeList PAL = getAttributes(); 826 PAL = PAL.removeAttribute(getContext(), i, Kind); 827 setAttributes(PAL); 828 } 829 830 void InvokeInst::removeAttribute(unsigned i, StringRef Kind) { 831 AttributeList PAL = getAttributes(); 832 PAL = PAL.removeAttribute(getContext(), i, Kind); 833 setAttributes(PAL); 834 } 835 836 void InvokeInst::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 837 AttributeList PAL = getAttributes(); 838 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind); 839 setAttributes(PAL); 840 } 841 842 void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) { 843 AttributeList PAL = getAttributes(); 844 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); 845 setAttributes(PAL); 846 } 847 848 void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { 849 AttributeList PAL = getAttributes(); 850 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); 851 setAttributes(PAL); 852 } 853 854 LandingPadInst *InvokeInst::getLandingPadInst() const { 855 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI()); 856 } 857 858 //===----------------------------------------------------------------------===// 859 // ReturnInst Implementation 860 //===----------------------------------------------------------------------===// 861 862 ReturnInst::ReturnInst(const ReturnInst &RI) 863 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret, 864 OperandTraits<ReturnInst>::op_end(this) - 865 RI.getNumOperands(), 866 RI.getNumOperands()) { 867 if (RI.getNumOperands()) 868 Op<0>() = RI.Op<0>(); 869 SubclassOptionalData = RI.SubclassOptionalData; 870 } 871 872 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore) 873 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret, 874 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 875 InsertBefore) { 876 if (retVal) 877 Op<0>() = retVal; 878 } 879 880 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd) 881 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret, 882 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 883 InsertAtEnd) { 884 if (retVal) 885 Op<0>() = retVal; 886 } 887 888 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 889 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret, 890 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) { 891 } 892 893 //===----------------------------------------------------------------------===// 894 // ResumeInst Implementation 895 //===----------------------------------------------------------------------===// 896 897 ResumeInst::ResumeInst(const ResumeInst &RI) 898 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume, 899 OperandTraits<ResumeInst>::op_begin(this), 1) { 900 Op<0>() = RI.Op<0>(); 901 } 902 903 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore) 904 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume, 905 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) { 906 Op<0>() = Exn; 907 } 908 909 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd) 910 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume, 911 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) { 912 Op<0>() = Exn; 913 } 914 915 //===----------------------------------------------------------------------===// 916 // CleanupReturnInst Implementation 917 //===----------------------------------------------------------------------===// 918 919 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI) 920 : TerminatorInst(CRI.getType(), Instruction::CleanupRet, 921 OperandTraits<CleanupReturnInst>::op_end(this) - 922 CRI.getNumOperands(), 923 CRI.getNumOperands()) { 924 setInstructionSubclassData(CRI.getSubclassDataFromInstruction()); 925 Op<0>() = CRI.Op<0>(); 926 if (CRI.hasUnwindDest()) 927 Op<1>() = CRI.Op<1>(); 928 } 929 930 void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) { 931 if (UnwindBB) 932 setInstructionSubclassData(getSubclassDataFromInstruction() | 1); 933 934 Op<0>() = CleanupPad; 935 if (UnwindBB) 936 Op<1>() = UnwindBB; 937 } 938 939 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, 940 unsigned Values, Instruction *InsertBefore) 941 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()), 942 Instruction::CleanupRet, 943 OperandTraits<CleanupReturnInst>::op_end(this) - Values, 944 Values, InsertBefore) { 945 init(CleanupPad, UnwindBB); 946 } 947 948 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB, 949 unsigned Values, BasicBlock *InsertAtEnd) 950 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()), 951 Instruction::CleanupRet, 952 OperandTraits<CleanupReturnInst>::op_end(this) - Values, 953 Values, InsertAtEnd) { 954 init(CleanupPad, UnwindBB); 955 } 956 957 //===----------------------------------------------------------------------===// 958 // CatchReturnInst Implementation 959 //===----------------------------------------------------------------------===// 960 void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) { 961 Op<0>() = CatchPad; 962 Op<1>() = BB; 963 } 964 965 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI) 966 : TerminatorInst(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet, 967 OperandTraits<CatchReturnInst>::op_begin(this), 2) { 968 Op<0>() = CRI.Op<0>(); 969 Op<1>() = CRI.Op<1>(); 970 } 971 972 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB, 973 Instruction *InsertBefore) 974 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, 975 OperandTraits<CatchReturnInst>::op_begin(this), 2, 976 InsertBefore) { 977 init(CatchPad, BB); 978 } 979 980 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB, 981 BasicBlock *InsertAtEnd) 982 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet, 983 OperandTraits<CatchReturnInst>::op_begin(this), 2, 984 InsertAtEnd) { 985 init(CatchPad, BB); 986 } 987 988 //===----------------------------------------------------------------------===// 989 // CatchSwitchInst Implementation 990 //===----------------------------------------------------------------------===// 991 992 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, 993 unsigned NumReservedValues, 994 const Twine &NameStr, 995 Instruction *InsertBefore) 996 : TerminatorInst(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0, 997 InsertBefore) { 998 if (UnwindDest) 999 ++NumReservedValues; 1000 init(ParentPad, UnwindDest, NumReservedValues + 1); 1001 setName(NameStr); 1002 } 1003 1004 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest, 1005 unsigned NumReservedValues, 1006 const Twine &NameStr, BasicBlock *InsertAtEnd) 1007 : TerminatorInst(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0, 1008 InsertAtEnd) { 1009 if (UnwindDest) 1010 ++NumReservedValues; 1011 init(ParentPad, UnwindDest, NumReservedValues + 1); 1012 setName(NameStr); 1013 } 1014 1015 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI) 1016 : TerminatorInst(CSI.getType(), Instruction::CatchSwitch, nullptr, 1017 CSI.getNumOperands()) { 1018 init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands()); 1019 setNumHungOffUseOperands(ReservedSpace); 1020 Use *OL = getOperandList(); 1021 const Use *InOL = CSI.getOperandList(); 1022 for (unsigned I = 1, E = ReservedSpace; I != E; ++I) 1023 OL[I] = InOL[I]; 1024 } 1025 1026 void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest, 1027 unsigned NumReservedValues) { 1028 assert(ParentPad && NumReservedValues); 1029 1030 ReservedSpace = NumReservedValues; 1031 setNumHungOffUseOperands(UnwindDest ? 2 : 1); 1032 allocHungoffUses(ReservedSpace); 1033 1034 Op<0>() = ParentPad; 1035 if (UnwindDest) { 1036 setInstructionSubclassData(getSubclassDataFromInstruction() | 1); 1037 setUnwindDest(UnwindDest); 1038 } 1039 } 1040 1041 /// growOperands - grow operands - This grows the operand list in response to a 1042 /// push_back style of operation. This grows the number of ops by 2 times. 1043 void CatchSwitchInst::growOperands(unsigned Size) { 1044 unsigned NumOperands = getNumOperands(); 1045 assert(NumOperands >= 1); 1046 if (ReservedSpace >= NumOperands + Size) 1047 return; 1048 ReservedSpace = (NumOperands + Size / 2) * 2; 1049 growHungoffUses(ReservedSpace); 1050 } 1051 1052 void CatchSwitchInst::addHandler(BasicBlock *Handler) { 1053 unsigned OpNo = getNumOperands(); 1054 growOperands(1); 1055 assert(OpNo < ReservedSpace && "Growing didn't work!"); 1056 setNumHungOffUseOperands(getNumOperands() + 1); 1057 getOperandList()[OpNo] = Handler; 1058 } 1059 1060 void CatchSwitchInst::removeHandler(handler_iterator HI) { 1061 // Move all subsequent handlers up one. 1062 Use *EndDst = op_end() - 1; 1063 for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst) 1064 *CurDst = *(CurDst + 1); 1065 // Null out the last handler use. 1066 *EndDst = nullptr; 1067 1068 setNumHungOffUseOperands(getNumOperands() - 1); 1069 } 1070 1071 //===----------------------------------------------------------------------===// 1072 // FuncletPadInst Implementation 1073 //===----------------------------------------------------------------------===// 1074 void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args, 1075 const Twine &NameStr) { 1076 assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?"); 1077 std::copy(Args.begin(), Args.end(), op_begin()); 1078 setParentPad(ParentPad); 1079 setName(NameStr); 1080 } 1081 1082 FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI) 1083 : Instruction(FPI.getType(), FPI.getOpcode(), 1084 OperandTraits<FuncletPadInst>::op_end(this) - 1085 FPI.getNumOperands(), 1086 FPI.getNumOperands()) { 1087 std::copy(FPI.op_begin(), FPI.op_end(), op_begin()); 1088 setParentPad(FPI.getParentPad()); 1089 } 1090 1091 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 1092 ArrayRef<Value *> Args, unsigned Values, 1093 const Twine &NameStr, Instruction *InsertBefore) 1094 : Instruction(ParentPad->getType(), Op, 1095 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values, 1096 InsertBefore) { 1097 init(ParentPad, Args, NameStr); 1098 } 1099 1100 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad, 1101 ArrayRef<Value *> Args, unsigned Values, 1102 const Twine &NameStr, BasicBlock *InsertAtEnd) 1103 : Instruction(ParentPad->getType(), Op, 1104 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values, 1105 InsertAtEnd) { 1106 init(ParentPad, Args, NameStr); 1107 } 1108 1109 //===----------------------------------------------------------------------===// 1110 // UnreachableInst Implementation 1111 //===----------------------------------------------------------------------===// 1112 1113 UnreachableInst::UnreachableInst(LLVMContext &Context, 1114 Instruction *InsertBefore) 1115 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable, 1116 nullptr, 0, InsertBefore) { 1117 } 1118 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 1119 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable, 1120 nullptr, 0, InsertAtEnd) { 1121 } 1122 1123 //===----------------------------------------------------------------------===// 1124 // BranchInst Implementation 1125 //===----------------------------------------------------------------------===// 1126 1127 void BranchInst::AssertOK() { 1128 if (isConditional()) 1129 assert(getCondition()->getType()->isIntegerTy(1) && 1130 "May only branch on boolean predicates!"); 1131 } 1132 1133 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore) 1134 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1135 OperandTraits<BranchInst>::op_end(this) - 1, 1136 1, InsertBefore) { 1137 assert(IfTrue && "Branch destination may not be null!"); 1138 Op<-1>() = IfTrue; 1139 } 1140 1141 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 1142 Instruction *InsertBefore) 1143 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1144 OperandTraits<BranchInst>::op_end(this) - 3, 1145 3, InsertBefore) { 1146 Op<-1>() = IfTrue; 1147 Op<-2>() = IfFalse; 1148 Op<-3>() = Cond; 1149 #ifndef NDEBUG 1150 AssertOK(); 1151 #endif 1152 } 1153 1154 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) 1155 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1156 OperandTraits<BranchInst>::op_end(this) - 1, 1157 1, InsertAtEnd) { 1158 assert(IfTrue && "Branch destination may not be null!"); 1159 Op<-1>() = IfTrue; 1160 } 1161 1162 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 1163 BasicBlock *InsertAtEnd) 1164 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 1165 OperandTraits<BranchInst>::op_end(this) - 3, 1166 3, InsertAtEnd) { 1167 Op<-1>() = IfTrue; 1168 Op<-2>() = IfFalse; 1169 Op<-3>() = Cond; 1170 #ifndef NDEBUG 1171 AssertOK(); 1172 #endif 1173 } 1174 1175 BranchInst::BranchInst(const BranchInst &BI) : 1176 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br, 1177 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(), 1178 BI.getNumOperands()) { 1179 Op<-1>() = BI.Op<-1>(); 1180 if (BI.getNumOperands() != 1) { 1181 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!"); 1182 Op<-3>() = BI.Op<-3>(); 1183 Op<-2>() = BI.Op<-2>(); 1184 } 1185 SubclassOptionalData = BI.SubclassOptionalData; 1186 } 1187 1188 void BranchInst::swapSuccessors() { 1189 assert(isConditional() && 1190 "Cannot swap successors of an unconditional branch"); 1191 Op<-1>().swap(Op<-2>()); 1192 1193 // Update profile metadata if present and it matches our structural 1194 // expectations. 1195 swapProfMetadata(); 1196 } 1197 1198 //===----------------------------------------------------------------------===// 1199 // AllocaInst Implementation 1200 //===----------------------------------------------------------------------===// 1201 1202 static Value *getAISize(LLVMContext &Context, Value *Amt) { 1203 if (!Amt) 1204 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1); 1205 else { 1206 assert(!isa<BasicBlock>(Amt) && 1207 "Passed basic block into allocation size parameter! Use other ctor"); 1208 assert(Amt->getType()->isIntegerTy() && 1209 "Allocation array size is not an integer!"); 1210 } 1211 return Amt; 1212 } 1213 1214 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, 1215 Instruction *InsertBefore) 1216 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {} 1217 1218 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name, 1219 BasicBlock *InsertAtEnd) 1220 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {} 1221 1222 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1223 const Twine &Name, Instruction *InsertBefore) 1224 : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/0, Name, InsertBefore) {} 1225 1226 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1227 const Twine &Name, BasicBlock *InsertAtEnd) 1228 : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/0, Name, InsertAtEnd) {} 1229 1230 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1231 unsigned Align, const Twine &Name, 1232 Instruction *InsertBefore) 1233 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, 1234 getAISize(Ty->getContext(), ArraySize), InsertBefore), 1235 AllocatedType(Ty) { 1236 setAlignment(Align); 1237 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1238 setName(Name); 1239 } 1240 1241 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, 1242 unsigned Align, const Twine &Name, 1243 BasicBlock *InsertAtEnd) 1244 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca, 1245 getAISize(Ty->getContext(), ArraySize), InsertAtEnd), 1246 AllocatedType(Ty) { 1247 setAlignment(Align); 1248 assert(!Ty->isVoidTy() && "Cannot allocate void!"); 1249 setName(Name); 1250 } 1251 1252 void AllocaInst::setAlignment(unsigned Align) { 1253 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1254 assert(Align <= MaximumAlignment && 1255 "Alignment is greater than MaximumAlignment!"); 1256 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) | 1257 (Log2_32(Align) + 1)); 1258 assert(getAlignment() == Align && "Alignment representation error!"); 1259 } 1260 1261 bool AllocaInst::isArrayAllocation() const { 1262 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0))) 1263 return !CI->isOne(); 1264 return true; 1265 } 1266 1267 /// isStaticAlloca - Return true if this alloca is in the entry block of the 1268 /// function and is a constant size. If so, the code generator will fold it 1269 /// into the prolog/epilog code, so it is basically free. 1270 bool AllocaInst::isStaticAlloca() const { 1271 // Must be constant size. 1272 if (!isa<ConstantInt>(getArraySize())) return false; 1273 1274 // Must be in the entry block. 1275 const BasicBlock *Parent = getParent(); 1276 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca(); 1277 } 1278 1279 //===----------------------------------------------------------------------===// 1280 // LoadInst Implementation 1281 //===----------------------------------------------------------------------===// 1282 1283 void LoadInst::AssertOK() { 1284 assert(getOperand(0)->getType()->isPointerTy() && 1285 "Ptr must have pointer type."); 1286 assert(!(isAtomic() && getAlignment() == 0) && 1287 "Alignment required for atomic load"); 1288 } 1289 1290 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef) 1291 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {} 1292 1293 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE) 1294 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {} 1295 1296 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1297 Instruction *InsertBef) 1298 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {} 1299 1300 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 1301 BasicBlock *InsertAE) 1302 : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {} 1303 1304 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1305 unsigned Align, Instruction *InsertBef) 1306 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, 1307 CrossThread, InsertBef) {} 1308 1309 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 1310 unsigned Align, BasicBlock *InsertAE) 1311 : LoadInst(Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic, 1312 CrossThread, InsertAE) {} 1313 1314 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile, 1315 unsigned Align, AtomicOrdering Order, 1316 SynchronizationScope SynchScope, Instruction *InsertBef) 1317 : UnaryInstruction(Ty, Load, Ptr, InsertBef) { 1318 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); 1319 setVolatile(isVolatile); 1320 setAlignment(Align); 1321 setAtomic(Order, SynchScope); 1322 AssertOK(); 1323 setName(Name); 1324 } 1325 1326 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 1327 unsigned Align, AtomicOrdering Order, 1328 SynchronizationScope SynchScope, 1329 BasicBlock *InsertAE) 1330 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1331 Load, Ptr, InsertAE) { 1332 setVolatile(isVolatile); 1333 setAlignment(Align); 1334 setAtomic(Order, SynchScope); 1335 AssertOK(); 1336 setName(Name); 1337 } 1338 1339 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef) 1340 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1341 Load, Ptr, InsertBef) { 1342 setVolatile(false); 1343 setAlignment(0); 1344 setAtomic(AtomicOrdering::NotAtomic); 1345 AssertOK(); 1346 if (Name && Name[0]) setName(Name); 1347 } 1348 1349 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE) 1350 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1351 Load, Ptr, InsertAE) { 1352 setVolatile(false); 1353 setAlignment(0); 1354 setAtomic(AtomicOrdering::NotAtomic); 1355 AssertOK(); 1356 if (Name && Name[0]) setName(Name); 1357 } 1358 1359 LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile, 1360 Instruction *InsertBef) 1361 : UnaryInstruction(Ty, Load, Ptr, InsertBef) { 1362 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType()); 1363 setVolatile(isVolatile); 1364 setAlignment(0); 1365 setAtomic(AtomicOrdering::NotAtomic); 1366 AssertOK(); 1367 if (Name && Name[0]) setName(Name); 1368 } 1369 1370 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile, 1371 BasicBlock *InsertAE) 1372 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1373 Load, Ptr, InsertAE) { 1374 setVolatile(isVolatile); 1375 setAlignment(0); 1376 setAtomic(AtomicOrdering::NotAtomic); 1377 AssertOK(); 1378 if (Name && Name[0]) setName(Name); 1379 } 1380 1381 void LoadInst::setAlignment(unsigned Align) { 1382 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1383 assert(Align <= MaximumAlignment && 1384 "Alignment is greater than MaximumAlignment!"); 1385 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | 1386 ((Log2_32(Align)+1)<<1)); 1387 assert(getAlignment() == Align && "Alignment representation error!"); 1388 } 1389 1390 //===----------------------------------------------------------------------===// 1391 // StoreInst Implementation 1392 //===----------------------------------------------------------------------===// 1393 1394 void StoreInst::AssertOK() { 1395 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!"); 1396 assert(getOperand(1)->getType()->isPointerTy() && 1397 "Ptr must have pointer type!"); 1398 assert(getOperand(0)->getType() == 1399 cast<PointerType>(getOperand(1)->getType())->getElementType() 1400 && "Ptr must be a pointer to Val type!"); 1401 assert(!(isAtomic() && getAlignment() == 0) && 1402 "Alignment required for atomic store"); 1403 } 1404 1405 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore) 1406 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {} 1407 1408 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd) 1409 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {} 1410 1411 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1412 Instruction *InsertBefore) 1413 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {} 1414 1415 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1416 BasicBlock *InsertAtEnd) 1417 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {} 1418 1419 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align, 1420 Instruction *InsertBefore) 1421 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, 1422 CrossThread, InsertBefore) {} 1423 1424 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align, 1425 BasicBlock *InsertAtEnd) 1426 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic, 1427 CrossThread, InsertAtEnd) {} 1428 1429 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1430 unsigned Align, AtomicOrdering Order, 1431 SynchronizationScope SynchScope, 1432 Instruction *InsertBefore) 1433 : Instruction(Type::getVoidTy(val->getContext()), Store, 1434 OperandTraits<StoreInst>::op_begin(this), 1435 OperandTraits<StoreInst>::operands(this), 1436 InsertBefore) { 1437 Op<0>() = val; 1438 Op<1>() = addr; 1439 setVolatile(isVolatile); 1440 setAlignment(Align); 1441 setAtomic(Order, SynchScope); 1442 AssertOK(); 1443 } 1444 1445 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1446 unsigned Align, AtomicOrdering Order, 1447 SynchronizationScope SynchScope, 1448 BasicBlock *InsertAtEnd) 1449 : Instruction(Type::getVoidTy(val->getContext()), Store, 1450 OperandTraits<StoreInst>::op_begin(this), 1451 OperandTraits<StoreInst>::operands(this), 1452 InsertAtEnd) { 1453 Op<0>() = val; 1454 Op<1>() = addr; 1455 setVolatile(isVolatile); 1456 setAlignment(Align); 1457 setAtomic(Order, SynchScope); 1458 AssertOK(); 1459 } 1460 1461 void StoreInst::setAlignment(unsigned Align) { 1462 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1463 assert(Align <= MaximumAlignment && 1464 "Alignment is greater than MaximumAlignment!"); 1465 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) | 1466 ((Log2_32(Align)+1) << 1)); 1467 assert(getAlignment() == Align && "Alignment representation error!"); 1468 } 1469 1470 //===----------------------------------------------------------------------===// 1471 // AtomicCmpXchgInst Implementation 1472 //===----------------------------------------------------------------------===// 1473 1474 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal, 1475 AtomicOrdering SuccessOrdering, 1476 AtomicOrdering FailureOrdering, 1477 SynchronizationScope SynchScope) { 1478 Op<0>() = Ptr; 1479 Op<1>() = Cmp; 1480 Op<2>() = NewVal; 1481 setSuccessOrdering(SuccessOrdering); 1482 setFailureOrdering(FailureOrdering); 1483 setSynchScope(SynchScope); 1484 1485 assert(getOperand(0) && getOperand(1) && getOperand(2) && 1486 "All operands must be non-null!"); 1487 assert(getOperand(0)->getType()->isPointerTy() && 1488 "Ptr must have pointer type!"); 1489 assert(getOperand(1)->getType() == 1490 cast<PointerType>(getOperand(0)->getType())->getElementType() 1491 && "Ptr must be a pointer to Cmp type!"); 1492 assert(getOperand(2)->getType() == 1493 cast<PointerType>(getOperand(0)->getType())->getElementType() 1494 && "Ptr must be a pointer to NewVal type!"); 1495 assert(SuccessOrdering != AtomicOrdering::NotAtomic && 1496 "AtomicCmpXchg instructions must be atomic!"); 1497 assert(FailureOrdering != AtomicOrdering::NotAtomic && 1498 "AtomicCmpXchg instructions must be atomic!"); 1499 assert(!isStrongerThan(FailureOrdering, SuccessOrdering) && 1500 "AtomicCmpXchg failure argument shall be no stronger than the success " 1501 "argument"); 1502 assert(FailureOrdering != AtomicOrdering::Release && 1503 FailureOrdering != AtomicOrdering::AcquireRelease && 1504 "AtomicCmpXchg failure ordering cannot include release semantics"); 1505 } 1506 1507 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1508 AtomicOrdering SuccessOrdering, 1509 AtomicOrdering FailureOrdering, 1510 SynchronizationScope SynchScope, 1511 Instruction *InsertBefore) 1512 : Instruction( 1513 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), 1514 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1515 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) { 1516 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope); 1517 } 1518 1519 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal, 1520 AtomicOrdering SuccessOrdering, 1521 AtomicOrdering FailureOrdering, 1522 SynchronizationScope SynchScope, 1523 BasicBlock *InsertAtEnd) 1524 : Instruction( 1525 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())), 1526 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this), 1527 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) { 1528 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope); 1529 } 1530 1531 //===----------------------------------------------------------------------===// 1532 // AtomicRMWInst Implementation 1533 //===----------------------------------------------------------------------===// 1534 1535 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val, 1536 AtomicOrdering Ordering, 1537 SynchronizationScope SynchScope) { 1538 Op<0>() = Ptr; 1539 Op<1>() = Val; 1540 setOperation(Operation); 1541 setOrdering(Ordering); 1542 setSynchScope(SynchScope); 1543 1544 assert(getOperand(0) && getOperand(1) && 1545 "All operands must be non-null!"); 1546 assert(getOperand(0)->getType()->isPointerTy() && 1547 "Ptr must have pointer type!"); 1548 assert(getOperand(1)->getType() == 1549 cast<PointerType>(getOperand(0)->getType())->getElementType() 1550 && "Ptr must be a pointer to Val type!"); 1551 assert(Ordering != AtomicOrdering::NotAtomic && 1552 "AtomicRMW instructions must be atomic!"); 1553 } 1554 1555 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1556 AtomicOrdering Ordering, 1557 SynchronizationScope SynchScope, 1558 Instruction *InsertBefore) 1559 : Instruction(Val->getType(), AtomicRMW, 1560 OperandTraits<AtomicRMWInst>::op_begin(this), 1561 OperandTraits<AtomicRMWInst>::operands(this), 1562 InsertBefore) { 1563 Init(Operation, Ptr, Val, Ordering, SynchScope); 1564 } 1565 1566 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val, 1567 AtomicOrdering Ordering, 1568 SynchronizationScope SynchScope, 1569 BasicBlock *InsertAtEnd) 1570 : Instruction(Val->getType(), AtomicRMW, 1571 OperandTraits<AtomicRMWInst>::op_begin(this), 1572 OperandTraits<AtomicRMWInst>::operands(this), 1573 InsertAtEnd) { 1574 Init(Operation, Ptr, Val, Ordering, SynchScope); 1575 } 1576 1577 //===----------------------------------------------------------------------===// 1578 // FenceInst Implementation 1579 //===----------------------------------------------------------------------===// 1580 1581 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1582 SynchronizationScope SynchScope, 1583 Instruction *InsertBefore) 1584 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) { 1585 setOrdering(Ordering); 1586 setSynchScope(SynchScope); 1587 } 1588 1589 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 1590 SynchronizationScope SynchScope, 1591 BasicBlock *InsertAtEnd) 1592 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) { 1593 setOrdering(Ordering); 1594 setSynchScope(SynchScope); 1595 } 1596 1597 //===----------------------------------------------------------------------===// 1598 // GetElementPtrInst Implementation 1599 //===----------------------------------------------------------------------===// 1600 1601 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList, 1602 const Twine &Name) { 1603 assert(getNumOperands() == 1 + IdxList.size() && 1604 "NumOperands not initialized?"); 1605 Op<0>() = Ptr; 1606 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1); 1607 setName(Name); 1608 } 1609 1610 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI) 1611 : Instruction(GEPI.getType(), GetElementPtr, 1612 OperandTraits<GetElementPtrInst>::op_end(this) - 1613 GEPI.getNumOperands(), 1614 GEPI.getNumOperands()), 1615 SourceElementType(GEPI.SourceElementType), 1616 ResultElementType(GEPI.ResultElementType) { 1617 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin()); 1618 SubclassOptionalData = GEPI.SubclassOptionalData; 1619 } 1620 1621 /// getIndexedType - Returns the type of the element that would be accessed with 1622 /// a gep instruction with the specified parameters. 1623 /// 1624 /// The Idxs pointer should point to a continuous piece of memory containing the 1625 /// indices, either as Value* or uint64_t. 1626 /// 1627 /// A null type is returned if the indices are invalid for the specified 1628 /// pointer type. 1629 /// 1630 template <typename IndexTy> 1631 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) { 1632 // Handle the special case of the empty set index set, which is always valid. 1633 if (IdxList.empty()) 1634 return Agg; 1635 1636 // If there is at least one index, the top level type must be sized, otherwise 1637 // it cannot be 'stepped over'. 1638 if (!Agg->isSized()) 1639 return nullptr; 1640 1641 unsigned CurIdx = 1; 1642 for (; CurIdx != IdxList.size(); ++CurIdx) { 1643 CompositeType *CT = dyn_cast<CompositeType>(Agg); 1644 if (!CT || CT->isPointerTy()) return nullptr; 1645 IndexTy Index = IdxList[CurIdx]; 1646 if (!CT->indexValid(Index)) return nullptr; 1647 Agg = CT->getTypeAtIndex(Index); 1648 } 1649 return CurIdx == IdxList.size() ? Agg : nullptr; 1650 } 1651 1652 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) { 1653 return getIndexedTypeInternal(Ty, IdxList); 1654 } 1655 1656 Type *GetElementPtrInst::getIndexedType(Type *Ty, 1657 ArrayRef<Constant *> IdxList) { 1658 return getIndexedTypeInternal(Ty, IdxList); 1659 } 1660 1661 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) { 1662 return getIndexedTypeInternal(Ty, IdxList); 1663 } 1664 1665 /// hasAllZeroIndices - Return true if all of the indices of this GEP are 1666 /// zeros. If so, the result pointer and the first operand have the same 1667 /// value, just potentially different types. 1668 bool GetElementPtrInst::hasAllZeroIndices() const { 1669 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1670 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) { 1671 if (!CI->isZero()) return false; 1672 } else { 1673 return false; 1674 } 1675 } 1676 return true; 1677 } 1678 1679 /// hasAllConstantIndices - Return true if all of the indices of this GEP are 1680 /// constant integers. If so, the result pointer and the first operand have 1681 /// a constant offset between them. 1682 bool GetElementPtrInst::hasAllConstantIndices() const { 1683 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1684 if (!isa<ConstantInt>(getOperand(i))) 1685 return false; 1686 } 1687 return true; 1688 } 1689 1690 void GetElementPtrInst::setIsInBounds(bool B) { 1691 cast<GEPOperator>(this)->setIsInBounds(B); 1692 } 1693 1694 bool GetElementPtrInst::isInBounds() const { 1695 return cast<GEPOperator>(this)->isInBounds(); 1696 } 1697 1698 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL, 1699 APInt &Offset) const { 1700 // Delegate to the generic GEPOperator implementation. 1701 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset); 1702 } 1703 1704 //===----------------------------------------------------------------------===// 1705 // ExtractElementInst Implementation 1706 //===----------------------------------------------------------------------===// 1707 1708 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1709 const Twine &Name, 1710 Instruction *InsertBef) 1711 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1712 ExtractElement, 1713 OperandTraits<ExtractElementInst>::op_begin(this), 1714 2, InsertBef) { 1715 assert(isValidOperands(Val, Index) && 1716 "Invalid extractelement instruction operands!"); 1717 Op<0>() = Val; 1718 Op<1>() = Index; 1719 setName(Name); 1720 } 1721 1722 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1723 const Twine &Name, 1724 BasicBlock *InsertAE) 1725 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1726 ExtractElement, 1727 OperandTraits<ExtractElementInst>::op_begin(this), 1728 2, InsertAE) { 1729 assert(isValidOperands(Val, Index) && 1730 "Invalid extractelement instruction operands!"); 1731 1732 Op<0>() = Val; 1733 Op<1>() = Index; 1734 setName(Name); 1735 } 1736 1737 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { 1738 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy()) 1739 return false; 1740 return true; 1741 } 1742 1743 //===----------------------------------------------------------------------===// 1744 // InsertElementInst Implementation 1745 //===----------------------------------------------------------------------===// 1746 1747 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1748 const Twine &Name, 1749 Instruction *InsertBef) 1750 : Instruction(Vec->getType(), InsertElement, 1751 OperandTraits<InsertElementInst>::op_begin(this), 1752 3, InsertBef) { 1753 assert(isValidOperands(Vec, Elt, Index) && 1754 "Invalid insertelement instruction operands!"); 1755 Op<0>() = Vec; 1756 Op<1>() = Elt; 1757 Op<2>() = Index; 1758 setName(Name); 1759 } 1760 1761 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1762 const Twine &Name, 1763 BasicBlock *InsertAE) 1764 : Instruction(Vec->getType(), InsertElement, 1765 OperandTraits<InsertElementInst>::op_begin(this), 1766 3, InsertAE) { 1767 assert(isValidOperands(Vec, Elt, Index) && 1768 "Invalid insertelement instruction operands!"); 1769 1770 Op<0>() = Vec; 1771 Op<1>() = Elt; 1772 Op<2>() = Index; 1773 setName(Name); 1774 } 1775 1776 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 1777 const Value *Index) { 1778 if (!Vec->getType()->isVectorTy()) 1779 return false; // First operand of insertelement must be vector type. 1780 1781 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType()) 1782 return false;// Second operand of insertelement must be vector element type. 1783 1784 if (!Index->getType()->isIntegerTy()) 1785 return false; // Third operand of insertelement must be i32. 1786 return true; 1787 } 1788 1789 //===----------------------------------------------------------------------===// 1790 // ShuffleVectorInst Implementation 1791 //===----------------------------------------------------------------------===// 1792 1793 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1794 const Twine &Name, 1795 Instruction *InsertBefore) 1796 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1797 cast<VectorType>(Mask->getType())->getNumElements()), 1798 ShuffleVector, 1799 OperandTraits<ShuffleVectorInst>::op_begin(this), 1800 OperandTraits<ShuffleVectorInst>::operands(this), 1801 InsertBefore) { 1802 assert(isValidOperands(V1, V2, Mask) && 1803 "Invalid shuffle vector instruction operands!"); 1804 Op<0>() = V1; 1805 Op<1>() = V2; 1806 Op<2>() = Mask; 1807 setName(Name); 1808 } 1809 1810 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1811 const Twine &Name, 1812 BasicBlock *InsertAtEnd) 1813 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1814 cast<VectorType>(Mask->getType())->getNumElements()), 1815 ShuffleVector, 1816 OperandTraits<ShuffleVectorInst>::op_begin(this), 1817 OperandTraits<ShuffleVectorInst>::operands(this), 1818 InsertAtEnd) { 1819 assert(isValidOperands(V1, V2, Mask) && 1820 "Invalid shuffle vector instruction operands!"); 1821 1822 Op<0>() = V1; 1823 Op<1>() = V2; 1824 Op<2>() = Mask; 1825 setName(Name); 1826 } 1827 1828 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 1829 const Value *Mask) { 1830 // V1 and V2 must be vectors of the same type. 1831 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType()) 1832 return false; 1833 1834 // Mask must be vector of i32. 1835 auto *MaskTy = dyn_cast<VectorType>(Mask->getType()); 1836 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32)) 1837 return false; 1838 1839 // Check to see if Mask is valid. 1840 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask)) 1841 return true; 1842 1843 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) { 1844 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); 1845 for (Value *Op : MV->operands()) { 1846 if (auto *CI = dyn_cast<ConstantInt>(Op)) { 1847 if (CI->uge(V1Size*2)) 1848 return false; 1849 } else if (!isa<UndefValue>(Op)) { 1850 return false; 1851 } 1852 } 1853 return true; 1854 } 1855 1856 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { 1857 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements(); 1858 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i) 1859 if (CDS->getElementAsInteger(i) >= V1Size*2) 1860 return false; 1861 return true; 1862 } 1863 1864 // The bitcode reader can create a place holder for a forward reference 1865 // used as the shuffle mask. When this occurs, the shuffle mask will 1866 // fall into this case and fail. To avoid this error, do this bit of 1867 // ugliness to allow such a mask pass. 1868 if (const auto *CE = dyn_cast<ConstantExpr>(Mask)) 1869 if (CE->getOpcode() == Instruction::UserOp1) 1870 return true; 1871 1872 return false; 1873 } 1874 1875 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) { 1876 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range"); 1877 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) 1878 return CDS->getElementAsInteger(i); 1879 Constant *C = Mask->getAggregateElement(i); 1880 if (isa<UndefValue>(C)) 1881 return -1; 1882 return cast<ConstantInt>(C)->getZExtValue(); 1883 } 1884 1885 void ShuffleVectorInst::getShuffleMask(Constant *Mask, 1886 SmallVectorImpl<int> &Result) { 1887 unsigned NumElts = Mask->getType()->getVectorNumElements(); 1888 1889 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) { 1890 for (unsigned i = 0; i != NumElts; ++i) 1891 Result.push_back(CDS->getElementAsInteger(i)); 1892 return; 1893 } 1894 for (unsigned i = 0; i != NumElts; ++i) { 1895 Constant *C = Mask->getAggregateElement(i); 1896 Result.push_back(isa<UndefValue>(C) ? -1 : 1897 cast<ConstantInt>(C)->getZExtValue()); 1898 } 1899 } 1900 1901 //===----------------------------------------------------------------------===// 1902 // InsertValueInst Class 1903 //===----------------------------------------------------------------------===// 1904 1905 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 1906 const Twine &Name) { 1907 assert(getNumOperands() == 2 && "NumOperands not initialized?"); 1908 1909 // There's no fundamental reason why we require at least one index 1910 // (other than weirdness with &*IdxBegin being invalid; see 1911 // getelementptr's init routine for example). But there's no 1912 // present need to support it. 1913 assert(!Idxs.empty() && "InsertValueInst must have at least one index"); 1914 1915 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) == 1916 Val->getType() && "Inserted value must match indexed type!"); 1917 Op<0>() = Agg; 1918 Op<1>() = Val; 1919 1920 Indices.append(Idxs.begin(), Idxs.end()); 1921 setName(Name); 1922 } 1923 1924 InsertValueInst::InsertValueInst(const InsertValueInst &IVI) 1925 : Instruction(IVI.getType(), InsertValue, 1926 OperandTraits<InsertValueInst>::op_begin(this), 2), 1927 Indices(IVI.Indices) { 1928 Op<0>() = IVI.getOperand(0); 1929 Op<1>() = IVI.getOperand(1); 1930 SubclassOptionalData = IVI.SubclassOptionalData; 1931 } 1932 1933 //===----------------------------------------------------------------------===// 1934 // ExtractValueInst Class 1935 //===----------------------------------------------------------------------===// 1936 1937 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) { 1938 assert(getNumOperands() == 1 && "NumOperands not initialized?"); 1939 1940 // There's no fundamental reason why we require at least one index. 1941 // But there's no present need to support it. 1942 assert(!Idxs.empty() && "ExtractValueInst must have at least one index"); 1943 1944 Indices.append(Idxs.begin(), Idxs.end()); 1945 setName(Name); 1946 } 1947 1948 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI) 1949 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)), 1950 Indices(EVI.Indices) { 1951 SubclassOptionalData = EVI.SubclassOptionalData; 1952 } 1953 1954 // getIndexedType - Returns the type of the element that would be extracted 1955 // with an extractvalue instruction with the specified parameters. 1956 // 1957 // A null type is returned if the indices are invalid for the specified 1958 // pointer type. 1959 // 1960 Type *ExtractValueInst::getIndexedType(Type *Agg, 1961 ArrayRef<unsigned> Idxs) { 1962 for (unsigned Index : Idxs) { 1963 // We can't use CompositeType::indexValid(Index) here. 1964 // indexValid() always returns true for arrays because getelementptr allows 1965 // out-of-bounds indices. Since we don't allow those for extractvalue and 1966 // insertvalue we need to check array indexing manually. 1967 // Since the only other types we can index into are struct types it's just 1968 // as easy to check those manually as well. 1969 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) { 1970 if (Index >= AT->getNumElements()) 1971 return nullptr; 1972 } else if (StructType *ST = dyn_cast<StructType>(Agg)) { 1973 if (Index >= ST->getNumElements()) 1974 return nullptr; 1975 } else { 1976 // Not a valid type to index into. 1977 return nullptr; 1978 } 1979 1980 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index); 1981 } 1982 return const_cast<Type*>(Agg); 1983 } 1984 1985 //===----------------------------------------------------------------------===// 1986 // BinaryOperator Class 1987 //===----------------------------------------------------------------------===// 1988 1989 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 1990 Type *Ty, const Twine &Name, 1991 Instruction *InsertBefore) 1992 : Instruction(Ty, iType, 1993 OperandTraits<BinaryOperator>::op_begin(this), 1994 OperandTraits<BinaryOperator>::operands(this), 1995 InsertBefore) { 1996 Op<0>() = S1; 1997 Op<1>() = S2; 1998 init(iType); 1999 setName(Name); 2000 } 2001 2002 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 2003 Type *Ty, const Twine &Name, 2004 BasicBlock *InsertAtEnd) 2005 : Instruction(Ty, iType, 2006 OperandTraits<BinaryOperator>::op_begin(this), 2007 OperandTraits<BinaryOperator>::operands(this), 2008 InsertAtEnd) { 2009 Op<0>() = S1; 2010 Op<1>() = S2; 2011 init(iType); 2012 setName(Name); 2013 } 2014 2015 void BinaryOperator::init(BinaryOps iType) { 2016 Value *LHS = getOperand(0), *RHS = getOperand(1); 2017 (void)LHS; (void)RHS; // Silence warnings. 2018 assert(LHS->getType() == RHS->getType() && 2019 "Binary operator operand types must match!"); 2020 #ifndef NDEBUG 2021 switch (iType) { 2022 case Add: case Sub: 2023 case Mul: 2024 assert(getType() == LHS->getType() && 2025 "Arithmetic operation should return same type as operands!"); 2026 assert(getType()->isIntOrIntVectorTy() && 2027 "Tried to create an integer operation on a non-integer type!"); 2028 break; 2029 case FAdd: case FSub: 2030 case FMul: 2031 assert(getType() == LHS->getType() && 2032 "Arithmetic operation should return same type as operands!"); 2033 assert(getType()->isFPOrFPVectorTy() && 2034 "Tried to create a floating-point operation on a " 2035 "non-floating-point type!"); 2036 break; 2037 case UDiv: 2038 case SDiv: 2039 assert(getType() == LHS->getType() && 2040 "Arithmetic operation should return same type as operands!"); 2041 assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 2042 cast<VectorType>(getType())->getElementType()->isIntegerTy())) && 2043 "Incorrect operand type (not integer) for S/UDIV"); 2044 break; 2045 case FDiv: 2046 assert(getType() == LHS->getType() && 2047 "Arithmetic operation should return same type as operands!"); 2048 assert(getType()->isFPOrFPVectorTy() && 2049 "Incorrect operand type (not floating point) for FDIV"); 2050 break; 2051 case URem: 2052 case SRem: 2053 assert(getType() == LHS->getType() && 2054 "Arithmetic operation should return same type as operands!"); 2055 assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 2056 cast<VectorType>(getType())->getElementType()->isIntegerTy())) && 2057 "Incorrect operand type (not integer) for S/UREM"); 2058 break; 2059 case FRem: 2060 assert(getType() == LHS->getType() && 2061 "Arithmetic operation should return same type as operands!"); 2062 assert(getType()->isFPOrFPVectorTy() && 2063 "Incorrect operand type (not floating point) for FREM"); 2064 break; 2065 case Shl: 2066 case LShr: 2067 case AShr: 2068 assert(getType() == LHS->getType() && 2069 "Shift operation should return same type as operands!"); 2070 assert((getType()->isIntegerTy() || 2071 (getType()->isVectorTy() && 2072 cast<VectorType>(getType())->getElementType()->isIntegerTy())) && 2073 "Tried to create a shift operation on a non-integral type!"); 2074 break; 2075 case And: case Or: 2076 case Xor: 2077 assert(getType() == LHS->getType() && 2078 "Logical operation should return same type as operands!"); 2079 assert((getType()->isIntegerTy() || 2080 (getType()->isVectorTy() && 2081 cast<VectorType>(getType())->getElementType()->isIntegerTy())) && 2082 "Tried to create a logical operation on a non-integral type!"); 2083 break; 2084 default: 2085 break; 2086 } 2087 #endif 2088 } 2089 2090 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2091 const Twine &Name, 2092 Instruction *InsertBefore) { 2093 assert(S1->getType() == S2->getType() && 2094 "Cannot create binary operator with two operands of differing type!"); 2095 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore); 2096 } 2097 2098 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 2099 const Twine &Name, 2100 BasicBlock *InsertAtEnd) { 2101 BinaryOperator *Res = Create(Op, S1, S2, Name); 2102 InsertAtEnd->getInstList().push_back(Res); 2103 return Res; 2104 } 2105 2106 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2107 Instruction *InsertBefore) { 2108 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2109 return new BinaryOperator(Instruction::Sub, 2110 zero, Op, 2111 Op->getType(), Name, InsertBefore); 2112 } 2113 2114 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 2115 BasicBlock *InsertAtEnd) { 2116 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2117 return new BinaryOperator(Instruction::Sub, 2118 zero, Op, 2119 Op->getType(), Name, InsertAtEnd); 2120 } 2121 2122 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2123 Instruction *InsertBefore) { 2124 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2125 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore); 2126 } 2127 2128 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name, 2129 BasicBlock *InsertAtEnd) { 2130 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2131 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd); 2132 } 2133 2134 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2135 Instruction *InsertBefore) { 2136 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2137 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore); 2138 } 2139 2140 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name, 2141 BasicBlock *InsertAtEnd) { 2142 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2143 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd); 2144 } 2145 2146 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name, 2147 Instruction *InsertBefore) { 2148 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2149 return new BinaryOperator(Instruction::FSub, zero, Op, 2150 Op->getType(), Name, InsertBefore); 2151 } 2152 2153 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name, 2154 BasicBlock *InsertAtEnd) { 2155 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 2156 return new BinaryOperator(Instruction::FSub, zero, Op, 2157 Op->getType(), Name, InsertAtEnd); 2158 } 2159 2160 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2161 Instruction *InsertBefore) { 2162 Constant *C = Constant::getAllOnesValue(Op->getType()); 2163 return new BinaryOperator(Instruction::Xor, Op, C, 2164 Op->getType(), Name, InsertBefore); 2165 } 2166 2167 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 2168 BasicBlock *InsertAtEnd) { 2169 Constant *AllOnes = Constant::getAllOnesValue(Op->getType()); 2170 return new BinaryOperator(Instruction::Xor, Op, AllOnes, 2171 Op->getType(), Name, InsertAtEnd); 2172 } 2173 2174 // isConstantAllOnes - Helper function for several functions below 2175 static inline bool isConstantAllOnes(const Value *V) { 2176 if (const Constant *C = dyn_cast<Constant>(V)) 2177 return C->isAllOnesValue(); 2178 return false; 2179 } 2180 2181 bool BinaryOperator::isNeg(const Value *V) { 2182 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 2183 if (Bop->getOpcode() == Instruction::Sub) 2184 if (Constant *C = dyn_cast<Constant>(Bop->getOperand(0))) 2185 return C->isNegativeZeroValue(); 2186 return false; 2187 } 2188 2189 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) { 2190 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 2191 if (Bop->getOpcode() == Instruction::FSub) 2192 if (Constant *C = dyn_cast<Constant>(Bop->getOperand(0))) { 2193 if (!IgnoreZeroSign) 2194 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros(); 2195 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue(); 2196 } 2197 return false; 2198 } 2199 2200 bool BinaryOperator::isNot(const Value *V) { 2201 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 2202 return (Bop->getOpcode() == Instruction::Xor && 2203 (isConstantAllOnes(Bop->getOperand(1)) || 2204 isConstantAllOnes(Bop->getOperand(0)))); 2205 return false; 2206 } 2207 2208 Value *BinaryOperator::getNegArgument(Value *BinOp) { 2209 return cast<BinaryOperator>(BinOp)->getOperand(1); 2210 } 2211 2212 const Value *BinaryOperator::getNegArgument(const Value *BinOp) { 2213 return getNegArgument(const_cast<Value*>(BinOp)); 2214 } 2215 2216 Value *BinaryOperator::getFNegArgument(Value *BinOp) { 2217 return cast<BinaryOperator>(BinOp)->getOperand(1); 2218 } 2219 2220 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) { 2221 return getFNegArgument(const_cast<Value*>(BinOp)); 2222 } 2223 2224 Value *BinaryOperator::getNotArgument(Value *BinOp) { 2225 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!"); 2226 BinaryOperator *BO = cast<BinaryOperator>(BinOp); 2227 Value *Op0 = BO->getOperand(0); 2228 Value *Op1 = BO->getOperand(1); 2229 if (isConstantAllOnes(Op0)) return Op1; 2230 2231 assert(isConstantAllOnes(Op1)); 2232 return Op0; 2233 } 2234 2235 const Value *BinaryOperator::getNotArgument(const Value *BinOp) { 2236 return getNotArgument(const_cast<Value*>(BinOp)); 2237 } 2238 2239 // Exchange the two operands to this instruction. This instruction is safe to 2240 // use on any binary instruction and does not modify the semantics of the 2241 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode 2242 // is changed. 2243 bool BinaryOperator::swapOperands() { 2244 if (!isCommutative()) 2245 return true; // Can't commute operands 2246 Op<0>().swap(Op<1>()); 2247 return false; 2248 } 2249 2250 //===----------------------------------------------------------------------===// 2251 // FPMathOperator Class 2252 //===----------------------------------------------------------------------===// 2253 2254 float FPMathOperator::getFPAccuracy() const { 2255 const MDNode *MD = 2256 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath); 2257 if (!MD) 2258 return 0.0; 2259 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0)); 2260 return Accuracy->getValueAPF().convertToFloat(); 2261 } 2262 2263 //===----------------------------------------------------------------------===// 2264 // CastInst Class 2265 //===----------------------------------------------------------------------===// 2266 2267 // Just determine if this cast only deals with integral->integral conversion. 2268 bool CastInst::isIntegerCast() const { 2269 switch (getOpcode()) { 2270 default: return false; 2271 case Instruction::ZExt: 2272 case Instruction::SExt: 2273 case Instruction::Trunc: 2274 return true; 2275 case Instruction::BitCast: 2276 return getOperand(0)->getType()->isIntegerTy() && 2277 getType()->isIntegerTy(); 2278 } 2279 } 2280 2281 bool CastInst::isLosslessCast() const { 2282 // Only BitCast can be lossless, exit fast if we're not BitCast 2283 if (getOpcode() != Instruction::BitCast) 2284 return false; 2285 2286 // Identity cast is always lossless 2287 Type *SrcTy = getOperand(0)->getType(); 2288 Type *DstTy = getType(); 2289 if (SrcTy == DstTy) 2290 return true; 2291 2292 // Pointer to pointer is always lossless. 2293 if (SrcTy->isPointerTy()) 2294 return DstTy->isPointerTy(); 2295 return false; // Other types have no identity values 2296 } 2297 2298 /// This function determines if the CastInst does not require any bits to be 2299 /// changed in order to effect the cast. Essentially, it identifies cases where 2300 /// no code gen is necessary for the cast, hence the name no-op cast. For 2301 /// example, the following are all no-op casts: 2302 /// # bitcast i32* %x to i8* 2303 /// # bitcast <2 x i32> %x to <4 x i16> 2304 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only 2305 /// @brief Determine if the described cast is a no-op. 2306 bool CastInst::isNoopCast(Instruction::CastOps Opcode, 2307 Type *SrcTy, 2308 Type *DestTy, 2309 Type *IntPtrTy) { 2310 switch (Opcode) { 2311 default: llvm_unreachable("Invalid CastOp"); 2312 case Instruction::Trunc: 2313 case Instruction::ZExt: 2314 case Instruction::SExt: 2315 case Instruction::FPTrunc: 2316 case Instruction::FPExt: 2317 case Instruction::UIToFP: 2318 case Instruction::SIToFP: 2319 case Instruction::FPToUI: 2320 case Instruction::FPToSI: 2321 case Instruction::AddrSpaceCast: 2322 // TODO: Target informations may give a more accurate answer here. 2323 return false; 2324 case Instruction::BitCast: 2325 return true; // BitCast never modifies bits. 2326 case Instruction::PtrToInt: 2327 return IntPtrTy->getScalarSizeInBits() == 2328 DestTy->getScalarSizeInBits(); 2329 case Instruction::IntToPtr: 2330 return IntPtrTy->getScalarSizeInBits() == 2331 SrcTy->getScalarSizeInBits(); 2332 } 2333 } 2334 2335 /// @brief Determine if a cast is a no-op. 2336 bool CastInst::isNoopCast(Type *IntPtrTy) const { 2337 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy); 2338 } 2339 2340 bool CastInst::isNoopCast(const DataLayout &DL) const { 2341 Type *PtrOpTy = nullptr; 2342 if (getOpcode() == Instruction::PtrToInt) 2343 PtrOpTy = getOperand(0)->getType(); 2344 else if (getOpcode() == Instruction::IntToPtr) 2345 PtrOpTy = getType(); 2346 2347 Type *IntPtrTy = 2348 PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0); 2349 2350 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy); 2351 } 2352 2353 /// This function determines if a pair of casts can be eliminated and what 2354 /// opcode should be used in the elimination. This assumes that there are two 2355 /// instructions like this: 2356 /// * %F = firstOpcode SrcTy %x to MidTy 2357 /// * %S = secondOpcode MidTy %F to DstTy 2358 /// The function returns a resultOpcode so these two casts can be replaced with: 2359 /// * %Replacement = resultOpcode %SrcTy %x to DstTy 2360 /// If no such cast is permitted, the function returns 0. 2361 unsigned CastInst::isEliminableCastPair( 2362 Instruction::CastOps firstOp, Instruction::CastOps secondOp, 2363 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy, 2364 Type *DstIntPtrTy) { 2365 // Define the 144 possibilities for these two cast instructions. The values 2366 // in this matrix determine what to do in a given situation and select the 2367 // case in the switch below. The rows correspond to firstOp, the columns 2368 // correspond to secondOp. In looking at the table below, keep in mind 2369 // the following cast properties: 2370 // 2371 // Size Compare Source Destination 2372 // Operator Src ? Size Type Sign Type Sign 2373 // -------- ------------ ------------------- --------------------- 2374 // TRUNC > Integer Any Integral Any 2375 // ZEXT < Integral Unsigned Integer Any 2376 // SEXT < Integral Signed Integer Any 2377 // FPTOUI n/a FloatPt n/a Integral Unsigned 2378 // FPTOSI n/a FloatPt n/a Integral Signed 2379 // UITOFP n/a Integral Unsigned FloatPt n/a 2380 // SITOFP n/a Integral Signed FloatPt n/a 2381 // FPTRUNC > FloatPt n/a FloatPt n/a 2382 // FPEXT < FloatPt n/a FloatPt n/a 2383 // PTRTOINT n/a Pointer n/a Integral Unsigned 2384 // INTTOPTR n/a Integral Unsigned Pointer n/a 2385 // BITCAST = FirstClass n/a FirstClass n/a 2386 // ADDRSPCST n/a Pointer n/a Pointer n/a 2387 // 2388 // NOTE: some transforms are safe, but we consider them to be non-profitable. 2389 // For example, we could merge "fptoui double to i32" + "zext i32 to i64", 2390 // into "fptoui double to i64", but this loses information about the range 2391 // of the produced value (we no longer know the top-part is all zeros). 2392 // Further this conversion is often much more expensive for typical hardware, 2393 // and causes issues when building libgcc. We disallow fptosi+sext for the 2394 // same reason. 2395 const unsigned numCastOps = 2396 Instruction::CastOpsEnd - Instruction::CastOpsBegin; 2397 static const uint8_t CastResults[numCastOps][numCastOps] = { 2398 // T F F U S F F P I B A -+ 2399 // R Z S P P I I T P 2 N T S | 2400 // U E E 2 2 2 2 R E I T C C +- secondOp 2401 // N X X U S F F N X N 2 V V | 2402 // C T T I I P P C T T P T T -+ 2403 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+ 2404 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt | 2405 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt | 2406 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI | 2407 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI | 2408 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp 2409 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP | 2410 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc | 2411 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt | 2412 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt | 2413 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr | 2414 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast | 2415 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+ 2416 }; 2417 2418 // TODO: This logic could be encoded into the table above and handled in the 2419 // switch below. 2420 // If either of the casts are a bitcast from scalar to vector, disallow the 2421 // merging. However, any pair of bitcasts are allowed. 2422 bool IsFirstBitcast = (firstOp == Instruction::BitCast); 2423 bool IsSecondBitcast = (secondOp == Instruction::BitCast); 2424 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast; 2425 2426 // Check if any of the casts convert scalars <-> vectors. 2427 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) || 2428 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy))) 2429 if (!AreBothBitcasts) 2430 return 0; 2431 2432 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin] 2433 [secondOp-Instruction::CastOpsBegin]; 2434 switch (ElimCase) { 2435 case 0: 2436 // Categorically disallowed. 2437 return 0; 2438 case 1: 2439 // Allowed, use first cast's opcode. 2440 return firstOp; 2441 case 2: 2442 // Allowed, use second cast's opcode. 2443 return secondOp; 2444 case 3: 2445 // No-op cast in second op implies firstOp as long as the DestTy 2446 // is integer and we are not converting between a vector and a 2447 // non-vector type. 2448 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy()) 2449 return firstOp; 2450 return 0; 2451 case 4: 2452 // No-op cast in second op implies firstOp as long as the DestTy 2453 // is floating point. 2454 if (DstTy->isFloatingPointTy()) 2455 return firstOp; 2456 return 0; 2457 case 5: 2458 // No-op cast in first op implies secondOp as long as the SrcTy 2459 // is an integer. 2460 if (SrcTy->isIntegerTy()) 2461 return secondOp; 2462 return 0; 2463 case 6: 2464 // No-op cast in first op implies secondOp as long as the SrcTy 2465 // is a floating point. 2466 if (SrcTy->isFloatingPointTy()) 2467 return secondOp; 2468 return 0; 2469 case 7: { 2470 // Cannot simplify if address spaces are different! 2471 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2472 return 0; 2473 2474 unsigned MidSize = MidTy->getScalarSizeInBits(); 2475 // We can still fold this without knowing the actual sizes as long we 2476 // know that the intermediate pointer is the largest possible 2477 // pointer size. 2478 // FIXME: Is this always true? 2479 if (MidSize == 64) 2480 return Instruction::BitCast; 2481 2482 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size. 2483 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy) 2484 return 0; 2485 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits(); 2486 if (MidSize >= PtrSize) 2487 return Instruction::BitCast; 2488 return 0; 2489 } 2490 case 8: { 2491 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size 2492 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy) 2493 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy) 2494 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2495 unsigned DstSize = DstTy->getScalarSizeInBits(); 2496 if (SrcSize == DstSize) 2497 return Instruction::BitCast; 2498 else if (SrcSize < DstSize) 2499 return firstOp; 2500 return secondOp; 2501 } 2502 case 9: 2503 // zext, sext -> zext, because sext can't sign extend after zext 2504 return Instruction::ZExt; 2505 case 10: 2506 // fpext followed by ftrunc is allowed if the bit size returned to is 2507 // the same as the original, in which case its just a bitcast 2508 if (SrcTy == DstTy) 2509 return Instruction::BitCast; 2510 return 0; // If the types are not the same we can't eliminate it. 2511 case 11: { 2512 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize 2513 if (!MidIntPtrTy) 2514 return 0; 2515 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits(); 2516 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2517 unsigned DstSize = DstTy->getScalarSizeInBits(); 2518 if (SrcSize <= PtrSize && SrcSize == DstSize) 2519 return Instruction::BitCast; 2520 return 0; 2521 } 2522 case 12: 2523 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS 2524 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS 2525 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) 2526 return Instruction::AddrSpaceCast; 2527 return Instruction::BitCast; 2528 case 13: 2529 // FIXME: this state can be merged with (1), but the following assert 2530 // is useful to check the correcteness of the sequence due to semantic 2531 // change of bitcast. 2532 assert( 2533 SrcTy->isPtrOrPtrVectorTy() && 2534 MidTy->isPtrOrPtrVectorTy() && 2535 DstTy->isPtrOrPtrVectorTy() && 2536 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() && 2537 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2538 "Illegal addrspacecast, bitcast sequence!"); 2539 // Allowed, use first cast's opcode 2540 return firstOp; 2541 case 14: 2542 // bitcast, addrspacecast -> addrspacecast if the element type of 2543 // bitcast's source is the same as that of addrspacecast's destination. 2544 if (SrcTy->getScalarType()->getPointerElementType() == 2545 DstTy->getScalarType()->getPointerElementType()) 2546 return Instruction::AddrSpaceCast; 2547 return 0; 2548 case 15: 2549 // FIXME: this state can be merged with (1), but the following assert 2550 // is useful to check the correcteness of the sequence due to semantic 2551 // change of bitcast. 2552 assert( 2553 SrcTy->isIntOrIntVectorTy() && 2554 MidTy->isPtrOrPtrVectorTy() && 2555 DstTy->isPtrOrPtrVectorTy() && 2556 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() && 2557 "Illegal inttoptr, bitcast sequence!"); 2558 // Allowed, use first cast's opcode 2559 return firstOp; 2560 case 16: 2561 // FIXME: this state can be merged with (2), but the following assert 2562 // is useful to check the correcteness of the sequence due to semantic 2563 // change of bitcast. 2564 assert( 2565 SrcTy->isPtrOrPtrVectorTy() && 2566 MidTy->isPtrOrPtrVectorTy() && 2567 DstTy->isIntOrIntVectorTy() && 2568 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() && 2569 "Illegal bitcast, ptrtoint sequence!"); 2570 // Allowed, use second cast's opcode 2571 return secondOp; 2572 case 17: 2573 // (sitofp (zext x)) -> (uitofp x) 2574 return Instruction::UIToFP; 2575 case 99: 2576 // Cast combination can't happen (error in input). This is for all cases 2577 // where the MidTy is not the same for the two cast instructions. 2578 llvm_unreachable("Invalid Cast Combination"); 2579 default: 2580 llvm_unreachable("Error in CastResults table!!!"); 2581 } 2582 } 2583 2584 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2585 const Twine &Name, Instruction *InsertBefore) { 2586 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2587 // Construct and return the appropriate CastInst subclass 2588 switch (op) { 2589 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore); 2590 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore); 2591 case SExt: return new SExtInst (S, Ty, Name, InsertBefore); 2592 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore); 2593 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore); 2594 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore); 2595 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore); 2596 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore); 2597 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore); 2598 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore); 2599 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore); 2600 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore); 2601 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore); 2602 default: llvm_unreachable("Invalid opcode provided"); 2603 } 2604 } 2605 2606 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 2607 const Twine &Name, BasicBlock *InsertAtEnd) { 2608 assert(castIsValid(op, S, Ty) && "Invalid cast!"); 2609 // Construct and return the appropriate CastInst subclass 2610 switch (op) { 2611 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd); 2612 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd); 2613 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd); 2614 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd); 2615 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd); 2616 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd); 2617 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd); 2618 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd); 2619 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd); 2620 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd); 2621 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd); 2622 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd); 2623 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd); 2624 default: llvm_unreachable("Invalid opcode provided"); 2625 } 2626 } 2627 2628 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2629 const Twine &Name, 2630 Instruction *InsertBefore) { 2631 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2632 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2633 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore); 2634 } 2635 2636 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 2637 const Twine &Name, 2638 BasicBlock *InsertAtEnd) { 2639 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2640 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2641 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd); 2642 } 2643 2644 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2645 const Twine &Name, 2646 Instruction *InsertBefore) { 2647 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2648 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2649 return Create(Instruction::SExt, S, Ty, Name, InsertBefore); 2650 } 2651 2652 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 2653 const Twine &Name, 2654 BasicBlock *InsertAtEnd) { 2655 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2656 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2657 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd); 2658 } 2659 2660 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2661 const Twine &Name, 2662 Instruction *InsertBefore) { 2663 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2664 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2665 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore); 2666 } 2667 2668 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty, 2669 const Twine &Name, 2670 BasicBlock *InsertAtEnd) { 2671 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2672 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2673 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd); 2674 } 2675 2676 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2677 const Twine &Name, 2678 BasicBlock *InsertAtEnd) { 2679 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2680 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2681 "Invalid cast"); 2682 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2683 assert((!Ty->isVectorTy() || 2684 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) && 2685 "Invalid cast"); 2686 2687 if (Ty->isIntOrIntVectorTy()) 2688 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd); 2689 2690 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd); 2691 } 2692 2693 /// @brief Create a BitCast or a PtrToInt cast instruction 2694 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 2695 const Twine &Name, 2696 Instruction *InsertBefore) { 2697 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2698 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) && 2699 "Invalid cast"); 2700 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast"); 2701 assert((!Ty->isVectorTy() || 2702 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) && 2703 "Invalid cast"); 2704 2705 if (Ty->isIntOrIntVectorTy()) 2706 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2707 2708 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore); 2709 } 2710 2711 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 2712 Value *S, Type *Ty, 2713 const Twine &Name, 2714 BasicBlock *InsertAtEnd) { 2715 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2716 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 2717 2718 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 2719 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd); 2720 2721 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2722 } 2723 2724 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast( 2725 Value *S, Type *Ty, 2726 const Twine &Name, 2727 Instruction *InsertBefore) { 2728 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast"); 2729 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast"); 2730 2731 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace()) 2732 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore); 2733 2734 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2735 } 2736 2737 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty, 2738 const Twine &Name, 2739 Instruction *InsertBefore) { 2740 if (S->getType()->isPointerTy() && Ty->isIntegerTy()) 2741 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2742 if (S->getType()->isIntegerTy() && Ty->isPointerTy()) 2743 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore); 2744 2745 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2746 } 2747 2748 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 2749 bool isSigned, const Twine &Name, 2750 Instruction *InsertBefore) { 2751 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 2752 "Invalid integer cast"); 2753 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2754 unsigned DstBits = Ty->getScalarSizeInBits(); 2755 Instruction::CastOps opcode = 2756 (SrcBits == DstBits ? Instruction::BitCast : 2757 (SrcBits > DstBits ? Instruction::Trunc : 2758 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2759 return Create(opcode, C, Ty, Name, InsertBefore); 2760 } 2761 2762 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 2763 bool isSigned, const Twine &Name, 2764 BasicBlock *InsertAtEnd) { 2765 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() && 2766 "Invalid cast"); 2767 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2768 unsigned DstBits = Ty->getScalarSizeInBits(); 2769 Instruction::CastOps opcode = 2770 (SrcBits == DstBits ? Instruction::BitCast : 2771 (SrcBits > DstBits ? Instruction::Trunc : 2772 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2773 return Create(opcode, C, Ty, Name, InsertAtEnd); 2774 } 2775 2776 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 2777 const Twine &Name, 2778 Instruction *InsertBefore) { 2779 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 2780 "Invalid cast"); 2781 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2782 unsigned DstBits = Ty->getScalarSizeInBits(); 2783 Instruction::CastOps opcode = 2784 (SrcBits == DstBits ? Instruction::BitCast : 2785 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 2786 return Create(opcode, C, Ty, Name, InsertBefore); 2787 } 2788 2789 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 2790 const Twine &Name, 2791 BasicBlock *InsertAtEnd) { 2792 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() && 2793 "Invalid cast"); 2794 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2795 unsigned DstBits = Ty->getScalarSizeInBits(); 2796 Instruction::CastOps opcode = 2797 (SrcBits == DstBits ? Instruction::BitCast : 2798 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 2799 return Create(opcode, C, Ty, Name, InsertAtEnd); 2800 } 2801 2802 // Check whether it is valid to call getCastOpcode for these types. 2803 // This routine must be kept in sync with getCastOpcode. 2804 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) { 2805 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 2806 return false; 2807 2808 if (SrcTy == DestTy) 2809 return true; 2810 2811 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 2812 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 2813 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 2814 // An element by element cast. Valid if casting the elements is valid. 2815 SrcTy = SrcVecTy->getElementType(); 2816 DestTy = DestVecTy->getElementType(); 2817 } 2818 2819 // Get the bit sizes, we'll need these 2820 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 2821 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 2822 2823 // Run through the possibilities ... 2824 if (DestTy->isIntegerTy()) { // Casting to integral 2825 if (SrcTy->isIntegerTy()) // Casting from integral 2826 return true; 2827 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 2828 return true; 2829 if (SrcTy->isVectorTy()) // Casting from vector 2830 return DestBits == SrcBits; 2831 // Casting from something else 2832 return SrcTy->isPointerTy(); 2833 } 2834 if (DestTy->isFloatingPointTy()) { // Casting to floating pt 2835 if (SrcTy->isIntegerTy()) // Casting from integral 2836 return true; 2837 if (SrcTy->isFloatingPointTy()) // Casting from floating pt 2838 return true; 2839 if (SrcTy->isVectorTy()) // Casting from vector 2840 return DestBits == SrcBits; 2841 // Casting from something else 2842 return false; 2843 } 2844 if (DestTy->isVectorTy()) // Casting to vector 2845 return DestBits == SrcBits; 2846 if (DestTy->isPointerTy()) { // Casting to pointer 2847 if (SrcTy->isPointerTy()) // Casting from pointer 2848 return true; 2849 return SrcTy->isIntegerTy(); // Casting from integral 2850 } 2851 if (DestTy->isX86_MMXTy()) { 2852 if (SrcTy->isVectorTy()) 2853 return DestBits == SrcBits; // 64-bit vector to MMX 2854 return false; 2855 } // Casting to something else 2856 return false; 2857 } 2858 2859 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) { 2860 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 2861 return false; 2862 2863 if (SrcTy == DestTy) 2864 return true; 2865 2866 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 2867 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) { 2868 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 2869 // An element by element cast. Valid if casting the elements is valid. 2870 SrcTy = SrcVecTy->getElementType(); 2871 DestTy = DestVecTy->getElementType(); 2872 } 2873 } 2874 } 2875 2876 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) { 2877 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) { 2878 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace(); 2879 } 2880 } 2881 2882 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 2883 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 2884 2885 // Could still have vectors of pointers if the number of elements doesn't 2886 // match 2887 if (SrcBits == 0 || DestBits == 0) 2888 return false; 2889 2890 if (SrcBits != DestBits) 2891 return false; 2892 2893 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy()) 2894 return false; 2895 2896 return true; 2897 } 2898 2899 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, 2900 const DataLayout &DL) { 2901 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy)) 2902 if (auto *IntTy = dyn_cast<IntegerType>(DestTy)) 2903 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy); 2904 if (auto *PtrTy = dyn_cast<PointerType>(DestTy)) 2905 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy)) 2906 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy); 2907 2908 return isBitCastable(SrcTy, DestTy); 2909 } 2910 2911 // Provide a way to get a "cast" where the cast opcode is inferred from the 2912 // types and size of the operand. This, basically, is a parallel of the 2913 // logic in the castIsValid function below. This axiom should hold: 2914 // castIsValid( getCastOpcode(Val, Ty), Val, Ty) 2915 // should not assert in castIsValid. In other words, this produces a "correct" 2916 // casting opcode for the arguments passed to it. 2917 // This routine must be kept in sync with isCastable. 2918 Instruction::CastOps 2919 CastInst::getCastOpcode( 2920 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) { 2921 Type *SrcTy = Src->getType(); 2922 2923 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() && 2924 "Only first class types are castable!"); 2925 2926 if (SrcTy == DestTy) 2927 return BitCast; 2928 2929 // FIXME: Check address space sizes here 2930 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) 2931 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) 2932 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) { 2933 // An element by element cast. Find the appropriate opcode based on the 2934 // element types. 2935 SrcTy = SrcVecTy->getElementType(); 2936 DestTy = DestVecTy->getElementType(); 2937 } 2938 2939 // Get the bit sizes, we'll need these 2940 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr 2941 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr 2942 2943 // Run through the possibilities ... 2944 if (DestTy->isIntegerTy()) { // Casting to integral 2945 if (SrcTy->isIntegerTy()) { // Casting from integral 2946 if (DestBits < SrcBits) 2947 return Trunc; // int -> smaller int 2948 else if (DestBits > SrcBits) { // its an extension 2949 if (SrcIsSigned) 2950 return SExt; // signed -> SEXT 2951 else 2952 return ZExt; // unsigned -> ZEXT 2953 } else { 2954 return BitCast; // Same size, No-op cast 2955 } 2956 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 2957 if (DestIsSigned) 2958 return FPToSI; // FP -> sint 2959 else 2960 return FPToUI; // FP -> uint 2961 } else if (SrcTy->isVectorTy()) { 2962 assert(DestBits == SrcBits && 2963 "Casting vector to integer of different width"); 2964 return BitCast; // Same size, no-op cast 2965 } else { 2966 assert(SrcTy->isPointerTy() && 2967 "Casting from a value that is not first-class type"); 2968 return PtrToInt; // ptr -> int 2969 } 2970 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt 2971 if (SrcTy->isIntegerTy()) { // Casting from integral 2972 if (SrcIsSigned) 2973 return SIToFP; // sint -> FP 2974 else 2975 return UIToFP; // uint -> FP 2976 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt 2977 if (DestBits < SrcBits) { 2978 return FPTrunc; // FP -> smaller FP 2979 } else if (DestBits > SrcBits) { 2980 return FPExt; // FP -> larger FP 2981 } else { 2982 return BitCast; // same size, no-op cast 2983 } 2984 } else if (SrcTy->isVectorTy()) { 2985 assert(DestBits == SrcBits && 2986 "Casting vector to floating point of different width"); 2987 return BitCast; // same size, no-op cast 2988 } 2989 llvm_unreachable("Casting pointer or non-first class to float"); 2990 } else if (DestTy->isVectorTy()) { 2991 assert(DestBits == SrcBits && 2992 "Illegal cast to vector (wrong type or size)"); 2993 return BitCast; 2994 } else if (DestTy->isPointerTy()) { 2995 if (SrcTy->isPointerTy()) { 2996 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace()) 2997 return AddrSpaceCast; 2998 return BitCast; // ptr -> ptr 2999 } else if (SrcTy->isIntegerTy()) { 3000 return IntToPtr; // int -> ptr 3001 } 3002 llvm_unreachable("Casting pointer to other than pointer or int"); 3003 } else if (DestTy->isX86_MMXTy()) { 3004 if (SrcTy->isVectorTy()) { 3005 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX"); 3006 return BitCast; // 64-bit vector to MMX 3007 } 3008 llvm_unreachable("Illegal cast to X86_MMX"); 3009 } 3010 llvm_unreachable("Casting to type that is not first-class"); 3011 } 3012 3013 //===----------------------------------------------------------------------===// 3014 // CastInst SubClass Constructors 3015 //===----------------------------------------------------------------------===// 3016 3017 /// Check that the construction parameters for a CastInst are correct. This 3018 /// could be broken out into the separate constructors but it is useful to have 3019 /// it in one place and to eliminate the redundant code for getting the sizes 3020 /// of the types involved. 3021 bool 3022 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) { 3023 // Check for type sanity on the arguments 3024 Type *SrcTy = S->getType(); 3025 3026 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() || 3027 SrcTy->isAggregateType() || DstTy->isAggregateType()) 3028 return false; 3029 3030 // Get the size of the types in bits, we'll need this later 3031 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 3032 unsigned DstBitSize = DstTy->getScalarSizeInBits(); 3033 3034 // If these are vector types, get the lengths of the vectors (using zero for 3035 // scalar types means that checking that vector lengths match also checks that 3036 // scalars are not being converted to vectors or vectors to scalars). 3037 unsigned SrcLength = SrcTy->isVectorTy() ? 3038 cast<VectorType>(SrcTy)->getNumElements() : 0; 3039 unsigned DstLength = DstTy->isVectorTy() ? 3040 cast<VectorType>(DstTy)->getNumElements() : 0; 3041 3042 // Switch on the opcode provided 3043 switch (op) { 3044 default: return false; // This is an input error 3045 case Instruction::Trunc: 3046 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3047 SrcLength == DstLength && SrcBitSize > DstBitSize; 3048 case Instruction::ZExt: 3049 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3050 SrcLength == DstLength && SrcBitSize < DstBitSize; 3051 case Instruction::SExt: 3052 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() && 3053 SrcLength == DstLength && SrcBitSize < DstBitSize; 3054 case Instruction::FPTrunc: 3055 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3056 SrcLength == DstLength && SrcBitSize > DstBitSize; 3057 case Instruction::FPExt: 3058 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() && 3059 SrcLength == DstLength && SrcBitSize < DstBitSize; 3060 case Instruction::UIToFP: 3061 case Instruction::SIToFP: 3062 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() && 3063 SrcLength == DstLength; 3064 case Instruction::FPToUI: 3065 case Instruction::FPToSI: 3066 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() && 3067 SrcLength == DstLength; 3068 case Instruction::PtrToInt: 3069 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy)) 3070 return false; 3071 if (VectorType *VT = dyn_cast<VectorType>(SrcTy)) 3072 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements()) 3073 return false; 3074 return SrcTy->getScalarType()->isPointerTy() && 3075 DstTy->getScalarType()->isIntegerTy(); 3076 case Instruction::IntToPtr: 3077 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy)) 3078 return false; 3079 if (VectorType *VT = dyn_cast<VectorType>(SrcTy)) 3080 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements()) 3081 return false; 3082 return SrcTy->getScalarType()->isIntegerTy() && 3083 DstTy->getScalarType()->isPointerTy(); 3084 case Instruction::BitCast: { 3085 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3086 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3087 3088 // BitCast implies a no-op cast of type only. No bits change. 3089 // However, you can't cast pointers to anything but pointers. 3090 if (!SrcPtrTy != !DstPtrTy) 3091 return false; 3092 3093 // For non-pointer cases, the cast is okay if the source and destination bit 3094 // widths are identical. 3095 if (!SrcPtrTy) 3096 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits(); 3097 3098 // If both are pointers then the address spaces must match. 3099 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) 3100 return false; 3101 3102 // A vector of pointers must have the same number of elements. 3103 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 3104 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy)) 3105 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements()); 3106 3107 return false; 3108 } 3109 3110 return true; 3111 } 3112 case Instruction::AddrSpaceCast: { 3113 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType()); 3114 if (!SrcPtrTy) 3115 return false; 3116 3117 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType()); 3118 if (!DstPtrTy) 3119 return false; 3120 3121 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace()) 3122 return false; 3123 3124 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) { 3125 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy)) 3126 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements()); 3127 3128 return false; 3129 } 3130 3131 return true; 3132 } 3133 } 3134 } 3135 3136 TruncInst::TruncInst( 3137 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3138 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) { 3139 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3140 } 3141 3142 TruncInst::TruncInst( 3143 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3144 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 3145 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 3146 } 3147 3148 ZExtInst::ZExtInst( 3149 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3150 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) { 3151 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3152 } 3153 3154 ZExtInst::ZExtInst( 3155 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3156 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 3157 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 3158 } 3159 SExtInst::SExtInst( 3160 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3161 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 3162 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3163 } 3164 3165 SExtInst::SExtInst( 3166 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3167 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 3168 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 3169 } 3170 3171 FPTruncInst::FPTruncInst( 3172 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3173 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 3174 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3175 } 3176 3177 FPTruncInst::FPTruncInst( 3178 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3179 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 3180 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 3181 } 3182 3183 FPExtInst::FPExtInst( 3184 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3185 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 3186 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3187 } 3188 3189 FPExtInst::FPExtInst( 3190 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3191 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 3192 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 3193 } 3194 3195 UIToFPInst::UIToFPInst( 3196 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3197 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 3198 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3199 } 3200 3201 UIToFPInst::UIToFPInst( 3202 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3203 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 3204 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 3205 } 3206 3207 SIToFPInst::SIToFPInst( 3208 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3209 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 3210 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3211 } 3212 3213 SIToFPInst::SIToFPInst( 3214 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3215 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 3216 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 3217 } 3218 3219 FPToUIInst::FPToUIInst( 3220 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3221 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 3222 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3223 } 3224 3225 FPToUIInst::FPToUIInst( 3226 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3227 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 3228 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 3229 } 3230 3231 FPToSIInst::FPToSIInst( 3232 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3233 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 3234 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3235 } 3236 3237 FPToSIInst::FPToSIInst( 3238 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3239 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 3240 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 3241 } 3242 3243 PtrToIntInst::PtrToIntInst( 3244 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3245 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 3246 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3247 } 3248 3249 PtrToIntInst::PtrToIntInst( 3250 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3251 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 3252 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 3253 } 3254 3255 IntToPtrInst::IntToPtrInst( 3256 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3257 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 3258 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3259 } 3260 3261 IntToPtrInst::IntToPtrInst( 3262 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3263 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 3264 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 3265 } 3266 3267 BitCastInst::BitCastInst( 3268 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3269 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 3270 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3271 } 3272 3273 BitCastInst::BitCastInst( 3274 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3275 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 3276 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 3277 } 3278 3279 AddrSpaceCastInst::AddrSpaceCastInst( 3280 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore 3281 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) { 3282 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3283 } 3284 3285 AddrSpaceCastInst::AddrSpaceCastInst( 3286 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 3287 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) { 3288 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast"); 3289 } 3290 3291 //===----------------------------------------------------------------------===// 3292 // CmpInst Classes 3293 //===----------------------------------------------------------------------===// 3294 3295 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3296 Value *RHS, const Twine &Name, Instruction *InsertBefore) 3297 : Instruction(ty, op, 3298 OperandTraits<CmpInst>::op_begin(this), 3299 OperandTraits<CmpInst>::operands(this), 3300 InsertBefore) { 3301 Op<0>() = LHS; 3302 Op<1>() = RHS; 3303 setPredicate((Predicate)predicate); 3304 setName(Name); 3305 } 3306 3307 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS, 3308 Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd) 3309 : Instruction(ty, op, 3310 OperandTraits<CmpInst>::op_begin(this), 3311 OperandTraits<CmpInst>::operands(this), 3312 InsertAtEnd) { 3313 Op<0>() = LHS; 3314 Op<1>() = RHS; 3315 setPredicate((Predicate)predicate); 3316 setName(Name); 3317 } 3318 3319 CmpInst * 3320 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3321 const Twine &Name, Instruction *InsertBefore) { 3322 if (Op == Instruction::ICmp) { 3323 if (InsertBefore) 3324 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate), 3325 S1, S2, Name); 3326 else 3327 return new ICmpInst(CmpInst::Predicate(predicate), 3328 S1, S2, Name); 3329 } 3330 3331 if (InsertBefore) 3332 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate), 3333 S1, S2, Name); 3334 else 3335 return new FCmpInst(CmpInst::Predicate(predicate), 3336 S1, S2, Name); 3337 } 3338 3339 CmpInst * 3340 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, 3341 const Twine &Name, BasicBlock *InsertAtEnd) { 3342 if (Op == Instruction::ICmp) { 3343 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3344 S1, S2, Name); 3345 } 3346 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 3347 S1, S2, Name); 3348 } 3349 3350 void CmpInst::swapOperands() { 3351 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3352 IC->swapOperands(); 3353 else 3354 cast<FCmpInst>(this)->swapOperands(); 3355 } 3356 3357 bool CmpInst::isCommutative() const { 3358 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3359 return IC->isCommutative(); 3360 return cast<FCmpInst>(this)->isCommutative(); 3361 } 3362 3363 bool CmpInst::isEquality() const { 3364 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this)) 3365 return IC->isEquality(); 3366 return cast<FCmpInst>(this)->isEquality(); 3367 } 3368 3369 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { 3370 switch (pred) { 3371 default: llvm_unreachable("Unknown cmp predicate!"); 3372 case ICMP_EQ: return ICMP_NE; 3373 case ICMP_NE: return ICMP_EQ; 3374 case ICMP_UGT: return ICMP_ULE; 3375 case ICMP_ULT: return ICMP_UGE; 3376 case ICMP_UGE: return ICMP_ULT; 3377 case ICMP_ULE: return ICMP_UGT; 3378 case ICMP_SGT: return ICMP_SLE; 3379 case ICMP_SLT: return ICMP_SGE; 3380 case ICMP_SGE: return ICMP_SLT; 3381 case ICMP_SLE: return ICMP_SGT; 3382 3383 case FCMP_OEQ: return FCMP_UNE; 3384 case FCMP_ONE: return FCMP_UEQ; 3385 case FCMP_OGT: return FCMP_ULE; 3386 case FCMP_OLT: return FCMP_UGE; 3387 case FCMP_OGE: return FCMP_ULT; 3388 case FCMP_OLE: return FCMP_UGT; 3389 case FCMP_UEQ: return FCMP_ONE; 3390 case FCMP_UNE: return FCMP_OEQ; 3391 case FCMP_UGT: return FCMP_OLE; 3392 case FCMP_ULT: return FCMP_OGE; 3393 case FCMP_UGE: return FCMP_OLT; 3394 case FCMP_ULE: return FCMP_OGT; 3395 case FCMP_ORD: return FCMP_UNO; 3396 case FCMP_UNO: return FCMP_ORD; 3397 case FCMP_TRUE: return FCMP_FALSE; 3398 case FCMP_FALSE: return FCMP_TRUE; 3399 } 3400 } 3401 3402 StringRef CmpInst::getPredicateName(Predicate Pred) { 3403 switch (Pred) { 3404 default: return "unknown"; 3405 case FCmpInst::FCMP_FALSE: return "false"; 3406 case FCmpInst::FCMP_OEQ: return "oeq"; 3407 case FCmpInst::FCMP_OGT: return "ogt"; 3408 case FCmpInst::FCMP_OGE: return "oge"; 3409 case FCmpInst::FCMP_OLT: return "olt"; 3410 case FCmpInst::FCMP_OLE: return "ole"; 3411 case FCmpInst::FCMP_ONE: return "one"; 3412 case FCmpInst::FCMP_ORD: return "ord"; 3413 case FCmpInst::FCMP_UNO: return "uno"; 3414 case FCmpInst::FCMP_UEQ: return "ueq"; 3415 case FCmpInst::FCMP_UGT: return "ugt"; 3416 case FCmpInst::FCMP_UGE: return "uge"; 3417 case FCmpInst::FCMP_ULT: return "ult"; 3418 case FCmpInst::FCMP_ULE: return "ule"; 3419 case FCmpInst::FCMP_UNE: return "une"; 3420 case FCmpInst::FCMP_TRUE: return "true"; 3421 case ICmpInst::ICMP_EQ: return "eq"; 3422 case ICmpInst::ICMP_NE: return "ne"; 3423 case ICmpInst::ICMP_SGT: return "sgt"; 3424 case ICmpInst::ICMP_SGE: return "sge"; 3425 case ICmpInst::ICMP_SLT: return "slt"; 3426 case ICmpInst::ICMP_SLE: return "sle"; 3427 case ICmpInst::ICMP_UGT: return "ugt"; 3428 case ICmpInst::ICMP_UGE: return "uge"; 3429 case ICmpInst::ICMP_ULT: return "ult"; 3430 case ICmpInst::ICMP_ULE: return "ule"; 3431 } 3432 } 3433 3434 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) { 3435 switch (pred) { 3436 default: llvm_unreachable("Unknown icmp predicate!"); 3437 case ICMP_EQ: case ICMP_NE: 3438 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 3439 return pred; 3440 case ICMP_UGT: return ICMP_SGT; 3441 case ICMP_ULT: return ICMP_SLT; 3442 case ICMP_UGE: return ICMP_SGE; 3443 case ICMP_ULE: return ICMP_SLE; 3444 } 3445 } 3446 3447 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) { 3448 switch (pred) { 3449 default: llvm_unreachable("Unknown icmp predicate!"); 3450 case ICMP_EQ: case ICMP_NE: 3451 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 3452 return pred; 3453 case ICMP_SGT: return ICMP_UGT; 3454 case ICMP_SLT: return ICMP_ULT; 3455 case ICMP_SGE: return ICMP_UGE; 3456 case ICMP_SLE: return ICMP_ULE; 3457 } 3458 } 3459 3460 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { 3461 switch (pred) { 3462 default: llvm_unreachable("Unknown cmp predicate!"); 3463 case ICMP_EQ: case ICMP_NE: 3464 return pred; 3465 case ICMP_SGT: return ICMP_SLT; 3466 case ICMP_SLT: return ICMP_SGT; 3467 case ICMP_SGE: return ICMP_SLE; 3468 case ICMP_SLE: return ICMP_SGE; 3469 case ICMP_UGT: return ICMP_ULT; 3470 case ICMP_ULT: return ICMP_UGT; 3471 case ICMP_UGE: return ICMP_ULE; 3472 case ICMP_ULE: return ICMP_UGE; 3473 3474 case FCMP_FALSE: case FCMP_TRUE: 3475 case FCMP_OEQ: case FCMP_ONE: 3476 case FCMP_UEQ: case FCMP_UNE: 3477 case FCMP_ORD: case FCMP_UNO: 3478 return pred; 3479 case FCMP_OGT: return FCMP_OLT; 3480 case FCMP_OLT: return FCMP_OGT; 3481 case FCMP_OGE: return FCMP_OLE; 3482 case FCMP_OLE: return FCMP_OGE; 3483 case FCMP_UGT: return FCMP_ULT; 3484 case FCMP_ULT: return FCMP_UGT; 3485 case FCMP_UGE: return FCMP_ULE; 3486 case FCMP_ULE: return FCMP_UGE; 3487 } 3488 } 3489 3490 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) { 3491 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!"); 3492 3493 switch (pred) { 3494 default: 3495 llvm_unreachable("Unknown predicate!"); 3496 case CmpInst::ICMP_ULT: 3497 return CmpInst::ICMP_SLT; 3498 case CmpInst::ICMP_ULE: 3499 return CmpInst::ICMP_SLE; 3500 case CmpInst::ICMP_UGT: 3501 return CmpInst::ICMP_SGT; 3502 case CmpInst::ICMP_UGE: 3503 return CmpInst::ICMP_SGE; 3504 } 3505 } 3506 3507 bool CmpInst::isUnsigned(Predicate predicate) { 3508 switch (predicate) { 3509 default: return false; 3510 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 3511 case ICmpInst::ICMP_UGE: return true; 3512 } 3513 } 3514 3515 bool CmpInst::isSigned(Predicate predicate) { 3516 switch (predicate) { 3517 default: return false; 3518 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 3519 case ICmpInst::ICMP_SGE: return true; 3520 } 3521 } 3522 3523 bool CmpInst::isOrdered(Predicate predicate) { 3524 switch (predicate) { 3525 default: return false; 3526 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 3527 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 3528 case FCmpInst::FCMP_ORD: return true; 3529 } 3530 } 3531 3532 bool CmpInst::isUnordered(Predicate predicate) { 3533 switch (predicate) { 3534 default: return false; 3535 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 3536 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 3537 case FCmpInst::FCMP_UNO: return true; 3538 } 3539 } 3540 3541 bool CmpInst::isTrueWhenEqual(Predicate predicate) { 3542 switch(predicate) { 3543 default: return false; 3544 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE: 3545 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true; 3546 } 3547 } 3548 3549 bool CmpInst::isFalseWhenEqual(Predicate predicate) { 3550 switch(predicate) { 3551 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT: 3552 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true; 3553 default: return false; 3554 } 3555 } 3556 3557 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) { 3558 // If the predicates match, then we know the first condition implies the 3559 // second is true. 3560 if (Pred1 == Pred2) 3561 return true; 3562 3563 switch (Pred1) { 3564 default: 3565 break; 3566 case ICMP_EQ: 3567 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true. 3568 return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE || 3569 Pred2 == ICMP_SLE; 3570 case ICMP_UGT: // A >u B implies A != B and A >=u B are true. 3571 return Pred2 == ICMP_NE || Pred2 == ICMP_UGE; 3572 case ICMP_ULT: // A <u B implies A != B and A <=u B are true. 3573 return Pred2 == ICMP_NE || Pred2 == ICMP_ULE; 3574 case ICMP_SGT: // A >s B implies A != B and A >=s B are true. 3575 return Pred2 == ICMP_NE || Pred2 == ICMP_SGE; 3576 case ICMP_SLT: // A <s B implies A != B and A <=s B are true. 3577 return Pred2 == ICMP_NE || Pred2 == ICMP_SLE; 3578 } 3579 return false; 3580 } 3581 3582 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) { 3583 return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2)); 3584 } 3585 3586 //===----------------------------------------------------------------------===// 3587 // SwitchInst Implementation 3588 //===----------------------------------------------------------------------===// 3589 3590 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) { 3591 assert(Value && Default && NumReserved); 3592 ReservedSpace = NumReserved; 3593 setNumHungOffUseOperands(2); 3594 allocHungoffUses(ReservedSpace); 3595 3596 Op<0>() = Value; 3597 Op<1>() = Default; 3598 } 3599 3600 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3601 /// switch on and a default destination. The number of additional cases can 3602 /// be specified here to make memory allocation more efficient. This 3603 /// constructor can also autoinsert before another instruction. 3604 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3605 Instruction *InsertBefore) 3606 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3607 nullptr, 0, InsertBefore) { 3608 init(Value, Default, 2+NumCases*2); 3609 } 3610 3611 /// SwitchInst ctor - Create a new switch instruction, specifying a value to 3612 /// switch on and a default destination. The number of additional cases can 3613 /// be specified here to make memory allocation more efficient. This 3614 /// constructor also autoinserts at the end of the specified BasicBlock. 3615 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 3616 BasicBlock *InsertAtEnd) 3617 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch, 3618 nullptr, 0, InsertAtEnd) { 3619 init(Value, Default, 2+NumCases*2); 3620 } 3621 3622 SwitchInst::SwitchInst(const SwitchInst &SI) 3623 : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) { 3624 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands()); 3625 setNumHungOffUseOperands(SI.getNumOperands()); 3626 Use *OL = getOperandList(); 3627 const Use *InOL = SI.getOperandList(); 3628 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) { 3629 OL[i] = InOL[i]; 3630 OL[i+1] = InOL[i+1]; 3631 } 3632 SubclassOptionalData = SI.SubclassOptionalData; 3633 } 3634 3635 3636 /// addCase - Add an entry to the switch instruction... 3637 /// 3638 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) { 3639 unsigned NewCaseIdx = getNumCases(); 3640 unsigned OpNo = getNumOperands(); 3641 if (OpNo+2 > ReservedSpace) 3642 growOperands(); // Get more space! 3643 // Initialize some new operands. 3644 assert(OpNo+1 < ReservedSpace && "Growing didn't work!"); 3645 setNumHungOffUseOperands(OpNo+2); 3646 CaseHandle Case(this, NewCaseIdx); 3647 Case.setValue(OnVal); 3648 Case.setSuccessor(Dest); 3649 } 3650 3651 /// removeCase - This method removes the specified case and its successor 3652 /// from the switch instruction. 3653 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) { 3654 unsigned idx = I->getCaseIndex(); 3655 3656 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!"); 3657 3658 unsigned NumOps = getNumOperands(); 3659 Use *OL = getOperandList(); 3660 3661 // Overwrite this case with the end of the list. 3662 if (2 + (idx + 1) * 2 != NumOps) { 3663 OL[2 + idx * 2] = OL[NumOps - 2]; 3664 OL[2 + idx * 2 + 1] = OL[NumOps - 1]; 3665 } 3666 3667 // Nuke the last value. 3668 OL[NumOps-2].set(nullptr); 3669 OL[NumOps-2+1].set(nullptr); 3670 setNumHungOffUseOperands(NumOps-2); 3671 3672 return CaseIt(this, idx); 3673 } 3674 3675 /// growOperands - grow operands - This grows the operand list in response 3676 /// to a push_back style of operation. This grows the number of ops by 3 times. 3677 /// 3678 void SwitchInst::growOperands() { 3679 unsigned e = getNumOperands(); 3680 unsigned NumOps = e*3; 3681 3682 ReservedSpace = NumOps; 3683 growHungoffUses(ReservedSpace); 3684 } 3685 3686 //===----------------------------------------------------------------------===// 3687 // IndirectBrInst Implementation 3688 //===----------------------------------------------------------------------===// 3689 3690 void IndirectBrInst::init(Value *Address, unsigned NumDests) { 3691 assert(Address && Address->getType()->isPointerTy() && 3692 "Address of indirectbr must be a pointer"); 3693 ReservedSpace = 1+NumDests; 3694 setNumHungOffUseOperands(1); 3695 allocHungoffUses(ReservedSpace); 3696 3697 Op<0>() = Address; 3698 } 3699 3700 3701 /// growOperands - grow operands - This grows the operand list in response 3702 /// to a push_back style of operation. This grows the number of ops by 2 times. 3703 /// 3704 void IndirectBrInst::growOperands() { 3705 unsigned e = getNumOperands(); 3706 unsigned NumOps = e*2; 3707 3708 ReservedSpace = NumOps; 3709 growHungoffUses(ReservedSpace); 3710 } 3711 3712 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 3713 Instruction *InsertBefore) 3714 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr, 3715 nullptr, 0, InsertBefore) { 3716 init(Address, NumCases); 3717 } 3718 3719 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases, 3720 BasicBlock *InsertAtEnd) 3721 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr, 3722 nullptr, 0, InsertAtEnd) { 3723 init(Address, NumCases); 3724 } 3725 3726 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI) 3727 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr, 3728 nullptr, IBI.getNumOperands()) { 3729 allocHungoffUses(IBI.getNumOperands()); 3730 Use *OL = getOperandList(); 3731 const Use *InOL = IBI.getOperandList(); 3732 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i) 3733 OL[i] = InOL[i]; 3734 SubclassOptionalData = IBI.SubclassOptionalData; 3735 } 3736 3737 /// addDestination - Add a destination. 3738 /// 3739 void IndirectBrInst::addDestination(BasicBlock *DestBB) { 3740 unsigned OpNo = getNumOperands(); 3741 if (OpNo+1 > ReservedSpace) 3742 growOperands(); // Get more space! 3743 // Initialize some new operands. 3744 assert(OpNo < ReservedSpace && "Growing didn't work!"); 3745 setNumHungOffUseOperands(OpNo+1); 3746 getOperandList()[OpNo] = DestBB; 3747 } 3748 3749 /// removeDestination - This method removes the specified successor from the 3750 /// indirectbr instruction. 3751 void IndirectBrInst::removeDestination(unsigned idx) { 3752 assert(idx < getNumOperands()-1 && "Successor index out of range!"); 3753 3754 unsigned NumOps = getNumOperands(); 3755 Use *OL = getOperandList(); 3756 3757 // Replace this value with the last one. 3758 OL[idx+1] = OL[NumOps-1]; 3759 3760 // Nuke the last value. 3761 OL[NumOps-1].set(nullptr); 3762 setNumHungOffUseOperands(NumOps-1); 3763 } 3764 3765 //===----------------------------------------------------------------------===// 3766 // cloneImpl() implementations 3767 //===----------------------------------------------------------------------===// 3768 3769 // Define these methods here so vtables don't get emitted into every translation 3770 // unit that uses these classes. 3771 3772 GetElementPtrInst *GetElementPtrInst::cloneImpl() const { 3773 return new (getNumOperands()) GetElementPtrInst(*this); 3774 } 3775 3776 BinaryOperator *BinaryOperator::cloneImpl() const { 3777 return Create(getOpcode(), Op<0>(), Op<1>()); 3778 } 3779 3780 FCmpInst *FCmpInst::cloneImpl() const { 3781 return new FCmpInst(getPredicate(), Op<0>(), Op<1>()); 3782 } 3783 3784 ICmpInst *ICmpInst::cloneImpl() const { 3785 return new ICmpInst(getPredicate(), Op<0>(), Op<1>()); 3786 } 3787 3788 ExtractValueInst *ExtractValueInst::cloneImpl() const { 3789 return new ExtractValueInst(*this); 3790 } 3791 3792 InsertValueInst *InsertValueInst::cloneImpl() const { 3793 return new InsertValueInst(*this); 3794 } 3795 3796 AllocaInst *AllocaInst::cloneImpl() const { 3797 AllocaInst *Result = new AllocaInst(getAllocatedType(), 3798 getType()->getAddressSpace(), 3799 (Value *)getOperand(0), getAlignment()); 3800 Result->setUsedWithInAlloca(isUsedWithInAlloca()); 3801 Result->setSwiftError(isSwiftError()); 3802 return Result; 3803 } 3804 3805 LoadInst *LoadInst::cloneImpl() const { 3806 return new LoadInst(getOperand(0), Twine(), isVolatile(), 3807 getAlignment(), getOrdering(), getSynchScope()); 3808 } 3809 3810 StoreInst *StoreInst::cloneImpl() const { 3811 return new StoreInst(getOperand(0), getOperand(1), isVolatile(), 3812 getAlignment(), getOrdering(), getSynchScope()); 3813 3814 } 3815 3816 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const { 3817 AtomicCmpXchgInst *Result = 3818 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2), 3819 getSuccessOrdering(), getFailureOrdering(), 3820 getSynchScope()); 3821 Result->setVolatile(isVolatile()); 3822 Result->setWeak(isWeak()); 3823 return Result; 3824 } 3825 3826 AtomicRMWInst *AtomicRMWInst::cloneImpl() const { 3827 AtomicRMWInst *Result = 3828 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1), 3829 getOrdering(), getSynchScope()); 3830 Result->setVolatile(isVolatile()); 3831 return Result; 3832 } 3833 3834 FenceInst *FenceInst::cloneImpl() const { 3835 return new FenceInst(getContext(), getOrdering(), getSynchScope()); 3836 } 3837 3838 TruncInst *TruncInst::cloneImpl() const { 3839 return new TruncInst(getOperand(0), getType()); 3840 } 3841 3842 ZExtInst *ZExtInst::cloneImpl() const { 3843 return new ZExtInst(getOperand(0), getType()); 3844 } 3845 3846 SExtInst *SExtInst::cloneImpl() const { 3847 return new SExtInst(getOperand(0), getType()); 3848 } 3849 3850 FPTruncInst *FPTruncInst::cloneImpl() const { 3851 return new FPTruncInst(getOperand(0), getType()); 3852 } 3853 3854 FPExtInst *FPExtInst::cloneImpl() const { 3855 return new FPExtInst(getOperand(0), getType()); 3856 } 3857 3858 UIToFPInst *UIToFPInst::cloneImpl() const { 3859 return new UIToFPInst(getOperand(0), getType()); 3860 } 3861 3862 SIToFPInst *SIToFPInst::cloneImpl() const { 3863 return new SIToFPInst(getOperand(0), getType()); 3864 } 3865 3866 FPToUIInst *FPToUIInst::cloneImpl() const { 3867 return new FPToUIInst(getOperand(0), getType()); 3868 } 3869 3870 FPToSIInst *FPToSIInst::cloneImpl() const { 3871 return new FPToSIInst(getOperand(0), getType()); 3872 } 3873 3874 PtrToIntInst *PtrToIntInst::cloneImpl() const { 3875 return new PtrToIntInst(getOperand(0), getType()); 3876 } 3877 3878 IntToPtrInst *IntToPtrInst::cloneImpl() const { 3879 return new IntToPtrInst(getOperand(0), getType()); 3880 } 3881 3882 BitCastInst *BitCastInst::cloneImpl() const { 3883 return new BitCastInst(getOperand(0), getType()); 3884 } 3885 3886 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const { 3887 return new AddrSpaceCastInst(getOperand(0), getType()); 3888 } 3889 3890 CallInst *CallInst::cloneImpl() const { 3891 if (hasOperandBundles()) { 3892 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 3893 return new(getNumOperands(), DescriptorBytes) CallInst(*this); 3894 } 3895 return new(getNumOperands()) CallInst(*this); 3896 } 3897 3898 SelectInst *SelectInst::cloneImpl() const { 3899 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2)); 3900 } 3901 3902 VAArgInst *VAArgInst::cloneImpl() const { 3903 return new VAArgInst(getOperand(0), getType()); 3904 } 3905 3906 ExtractElementInst *ExtractElementInst::cloneImpl() const { 3907 return ExtractElementInst::Create(getOperand(0), getOperand(1)); 3908 } 3909 3910 InsertElementInst *InsertElementInst::cloneImpl() const { 3911 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2)); 3912 } 3913 3914 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const { 3915 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2)); 3916 } 3917 3918 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); } 3919 3920 LandingPadInst *LandingPadInst::cloneImpl() const { 3921 return new LandingPadInst(*this); 3922 } 3923 3924 ReturnInst *ReturnInst::cloneImpl() const { 3925 return new(getNumOperands()) ReturnInst(*this); 3926 } 3927 3928 BranchInst *BranchInst::cloneImpl() const { 3929 return new(getNumOperands()) BranchInst(*this); 3930 } 3931 3932 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); } 3933 3934 IndirectBrInst *IndirectBrInst::cloneImpl() const { 3935 return new IndirectBrInst(*this); 3936 } 3937 3938 InvokeInst *InvokeInst::cloneImpl() const { 3939 if (hasOperandBundles()) { 3940 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo); 3941 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this); 3942 } 3943 return new(getNumOperands()) InvokeInst(*this); 3944 } 3945 3946 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); } 3947 3948 CleanupReturnInst *CleanupReturnInst::cloneImpl() const { 3949 return new (getNumOperands()) CleanupReturnInst(*this); 3950 } 3951 3952 CatchReturnInst *CatchReturnInst::cloneImpl() const { 3953 return new (getNumOperands()) CatchReturnInst(*this); 3954 } 3955 3956 CatchSwitchInst *CatchSwitchInst::cloneImpl() const { 3957 return new CatchSwitchInst(*this); 3958 } 3959 3960 FuncletPadInst *FuncletPadInst::cloneImpl() const { 3961 return new (getNumOperands()) FuncletPadInst(*this); 3962 } 3963 3964 UnreachableInst *UnreachableInst::cloneImpl() const { 3965 LLVMContext &Context = getContext(); 3966 return new UnreachableInst(Context); 3967 } 3968