Instructions.cpp revision a276c603b82a11b0bf0b59f0517a69e4b63adeab
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 "LLVMContextImpl.h" 16#include "llvm/Constants.h" 17#include "llvm/DerivedTypes.h" 18#include "llvm/Function.h" 19#include "llvm/Instructions.h" 20#include "llvm/Module.h" 21#include "llvm/Operator.h" 22#include "llvm/Analysis/Dominators.h" 23#include "llvm/Support/ErrorHandling.h" 24#include "llvm/Support/CallSite.h" 25#include "llvm/Support/ConstantRange.h" 26#include "llvm/Support/MathExtras.h" 27 28using namespace llvm; 29 30//===----------------------------------------------------------------------===// 31// CallSite Class 32//===----------------------------------------------------------------------===// 33 34#define CALLSITE_DELEGATE_GETTER(METHOD) \ 35 Instruction *II(getInstruction()); \ 36 return isCall() \ 37 ? cast<CallInst>(II)->METHOD \ 38 : cast<InvokeInst>(II)->METHOD 39 40#define CALLSITE_DELEGATE_SETTER(METHOD) \ 41 Instruction *II(getInstruction()); \ 42 if (isCall()) \ 43 cast<CallInst>(II)->METHOD; \ 44 else \ 45 cast<InvokeInst>(II)->METHOD 46 47CallSite::CallSite(Instruction *C) { 48 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!"); 49 I.setPointer(C); 50 I.setInt(isa<CallInst>(C)); 51} 52CallingConv::ID CallSite::getCallingConv() const { 53 CALLSITE_DELEGATE_GETTER(getCallingConv()); 54} 55void CallSite::setCallingConv(CallingConv::ID CC) { 56 CALLSITE_DELEGATE_SETTER(setCallingConv(CC)); 57} 58const AttrListPtr &CallSite::getAttributes() const { 59 CALLSITE_DELEGATE_GETTER(getAttributes()); 60} 61void CallSite::setAttributes(const AttrListPtr &PAL) { 62 CALLSITE_DELEGATE_SETTER(setAttributes(PAL)); 63} 64bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const { 65 CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr)); 66} 67uint16_t CallSite::getParamAlignment(uint16_t i) const { 68 CALLSITE_DELEGATE_GETTER(getParamAlignment(i)); 69} 70bool CallSite::doesNotAccessMemory() const { 71 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory()); 72} 73void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) { 74 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory)); 75} 76bool CallSite::onlyReadsMemory() const { 77 CALLSITE_DELEGATE_GETTER(onlyReadsMemory()); 78} 79void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) { 80 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory)); 81} 82bool CallSite::doesNotReturn() const { 83 CALLSITE_DELEGATE_GETTER(doesNotReturn()); 84} 85void CallSite::setDoesNotReturn(bool doesNotReturn) { 86 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn)); 87} 88bool CallSite::doesNotThrow() const { 89 CALLSITE_DELEGATE_GETTER(doesNotThrow()); 90} 91void CallSite::setDoesNotThrow(bool doesNotThrow) { 92 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow)); 93} 94 95bool CallSite::hasArgument(const Value *Arg) const { 96 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI) 97 if (AI->get() == Arg) 98 return true; 99 return false; 100} 101 102#undef CALLSITE_DELEGATE_GETTER 103#undef CALLSITE_DELEGATE_SETTER 104 105//===----------------------------------------------------------------------===// 106// TerminatorInst Class 107//===----------------------------------------------------------------------===// 108 109// Out of line virtual method, so the vtable, etc has a home. 110TerminatorInst::~TerminatorInst() { 111} 112 113//===----------------------------------------------------------------------===// 114// UnaryInstruction Class 115//===----------------------------------------------------------------------===// 116 117// Out of line virtual method, so the vtable, etc has a home. 118UnaryInstruction::~UnaryInstruction() { 119} 120 121//===----------------------------------------------------------------------===// 122// SelectInst Class 123//===----------------------------------------------------------------------===// 124 125/// areInvalidOperands - Return a string if the specified operands are invalid 126/// for a select operation, otherwise return null. 127const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) { 128 if (Op1->getType() != Op2->getType()) 129 return "both values to select must have same type"; 130 131 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) { 132 // Vector select. 133 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext())) 134 return "vector select condition element type must be i1"; 135 const VectorType *ET = dyn_cast<VectorType>(Op1->getType()); 136 if (ET == 0) 137 return "selected values for vector select must be vectors"; 138 if (ET->getNumElements() != VT->getNumElements()) 139 return "vector select requires selected vectors to have " 140 "the same vector length as select condition"; 141 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) { 142 return "select condition must be i1 or <n x i1>"; 143 } 144 return 0; 145} 146 147 148//===----------------------------------------------------------------------===// 149// PHINode Class 150//===----------------------------------------------------------------------===// 151 152PHINode::PHINode(const PHINode &PN) 153 : Instruction(PN.getType(), Instruction::PHI, 154 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()), 155 ReservedSpace(PN.getNumOperands()) { 156 Use *OL = OperandList; 157 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) { 158 OL[i] = PN.getOperand(i); 159 OL[i+1] = PN.getOperand(i+1); 160 } 161 SubclassOptionalData = PN.SubclassOptionalData; 162} 163 164PHINode::~PHINode() { 165 if (OperandList) 166 dropHungoffUses(OperandList); 167} 168 169// removeIncomingValue - Remove an incoming value. This is useful if a 170// predecessor basic block is deleted. 171Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) { 172 unsigned NumOps = getNumOperands(); 173 Use *OL = OperandList; 174 assert(Idx*2 < NumOps && "BB not in PHI node!"); 175 Value *Removed = OL[Idx*2]; 176 177 // Move everything after this operand down. 178 // 179 // FIXME: we could just swap with the end of the list, then erase. However, 180 // client might not expect this to happen. The code as it is thrashes the 181 // use/def lists, which is kinda lame. 182 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) { 183 OL[i-2] = OL[i]; 184 OL[i-2+1] = OL[i+1]; 185 } 186 187 // Nuke the last value. 188 OL[NumOps-2].set(0); 189 OL[NumOps-2+1].set(0); 190 NumOperands = NumOps-2; 191 192 // If the PHI node is dead, because it has zero entries, nuke it now. 193 if (NumOps == 2 && DeletePHIIfEmpty) { 194 // If anyone is using this PHI, make them use a dummy value instead... 195 replaceAllUsesWith(UndefValue::get(getType())); 196 eraseFromParent(); 197 } 198 return Removed; 199} 200 201/// resizeOperands - resize operands - This adjusts the length of the operands 202/// list according to the following behavior: 203/// 1. If NumOps == 0, grow the operand list in response to a push_back style 204/// of operation. This grows the number of ops by 1.5 times. 205/// 2. If NumOps > NumOperands, reserve space for NumOps operands. 206/// 3. If NumOps == NumOperands, trim the reserved space. 207/// 208void PHINode::resizeOperands(unsigned NumOps) { 209 unsigned e = getNumOperands(); 210 if (NumOps == 0) { 211 NumOps = e*3/2; 212 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common. 213 } else if (NumOps*2 > NumOperands) { 214 // No resize needed. 215 if (ReservedSpace >= NumOps) return; 216 } else if (NumOps == NumOperands) { 217 if (ReservedSpace == NumOps) return; 218 } else { 219 return; 220 } 221 222 ReservedSpace = NumOps; 223 Use *OldOps = OperandList; 224 Use *NewOps = allocHungoffUses(NumOps); 225 std::copy(OldOps, OldOps + e, NewOps); 226 OperandList = NewOps; 227 if (OldOps) Use::zap(OldOps, OldOps + e, true); 228} 229 230/// hasConstantValue - If the specified PHI node always merges together the same 231/// value, return the value, otherwise return null. 232/// 233/// If the PHI has undef operands, but all the rest of the operands are 234/// some unique value, return that value if it can be proved that the 235/// value dominates the PHI. If DT is null, use a conservative check, 236/// otherwise use DT to test for dominance. 237/// 238Value *PHINode::hasConstantValue(DominatorTree *DT) const { 239 // If the PHI node only has one incoming value, eliminate the PHI node. 240 if (getNumIncomingValues() == 1) { 241 if (getIncomingValue(0) != this) // not X = phi X 242 return getIncomingValue(0); 243 return UndefValue::get(getType()); // Self cycle is dead. 244 } 245 246 // Otherwise if all of the incoming values are the same for the PHI, replace 247 // the PHI node with the incoming value. 248 // 249 Value *InVal = 0; 250 bool HasUndefInput = false; 251 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) 252 if (isa<UndefValue>(getIncomingValue(i))) { 253 HasUndefInput = true; 254 } else if (getIncomingValue(i) != this) { // Not the PHI node itself... 255 if (InVal && getIncomingValue(i) != InVal) 256 return 0; // Not the same, bail out. 257 InVal = getIncomingValue(i); 258 } 259 260 // The only case that could cause InVal to be null is if we have a PHI node 261 // that only has entries for itself. In this case, there is no entry into the 262 // loop, so kill the PHI. 263 // 264 if (InVal == 0) InVal = UndefValue::get(getType()); 265 266 // If we have a PHI node like phi(X, undef, X), where X is defined by some 267 // instruction, we cannot always return X as the result of the PHI node. Only 268 // do this if X is not an instruction (thus it must dominate the PHI block), 269 // or if the client is prepared to deal with this possibility. 270 if (!HasUndefInput || !isa<Instruction>(InVal)) 271 return InVal; 272 273 Instruction *IV = cast<Instruction>(InVal); 274 if (DT) { 275 // We have a DominatorTree. Do a precise test. 276 if (!DT->dominates(IV, this)) 277 return 0; 278 } else { 279 // If it is in the entry block, it obviously dominates everything. 280 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() || 281 isa<InvokeInst>(IV)) 282 return 0; // Cannot guarantee that InVal dominates this PHINode. 283 } 284 285 // All of the incoming values are the same, return the value now. 286 return InVal; 287} 288 289 290//===----------------------------------------------------------------------===// 291// CallInst Implementation 292//===----------------------------------------------------------------------===// 293 294CallInst::~CallInst() { 295} 296 297void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) { 298 assert(NumOperands == NumParams+1 && "NumOperands not set up?"); 299 Use *OL = OperandList; 300 OL[0] = Func; 301 302 const FunctionType *FTy = 303 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); 304 FTy = FTy; // silence warning. 305 306 assert((NumParams == FTy->getNumParams() || 307 (FTy->isVarArg() && NumParams > FTy->getNumParams())) && 308 "Calling a function with bad signature!"); 309 for (unsigned i = 0; i != NumParams; ++i) { 310 assert((i >= FTy->getNumParams() || 311 FTy->getParamType(i) == Params[i]->getType()) && 312 "Calling a function with a bad signature!"); 313 OL[i+1] = Params[i]; 314 } 315} 316 317void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) { 318 assert(NumOperands == 3 && "NumOperands not set up?"); 319 Use *OL = OperandList; 320 OL[0] = Func; 321 OL[1] = Actual1; 322 OL[2] = Actual2; 323 324 const FunctionType *FTy = 325 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); 326 FTy = FTy; // silence warning. 327 328 assert((FTy->getNumParams() == 2 || 329 (FTy->isVarArg() && FTy->getNumParams() < 2)) && 330 "Calling a function with bad signature"); 331 assert((0 >= FTy->getNumParams() || 332 FTy->getParamType(0) == Actual1->getType()) && 333 "Calling a function with a bad signature!"); 334 assert((1 >= FTy->getNumParams() || 335 FTy->getParamType(1) == Actual2->getType()) && 336 "Calling a function with a bad signature!"); 337} 338 339void CallInst::init(Value *Func, Value *Actual) { 340 assert(NumOperands == 2 && "NumOperands not set up?"); 341 Use *OL = OperandList; 342 OL[0] = Func; 343 OL[1] = Actual; 344 345 const FunctionType *FTy = 346 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); 347 FTy = FTy; // silence warning. 348 349 assert((FTy->getNumParams() == 1 || 350 (FTy->isVarArg() && FTy->getNumParams() == 0)) && 351 "Calling a function with bad signature"); 352 assert((0 == FTy->getNumParams() || 353 FTy->getParamType(0) == Actual->getType()) && 354 "Calling a function with a bad signature!"); 355} 356 357void CallInst::init(Value *Func) { 358 assert(NumOperands == 1 && "NumOperands not set up?"); 359 Use *OL = OperandList; 360 OL[0] = Func; 361 362 const FunctionType *FTy = 363 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType()); 364 FTy = FTy; // silence warning. 365 366 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature"); 367} 368 369CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name, 370 Instruction *InsertBefore) 371 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 372 ->getElementType())->getReturnType(), 373 Instruction::Call, 374 OperandTraits<CallInst>::op_end(this) - 2, 375 2, InsertBefore) { 376 init(Func, Actual); 377 setName(Name); 378} 379 380CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name, 381 BasicBlock *InsertAtEnd) 382 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 383 ->getElementType())->getReturnType(), 384 Instruction::Call, 385 OperandTraits<CallInst>::op_end(this) - 2, 386 2, InsertAtEnd) { 387 init(Func, Actual); 388 setName(Name); 389} 390CallInst::CallInst(Value *Func, const Twine &Name, 391 Instruction *InsertBefore) 392 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 393 ->getElementType())->getReturnType(), 394 Instruction::Call, 395 OperandTraits<CallInst>::op_end(this) - 1, 396 1, InsertBefore) { 397 init(Func); 398 setName(Name); 399} 400 401CallInst::CallInst(Value *Func, const Twine &Name, 402 BasicBlock *InsertAtEnd) 403 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType()) 404 ->getElementType())->getReturnType(), 405 Instruction::Call, 406 OperandTraits<CallInst>::op_end(this) - 1, 407 1, InsertAtEnd) { 408 init(Func); 409 setName(Name); 410} 411 412CallInst::CallInst(const CallInst &CI) 413 : Instruction(CI.getType(), Instruction::Call, 414 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(), 415 CI.getNumOperands()) { 416 setAttributes(CI.getAttributes()); 417 SubclassData = CI.SubclassData; 418 Use *OL = OperandList; 419 Use *InOL = CI.OperandList; 420 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i) 421 OL[i] = InOL[i]; 422 SubclassOptionalData = CI.SubclassOptionalData; 423} 424 425void CallInst::addAttribute(unsigned i, Attributes attr) { 426 AttrListPtr PAL = getAttributes(); 427 PAL = PAL.addAttr(i, attr); 428 setAttributes(PAL); 429} 430 431void CallInst::removeAttribute(unsigned i, Attributes attr) { 432 AttrListPtr PAL = getAttributes(); 433 PAL = PAL.removeAttr(i, attr); 434 setAttributes(PAL); 435} 436 437bool CallInst::paramHasAttr(unsigned i, Attributes attr) const { 438 if (AttributeList.paramHasAttr(i, attr)) 439 return true; 440 if (const Function *F = getCalledFunction()) 441 return F->paramHasAttr(i, attr); 442 return false; 443} 444 445/// IsConstantOne - Return true only if val is constant int 1 446static bool IsConstantOne(Value *val) { 447 assert(val && "IsConstantOne does not work with NULL val"); 448 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne(); 449} 450 451static Value *checkArraySize(Value *Amt, const Type *IntPtrTy) { 452 if (!Amt) 453 Amt = ConstantInt::get(IntPtrTy, 1); 454 else { 455 assert(!isa<BasicBlock>(Amt) && 456 "Passed basic block into malloc size parameter! Use other ctor"); 457 assert(Amt->getType() == IntPtrTy && 458 "Malloc array size is not an intptr!"); 459 } 460 return Amt; 461} 462 463static Value *createMalloc(Instruction *InsertBefore, BasicBlock *InsertAtEnd, 464 const Type *IntPtrTy, const Type *AllocTy, 465 Value *ArraySize, Function* MallocF, 466 const Twine &NameStr) { 467 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) && 468 "createMalloc needs either InsertBefore or InsertAtEnd"); 469 470 // malloc(type) becomes: 471 // bitcast (i8* malloc(typeSize)) to type* 472 // malloc(type, arraySize) becomes: 473 // bitcast (i8 *malloc(typeSize*arraySize)) to type* 474 Value *AllocSize = ConstantExpr::getSizeOf(AllocTy); 475 AllocSize = ConstantExpr::getTruncOrBitCast(cast<Constant>(AllocSize), 476 IntPtrTy); 477 ArraySize = checkArraySize(ArraySize, IntPtrTy); 478 479 if (!IsConstantOne(ArraySize)) { 480 if (IsConstantOne(AllocSize)) { 481 AllocSize = ArraySize; // Operand * 1 = Operand 482 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) { 483 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy, 484 false /*ZExt*/); 485 // Malloc arg is constant product of type size and array size 486 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize)); 487 } else { 488 // Multiply type size by the array size... 489 if (InsertBefore) 490 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 491 "mallocsize", InsertBefore); 492 else 493 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize, 494 "mallocsize", InsertAtEnd); 495 } 496 } 497 498 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size"); 499 // Create the call to Malloc. 500 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd; 501 Module* M = BB->getParent()->getParent(); 502 const Type *BPTy = Type::getInt8PtrTy(BB->getContext()); 503 if (!MallocF) 504 // prototype malloc as "void *malloc(size_t)" 505 MallocF = cast<Function>(M->getOrInsertFunction("malloc", BPTy, 506 IntPtrTy, NULL)); 507 if (!MallocF->doesNotAlias(0)) MallocF->setDoesNotAlias(0); 508 const PointerType *AllocPtrType = PointerType::getUnqual(AllocTy); 509 CallInst *MCall = NULL; 510 Value *Result = NULL; 511 if (InsertBefore) { 512 MCall = CallInst::Create(MallocF, AllocSize, "malloccall", InsertBefore); 513 Result = MCall; 514 if (Result->getType() != AllocPtrType) 515 // Create a cast instruction to convert to the right type... 516 Result = new BitCastInst(MCall, AllocPtrType, NameStr, InsertBefore); 517 } else { 518 MCall = CallInst::Create(MallocF, AllocSize, "malloccall"); 519 Result = MCall; 520 if (Result->getType() != AllocPtrType) { 521 InsertAtEnd->getInstList().push_back(MCall); 522 // Create a cast instruction to convert to the right type... 523 Result = new BitCastInst(MCall, AllocPtrType, NameStr); 524 } 525 } 526 MCall->setTailCall(); 527 assert(MCall->getType() != Type::getVoidTy(BB->getContext()) && 528 "Malloc has void return type"); 529 530 return Result; 531} 532 533/// CreateMalloc - Generate the IR for a call to malloc: 534/// 1. Compute the malloc call's argument as the specified type's size, 535/// possibly multiplied by the array size if the array size is not 536/// constant 1. 537/// 2. Call malloc with that argument. 538/// 3. Bitcast the result of the malloc call to the specified type. 539Value *CallInst::CreateMalloc(Instruction *InsertBefore, const Type *IntPtrTy, 540 const Type *AllocTy, Value *ArraySize, 541 const Twine &Name) { 542 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, 543 ArraySize, NULL, Name); 544} 545 546/// CreateMalloc - Generate the IR for a call to malloc: 547/// 1. Compute the malloc call's argument as the specified type's size, 548/// possibly multiplied by the array size if the array size is not 549/// constant 1. 550/// 2. Call malloc with that argument. 551/// 3. Bitcast the result of the malloc call to the specified type. 552/// Note: This function does not add the bitcast to the basic block, that is the 553/// responsibility of the caller. 554Value *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, const Type *IntPtrTy, 555 const Type *AllocTy, Value *ArraySize, 556 Function* MallocF, const Twine &Name) { 557 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, 558 ArraySize, MallocF, Name); 559} 560 561//===----------------------------------------------------------------------===// 562// InvokeInst Implementation 563//===----------------------------------------------------------------------===// 564 565void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException, 566 Value* const *Args, unsigned NumArgs) { 567 assert(NumOperands == 3+NumArgs && "NumOperands not set up?"); 568 Use *OL = OperandList; 569 OL[0] = Fn; 570 OL[1] = IfNormal; 571 OL[2] = IfException; 572 const FunctionType *FTy = 573 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType()); 574 FTy = FTy; // silence warning. 575 576 assert(((NumArgs == FTy->getNumParams()) || 577 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) && 578 "Calling a function with bad signature"); 579 580 for (unsigned i = 0, e = NumArgs; i != e; i++) { 581 assert((i >= FTy->getNumParams() || 582 FTy->getParamType(i) == Args[i]->getType()) && 583 "Invoking a function with a bad signature!"); 584 585 OL[i+3] = Args[i]; 586 } 587} 588 589InvokeInst::InvokeInst(const InvokeInst &II) 590 : TerminatorInst(II.getType(), Instruction::Invoke, 591 OperandTraits<InvokeInst>::op_end(this) 592 - II.getNumOperands(), 593 II.getNumOperands()) { 594 setAttributes(II.getAttributes()); 595 SubclassData = II.SubclassData; 596 Use *OL = OperandList, *InOL = II.OperandList; 597 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i) 598 OL[i] = InOL[i]; 599 SubclassOptionalData = II.SubclassOptionalData; 600} 601 602BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const { 603 return getSuccessor(idx); 604} 605unsigned InvokeInst::getNumSuccessorsV() const { 606 return getNumSuccessors(); 607} 608void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) { 609 return setSuccessor(idx, B); 610} 611 612bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const { 613 if (AttributeList.paramHasAttr(i, attr)) 614 return true; 615 if (const Function *F = getCalledFunction()) 616 return F->paramHasAttr(i, attr); 617 return false; 618} 619 620void InvokeInst::addAttribute(unsigned i, Attributes attr) { 621 AttrListPtr PAL = getAttributes(); 622 PAL = PAL.addAttr(i, attr); 623 setAttributes(PAL); 624} 625 626void InvokeInst::removeAttribute(unsigned i, Attributes attr) { 627 AttrListPtr PAL = getAttributes(); 628 PAL = PAL.removeAttr(i, attr); 629 setAttributes(PAL); 630} 631 632 633//===----------------------------------------------------------------------===// 634// ReturnInst Implementation 635//===----------------------------------------------------------------------===// 636 637ReturnInst::ReturnInst(const ReturnInst &RI) 638 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret, 639 OperandTraits<ReturnInst>::op_end(this) - 640 RI.getNumOperands(), 641 RI.getNumOperands()) { 642 if (RI.getNumOperands()) 643 Op<0>() = RI.Op<0>(); 644 SubclassOptionalData = RI.SubclassOptionalData; 645} 646 647ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore) 648 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret, 649 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 650 InsertBefore) { 651 if (retVal) 652 Op<0>() = retVal; 653} 654ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd) 655 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret, 656 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal, 657 InsertAtEnd) { 658 if (retVal) 659 Op<0>() = retVal; 660} 661ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 662 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret, 663 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) { 664} 665 666unsigned ReturnInst::getNumSuccessorsV() const { 667 return getNumSuccessors(); 668} 669 670/// Out-of-line ReturnInst method, put here so the C++ compiler can choose to 671/// emit the vtable for the class in this translation unit. 672void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { 673 llvm_unreachable("ReturnInst has no successors!"); 674} 675 676BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const { 677 llvm_unreachable("ReturnInst has no successors!"); 678 return 0; 679} 680 681ReturnInst::~ReturnInst() { 682} 683 684//===----------------------------------------------------------------------===// 685// UnwindInst Implementation 686//===----------------------------------------------------------------------===// 687 688UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore) 689 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind, 690 0, 0, InsertBefore) { 691} 692UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 693 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind, 694 0, 0, InsertAtEnd) { 695} 696 697 698unsigned UnwindInst::getNumSuccessorsV() const { 699 return getNumSuccessors(); 700} 701 702void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { 703 llvm_unreachable("UnwindInst has no successors!"); 704} 705 706BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const { 707 llvm_unreachable("UnwindInst has no successors!"); 708 return 0; 709} 710 711//===----------------------------------------------------------------------===// 712// UnreachableInst Implementation 713//===----------------------------------------------------------------------===// 714 715UnreachableInst::UnreachableInst(LLVMContext &Context, 716 Instruction *InsertBefore) 717 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable, 718 0, 0, InsertBefore) { 719} 720UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd) 721 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable, 722 0, 0, InsertAtEnd) { 723} 724 725unsigned UnreachableInst::getNumSuccessorsV() const { 726 return getNumSuccessors(); 727} 728 729void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) { 730 llvm_unreachable("UnwindInst has no successors!"); 731} 732 733BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const { 734 llvm_unreachable("UnwindInst has no successors!"); 735 return 0; 736} 737 738//===----------------------------------------------------------------------===// 739// BranchInst Implementation 740//===----------------------------------------------------------------------===// 741 742void BranchInst::AssertOK() { 743 if (isConditional()) 744 assert(getCondition()->getType() == Type::getInt1Ty(getContext()) && 745 "May only branch on boolean predicates!"); 746} 747 748BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore) 749 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 750 OperandTraits<BranchInst>::op_end(this) - 1, 751 1, InsertBefore) { 752 assert(IfTrue != 0 && "Branch destination may not be null!"); 753 Op<-1>() = IfTrue; 754} 755BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 756 Instruction *InsertBefore) 757 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 758 OperandTraits<BranchInst>::op_end(this) - 3, 759 3, InsertBefore) { 760 Op<-1>() = IfTrue; 761 Op<-2>() = IfFalse; 762 Op<-3>() = Cond; 763#ifndef NDEBUG 764 AssertOK(); 765#endif 766} 767 768BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) 769 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 770 OperandTraits<BranchInst>::op_end(this) - 1, 771 1, InsertAtEnd) { 772 assert(IfTrue != 0 && "Branch destination may not be null!"); 773 Op<-1>() = IfTrue; 774} 775 776BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond, 777 BasicBlock *InsertAtEnd) 778 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br, 779 OperandTraits<BranchInst>::op_end(this) - 3, 780 3, InsertAtEnd) { 781 Op<-1>() = IfTrue; 782 Op<-2>() = IfFalse; 783 Op<-3>() = Cond; 784#ifndef NDEBUG 785 AssertOK(); 786#endif 787} 788 789 790BranchInst::BranchInst(const BranchInst &BI) : 791 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br, 792 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(), 793 BI.getNumOperands()) { 794 Op<-1>() = BI.Op<-1>(); 795 if (BI.getNumOperands() != 1) { 796 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!"); 797 Op<-3>() = BI.Op<-3>(); 798 Op<-2>() = BI.Op<-2>(); 799 } 800 SubclassOptionalData = BI.SubclassOptionalData; 801} 802 803 804Use* Use::getPrefix() { 805 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev); 806 if (PotentialPrefix.getOpaqueValue()) 807 return 0; 808 809 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1); 810} 811 812BranchInst::~BranchInst() { 813 if (NumOperands == 1) { 814 if (Use *Prefix = OperandList->getPrefix()) { 815 Op<-1>() = 0; 816 // 817 // mark OperandList to have a special value for scrutiny 818 // by baseclass destructors and operator delete 819 OperandList = Prefix; 820 } else { 821 NumOperands = 3; 822 OperandList = op_begin(); 823 } 824 } 825} 826 827 828BasicBlock *BranchInst::getSuccessorV(unsigned idx) const { 829 return getSuccessor(idx); 830} 831unsigned BranchInst::getNumSuccessorsV() const { 832 return getNumSuccessors(); 833} 834void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) { 835 setSuccessor(idx, B); 836} 837 838 839//===----------------------------------------------------------------------===// 840// AllocationInst Implementation 841//===----------------------------------------------------------------------===// 842 843static Value *getAISize(LLVMContext &Context, Value *Amt) { 844 if (!Amt) 845 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1); 846 else { 847 assert(!isa<BasicBlock>(Amt) && 848 "Passed basic block into allocation size parameter! Use other ctor"); 849 assert(Amt->getType() == Type::getInt32Ty(Context) && 850 "Allocation array size is not a 32-bit integer!"); 851 } 852 return Amt; 853} 854 855AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy, 856 unsigned Align, const Twine &Name, 857 Instruction *InsertBefore) 858 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, 859 getAISize(Ty->getContext(), ArraySize), InsertBefore) { 860 setAlignment(Align); 861 assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!"); 862 setName(Name); 863} 864 865AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy, 866 unsigned Align, const Twine &Name, 867 BasicBlock *InsertAtEnd) 868 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, 869 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) { 870 setAlignment(Align); 871 assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!"); 872 setName(Name); 873} 874 875// Out of line virtual method, so the vtable, etc has a home. 876AllocationInst::~AllocationInst() { 877} 878 879void AllocationInst::setAlignment(unsigned Align) { 880 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 881 SubclassData = Log2_32(Align) + 1; 882 assert(getAlignment() == Align && "Alignment representation error!"); 883} 884 885bool AllocationInst::isArrayAllocation() const { 886 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0))) 887 return CI->getZExtValue() != 1; 888 return true; 889} 890 891const Type *AllocationInst::getAllocatedType() const { 892 return getType()->getElementType(); 893} 894 895/// isStaticAlloca - Return true if this alloca is in the entry block of the 896/// function and is a constant size. If so, the code generator will fold it 897/// into the prolog/epilog code, so it is basically free. 898bool AllocaInst::isStaticAlloca() const { 899 // Must be constant size. 900 if (!isa<ConstantInt>(getArraySize())) return false; 901 902 // Must be in the entry block. 903 const BasicBlock *Parent = getParent(); 904 return Parent == &Parent->getParent()->front(); 905} 906 907//===----------------------------------------------------------------------===// 908// FreeInst Implementation 909//===----------------------------------------------------------------------===// 910 911void FreeInst::AssertOK() { 912 assert(isa<PointerType>(getOperand(0)->getType()) && 913 "Can not free something of nonpointer type!"); 914} 915 916FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore) 917 : UnaryInstruction(Type::getVoidTy(Ptr->getContext()), 918 Free, Ptr, InsertBefore) { 919 AssertOK(); 920} 921 922FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd) 923 : UnaryInstruction(Type::getVoidTy(Ptr->getContext()), 924 Free, Ptr, InsertAtEnd) { 925 AssertOK(); 926} 927 928 929//===----------------------------------------------------------------------===// 930// LoadInst Implementation 931//===----------------------------------------------------------------------===// 932 933void LoadInst::AssertOK() { 934 assert(isa<PointerType>(getOperand(0)->getType()) && 935 "Ptr must have pointer type."); 936} 937 938LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef) 939 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 940 Load, Ptr, InsertBef) { 941 setVolatile(false); 942 setAlignment(0); 943 AssertOK(); 944 setName(Name); 945} 946 947LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE) 948 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 949 Load, Ptr, InsertAE) { 950 setVolatile(false); 951 setAlignment(0); 952 AssertOK(); 953 setName(Name); 954} 955 956LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 957 Instruction *InsertBef) 958 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 959 Load, Ptr, InsertBef) { 960 setVolatile(isVolatile); 961 setAlignment(0); 962 AssertOK(); 963 setName(Name); 964} 965 966LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 967 unsigned Align, Instruction *InsertBef) 968 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 969 Load, Ptr, InsertBef) { 970 setVolatile(isVolatile); 971 setAlignment(Align); 972 AssertOK(); 973 setName(Name); 974} 975 976LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 977 unsigned Align, BasicBlock *InsertAE) 978 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 979 Load, Ptr, InsertAE) { 980 setVolatile(isVolatile); 981 setAlignment(Align); 982 AssertOK(); 983 setName(Name); 984} 985 986LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 987 BasicBlock *InsertAE) 988 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 989 Load, Ptr, InsertAE) { 990 setVolatile(isVolatile); 991 setAlignment(0); 992 AssertOK(); 993 setName(Name); 994} 995 996 997 998LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef) 999 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1000 Load, Ptr, InsertBef) { 1001 setVolatile(false); 1002 setAlignment(0); 1003 AssertOK(); 1004 if (Name && Name[0]) setName(Name); 1005} 1006 1007LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE) 1008 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1009 Load, Ptr, InsertAE) { 1010 setVolatile(false); 1011 setAlignment(0); 1012 AssertOK(); 1013 if (Name && Name[0]) setName(Name); 1014} 1015 1016LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile, 1017 Instruction *InsertBef) 1018: UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1019 Load, Ptr, InsertBef) { 1020 setVolatile(isVolatile); 1021 setAlignment(0); 1022 AssertOK(); 1023 if (Name && Name[0]) setName(Name); 1024} 1025 1026LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile, 1027 BasicBlock *InsertAE) 1028 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(), 1029 Load, Ptr, InsertAE) { 1030 setVolatile(isVolatile); 1031 setAlignment(0); 1032 AssertOK(); 1033 if (Name && Name[0]) setName(Name); 1034} 1035 1036void LoadInst::setAlignment(unsigned Align) { 1037 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1038 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1); 1039} 1040 1041//===----------------------------------------------------------------------===// 1042// StoreInst Implementation 1043//===----------------------------------------------------------------------===// 1044 1045void StoreInst::AssertOK() { 1046 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!"); 1047 assert(isa<PointerType>(getOperand(1)->getType()) && 1048 "Ptr must have pointer type!"); 1049 assert(getOperand(0)->getType() == 1050 cast<PointerType>(getOperand(1)->getType())->getElementType() 1051 && "Ptr must be a pointer to Val type!"); 1052} 1053 1054 1055StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore) 1056 : Instruction(Type::getVoidTy(val->getContext()), Store, 1057 OperandTraits<StoreInst>::op_begin(this), 1058 OperandTraits<StoreInst>::operands(this), 1059 InsertBefore) { 1060 Op<0>() = val; 1061 Op<1>() = addr; 1062 setVolatile(false); 1063 setAlignment(0); 1064 AssertOK(); 1065} 1066 1067StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd) 1068 : Instruction(Type::getVoidTy(val->getContext()), Store, 1069 OperandTraits<StoreInst>::op_begin(this), 1070 OperandTraits<StoreInst>::operands(this), 1071 InsertAtEnd) { 1072 Op<0>() = val; 1073 Op<1>() = addr; 1074 setVolatile(false); 1075 setAlignment(0); 1076 AssertOK(); 1077} 1078 1079StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1080 Instruction *InsertBefore) 1081 : Instruction(Type::getVoidTy(val->getContext()), Store, 1082 OperandTraits<StoreInst>::op_begin(this), 1083 OperandTraits<StoreInst>::operands(this), 1084 InsertBefore) { 1085 Op<0>() = val; 1086 Op<1>() = addr; 1087 setVolatile(isVolatile); 1088 setAlignment(0); 1089 AssertOK(); 1090} 1091 1092StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1093 unsigned Align, Instruction *InsertBefore) 1094 : Instruction(Type::getVoidTy(val->getContext()), Store, 1095 OperandTraits<StoreInst>::op_begin(this), 1096 OperandTraits<StoreInst>::operands(this), 1097 InsertBefore) { 1098 Op<0>() = val; 1099 Op<1>() = addr; 1100 setVolatile(isVolatile); 1101 setAlignment(Align); 1102 AssertOK(); 1103} 1104 1105StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1106 unsigned Align, BasicBlock *InsertAtEnd) 1107 : Instruction(Type::getVoidTy(val->getContext()), Store, 1108 OperandTraits<StoreInst>::op_begin(this), 1109 OperandTraits<StoreInst>::operands(this), 1110 InsertAtEnd) { 1111 Op<0>() = val; 1112 Op<1>() = addr; 1113 setVolatile(isVolatile); 1114 setAlignment(Align); 1115 AssertOK(); 1116} 1117 1118StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, 1119 BasicBlock *InsertAtEnd) 1120 : Instruction(Type::getVoidTy(val->getContext()), Store, 1121 OperandTraits<StoreInst>::op_begin(this), 1122 OperandTraits<StoreInst>::operands(this), 1123 InsertAtEnd) { 1124 Op<0>() = val; 1125 Op<1>() = addr; 1126 setVolatile(isVolatile); 1127 setAlignment(0); 1128 AssertOK(); 1129} 1130 1131void StoreInst::setAlignment(unsigned Align) { 1132 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!"); 1133 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1); 1134} 1135 1136//===----------------------------------------------------------------------===// 1137// GetElementPtrInst Implementation 1138//===----------------------------------------------------------------------===// 1139 1140static unsigned retrieveAddrSpace(const Value *Val) { 1141 return cast<PointerType>(Val->getType())->getAddressSpace(); 1142} 1143 1144void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx, 1145 const Twine &Name) { 1146 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?"); 1147 Use *OL = OperandList; 1148 OL[0] = Ptr; 1149 1150 for (unsigned i = 0; i != NumIdx; ++i) 1151 OL[i+1] = Idx[i]; 1152 1153 setName(Name); 1154} 1155 1156void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) { 1157 assert(NumOperands == 2 && "NumOperands not initialized?"); 1158 Use *OL = OperandList; 1159 OL[0] = Ptr; 1160 OL[1] = Idx; 1161 1162 setName(Name); 1163} 1164 1165GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI) 1166 : Instruction(GEPI.getType(), GetElementPtr, 1167 OperandTraits<GetElementPtrInst>::op_end(this) 1168 - GEPI.getNumOperands(), 1169 GEPI.getNumOperands()) { 1170 Use *OL = OperandList; 1171 Use *GEPIOL = GEPI.OperandList; 1172 for (unsigned i = 0, E = NumOperands; i != E; ++i) 1173 OL[i] = GEPIOL[i]; 1174 SubclassOptionalData = GEPI.SubclassOptionalData; 1175} 1176 1177GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx, 1178 const Twine &Name, Instruction *InBe) 1179 : Instruction(PointerType::get( 1180 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)), 1181 GetElementPtr, 1182 OperandTraits<GetElementPtrInst>::op_end(this) - 2, 1183 2, InBe) { 1184 init(Ptr, Idx, Name); 1185} 1186 1187GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx, 1188 const Twine &Name, BasicBlock *IAE) 1189 : Instruction(PointerType::get( 1190 checkType(getIndexedType(Ptr->getType(),Idx)), 1191 retrieveAddrSpace(Ptr)), 1192 GetElementPtr, 1193 OperandTraits<GetElementPtrInst>::op_end(this) - 2, 1194 2, IAE) { 1195 init(Ptr, Idx, Name); 1196} 1197 1198/// getIndexedType - Returns the type of the element that would be accessed with 1199/// a gep instruction with the specified parameters. 1200/// 1201/// The Idxs pointer should point to a continuous piece of memory containing the 1202/// indices, either as Value* or uint64_t. 1203/// 1204/// A null type is returned if the indices are invalid for the specified 1205/// pointer type. 1206/// 1207template <typename IndexTy> 1208static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs, 1209 unsigned NumIdx) { 1210 const PointerType *PTy = dyn_cast<PointerType>(Ptr); 1211 if (!PTy) return 0; // Type isn't a pointer type! 1212 const Type *Agg = PTy->getElementType(); 1213 1214 // Handle the special case of the empty set index set, which is always valid. 1215 if (NumIdx == 0) 1216 return Agg; 1217 1218 // If there is at least one index, the top level type must be sized, otherwise 1219 // it cannot be 'stepped over'. We explicitly allow abstract types (those 1220 // that contain opaque types) under the assumption that it will be resolved to 1221 // a sane type later. 1222 if (!Agg->isSized() && !Agg->isAbstract()) 1223 return 0; 1224 1225 unsigned CurIdx = 1; 1226 for (; CurIdx != NumIdx; ++CurIdx) { 1227 const CompositeType *CT = dyn_cast<CompositeType>(Agg); 1228 if (!CT || isa<PointerType>(CT)) return 0; 1229 IndexTy Index = Idxs[CurIdx]; 1230 if (!CT->indexValid(Index)) return 0; 1231 Agg = CT->getTypeAtIndex(Index); 1232 1233 // If the new type forwards to another type, then it is in the middle 1234 // of being refined to another type (and hence, may have dropped all 1235 // references to what it was using before). So, use the new forwarded 1236 // type. 1237 if (const Type *Ty = Agg->getForwardedType()) 1238 Agg = Ty; 1239 } 1240 return CurIdx == NumIdx ? Agg : 0; 1241} 1242 1243const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, 1244 Value* const *Idxs, 1245 unsigned NumIdx) { 1246 return getIndexedTypeInternal(Ptr, Idxs, NumIdx); 1247} 1248 1249const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, 1250 uint64_t const *Idxs, 1251 unsigned NumIdx) { 1252 return getIndexedTypeInternal(Ptr, Idxs, NumIdx); 1253} 1254 1255const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) { 1256 const PointerType *PTy = dyn_cast<PointerType>(Ptr); 1257 if (!PTy) return 0; // Type isn't a pointer type! 1258 1259 // Check the pointer index. 1260 if (!PTy->indexValid(Idx)) return 0; 1261 1262 return PTy->getElementType(); 1263} 1264 1265 1266/// hasAllZeroIndices - Return true if all of the indices of this GEP are 1267/// zeros. If so, the result pointer and the first operand have the same 1268/// value, just potentially different types. 1269bool GetElementPtrInst::hasAllZeroIndices() const { 1270 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1271 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) { 1272 if (!CI->isZero()) return false; 1273 } else { 1274 return false; 1275 } 1276 } 1277 return true; 1278} 1279 1280/// hasAllConstantIndices - Return true if all of the indices of this GEP are 1281/// constant integers. If so, the result pointer and the first operand have 1282/// a constant offset between them. 1283bool GetElementPtrInst::hasAllConstantIndices() const { 1284 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) { 1285 if (!isa<ConstantInt>(getOperand(i))) 1286 return false; 1287 } 1288 return true; 1289} 1290 1291void GetElementPtrInst::setIsInBounds(bool B) { 1292 cast<GEPOperator>(this)->setIsInBounds(B); 1293} 1294 1295bool GetElementPtrInst::isInBounds() const { 1296 return cast<GEPOperator>(this)->isInBounds(); 1297} 1298 1299//===----------------------------------------------------------------------===// 1300// ExtractElementInst Implementation 1301//===----------------------------------------------------------------------===// 1302 1303ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1304 const Twine &Name, 1305 Instruction *InsertBef) 1306 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1307 ExtractElement, 1308 OperandTraits<ExtractElementInst>::op_begin(this), 1309 2, InsertBef) { 1310 assert(isValidOperands(Val, Index) && 1311 "Invalid extractelement instruction operands!"); 1312 Op<0>() = Val; 1313 Op<1>() = Index; 1314 setName(Name); 1315} 1316 1317ExtractElementInst::ExtractElementInst(Value *Val, Value *Index, 1318 const Twine &Name, 1319 BasicBlock *InsertAE) 1320 : Instruction(cast<VectorType>(Val->getType())->getElementType(), 1321 ExtractElement, 1322 OperandTraits<ExtractElementInst>::op_begin(this), 1323 2, InsertAE) { 1324 assert(isValidOperands(Val, Index) && 1325 "Invalid extractelement instruction operands!"); 1326 1327 Op<0>() = Val; 1328 Op<1>() = Index; 1329 setName(Name); 1330} 1331 1332 1333bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) { 1334 if (!isa<VectorType>(Val->getType()) || 1335 Index->getType() != Type::getInt32Ty(Val->getContext())) 1336 return false; 1337 return true; 1338} 1339 1340 1341//===----------------------------------------------------------------------===// 1342// InsertElementInst Implementation 1343//===----------------------------------------------------------------------===// 1344 1345InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1346 const Twine &Name, 1347 Instruction *InsertBef) 1348 : Instruction(Vec->getType(), InsertElement, 1349 OperandTraits<InsertElementInst>::op_begin(this), 1350 3, InsertBef) { 1351 assert(isValidOperands(Vec, Elt, Index) && 1352 "Invalid insertelement instruction operands!"); 1353 Op<0>() = Vec; 1354 Op<1>() = Elt; 1355 Op<2>() = Index; 1356 setName(Name); 1357} 1358 1359InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index, 1360 const Twine &Name, 1361 BasicBlock *InsertAE) 1362 : Instruction(Vec->getType(), InsertElement, 1363 OperandTraits<InsertElementInst>::op_begin(this), 1364 3, InsertAE) { 1365 assert(isValidOperands(Vec, Elt, Index) && 1366 "Invalid insertelement instruction operands!"); 1367 1368 Op<0>() = Vec; 1369 Op<1>() = Elt; 1370 Op<2>() = Index; 1371 setName(Name); 1372} 1373 1374bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 1375 const Value *Index) { 1376 if (!isa<VectorType>(Vec->getType())) 1377 return false; // First operand of insertelement must be vector type. 1378 1379 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType()) 1380 return false;// Second operand of insertelement must be vector element type. 1381 1382 if (Index->getType() != Type::getInt32Ty(Vec->getContext())) 1383 return false; // Third operand of insertelement must be i32. 1384 return true; 1385} 1386 1387 1388//===----------------------------------------------------------------------===// 1389// ShuffleVectorInst Implementation 1390//===----------------------------------------------------------------------===// 1391 1392ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1393 const Twine &Name, 1394 Instruction *InsertBefore) 1395: Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1396 cast<VectorType>(Mask->getType())->getNumElements()), 1397 ShuffleVector, 1398 OperandTraits<ShuffleVectorInst>::op_begin(this), 1399 OperandTraits<ShuffleVectorInst>::operands(this), 1400 InsertBefore) { 1401 assert(isValidOperands(V1, V2, Mask) && 1402 "Invalid shuffle vector instruction operands!"); 1403 Op<0>() = V1; 1404 Op<1>() = V2; 1405 Op<2>() = Mask; 1406 setName(Name); 1407} 1408 1409ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask, 1410 const Twine &Name, 1411 BasicBlock *InsertAtEnd) 1412: Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(), 1413 cast<VectorType>(Mask->getType())->getNumElements()), 1414 ShuffleVector, 1415 OperandTraits<ShuffleVectorInst>::op_begin(this), 1416 OperandTraits<ShuffleVectorInst>::operands(this), 1417 InsertAtEnd) { 1418 assert(isValidOperands(V1, V2, Mask) && 1419 "Invalid shuffle vector instruction operands!"); 1420 1421 Op<0>() = V1; 1422 Op<1>() = V2; 1423 Op<2>() = Mask; 1424 setName(Name); 1425} 1426 1427bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 1428 const Value *Mask) { 1429 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType()) 1430 return false; 1431 1432 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType()); 1433 if (!isa<Constant>(Mask) || MaskTy == 0 || 1434 MaskTy->getElementType() != Type::getInt32Ty(V1->getContext())) 1435 return false; 1436 return true; 1437} 1438 1439/// getMaskValue - Return the index from the shuffle mask for the specified 1440/// output result. This is either -1 if the element is undef or a number less 1441/// than 2*numelements. 1442int ShuffleVectorInst::getMaskValue(unsigned i) const { 1443 const Constant *Mask = cast<Constant>(getOperand(2)); 1444 if (isa<UndefValue>(Mask)) return -1; 1445 if (isa<ConstantAggregateZero>(Mask)) return 0; 1446 const ConstantVector *MaskCV = cast<ConstantVector>(Mask); 1447 assert(i < MaskCV->getNumOperands() && "Index out of range"); 1448 1449 if (isa<UndefValue>(MaskCV->getOperand(i))) 1450 return -1; 1451 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue(); 1452} 1453 1454//===----------------------------------------------------------------------===// 1455// InsertValueInst Class 1456//===----------------------------------------------------------------------===// 1457 1458void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx, 1459 unsigned NumIdx, const Twine &Name) { 1460 assert(NumOperands == 2 && "NumOperands not initialized?"); 1461 Op<0>() = Agg; 1462 Op<1>() = Val; 1463 1464 Indices.insert(Indices.end(), Idx, Idx + NumIdx); 1465 setName(Name); 1466} 1467 1468void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx, 1469 const Twine &Name) { 1470 assert(NumOperands == 2 && "NumOperands not initialized?"); 1471 Op<0>() = Agg; 1472 Op<1>() = Val; 1473 1474 Indices.push_back(Idx); 1475 setName(Name); 1476} 1477 1478InsertValueInst::InsertValueInst(const InsertValueInst &IVI) 1479 : Instruction(IVI.getType(), InsertValue, 1480 OperandTraits<InsertValueInst>::op_begin(this), 2), 1481 Indices(IVI.Indices) { 1482 Op<0>() = IVI.getOperand(0); 1483 Op<1>() = IVI.getOperand(1); 1484 SubclassOptionalData = IVI.SubclassOptionalData; 1485} 1486 1487InsertValueInst::InsertValueInst(Value *Agg, 1488 Value *Val, 1489 unsigned Idx, 1490 const Twine &Name, 1491 Instruction *InsertBefore) 1492 : Instruction(Agg->getType(), InsertValue, 1493 OperandTraits<InsertValueInst>::op_begin(this), 1494 2, InsertBefore) { 1495 init(Agg, Val, Idx, Name); 1496} 1497 1498InsertValueInst::InsertValueInst(Value *Agg, 1499 Value *Val, 1500 unsigned Idx, 1501 const Twine &Name, 1502 BasicBlock *InsertAtEnd) 1503 : Instruction(Agg->getType(), InsertValue, 1504 OperandTraits<InsertValueInst>::op_begin(this), 1505 2, InsertAtEnd) { 1506 init(Agg, Val, Idx, Name); 1507} 1508 1509//===----------------------------------------------------------------------===// 1510// ExtractValueInst Class 1511//===----------------------------------------------------------------------===// 1512 1513void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx, 1514 const Twine &Name) { 1515 assert(NumOperands == 1 && "NumOperands not initialized?"); 1516 1517 Indices.insert(Indices.end(), Idx, Idx + NumIdx); 1518 setName(Name); 1519} 1520 1521void ExtractValueInst::init(unsigned Idx, const Twine &Name) { 1522 assert(NumOperands == 1 && "NumOperands not initialized?"); 1523 1524 Indices.push_back(Idx); 1525 setName(Name); 1526} 1527 1528ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI) 1529 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)), 1530 Indices(EVI.Indices) { 1531 SubclassOptionalData = EVI.SubclassOptionalData; 1532} 1533 1534// getIndexedType - Returns the type of the element that would be extracted 1535// with an extractvalue instruction with the specified parameters. 1536// 1537// A null type is returned if the indices are invalid for the specified 1538// pointer type. 1539// 1540const Type* ExtractValueInst::getIndexedType(const Type *Agg, 1541 const unsigned *Idxs, 1542 unsigned NumIdx) { 1543 unsigned CurIdx = 0; 1544 for (; CurIdx != NumIdx; ++CurIdx) { 1545 const CompositeType *CT = dyn_cast<CompositeType>(Agg); 1546 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0; 1547 unsigned Index = Idxs[CurIdx]; 1548 if (!CT->indexValid(Index)) return 0; 1549 Agg = CT->getTypeAtIndex(Index); 1550 1551 // If the new type forwards to another type, then it is in the middle 1552 // of being refined to another type (and hence, may have dropped all 1553 // references to what it was using before). So, use the new forwarded 1554 // type. 1555 if (const Type *Ty = Agg->getForwardedType()) 1556 Agg = Ty; 1557 } 1558 return CurIdx == NumIdx ? Agg : 0; 1559} 1560 1561const Type* ExtractValueInst::getIndexedType(const Type *Agg, 1562 unsigned Idx) { 1563 return getIndexedType(Agg, &Idx, 1); 1564} 1565 1566//===----------------------------------------------------------------------===// 1567// BinaryOperator Class 1568//===----------------------------------------------------------------------===// 1569 1570/// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the 1571/// type is floating-point, to help provide compatibility with an older API. 1572/// 1573static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType, 1574 const Type *Ty) { 1575 // API compatibility: Adjust integer opcodes to floating-point opcodes. 1576 if (Ty->isFPOrFPVector()) { 1577 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd; 1578 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub; 1579 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul; 1580 } 1581 return iType; 1582} 1583 1584BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 1585 const Type *Ty, const Twine &Name, 1586 Instruction *InsertBefore) 1587 : Instruction(Ty, AdjustIType(iType, Ty), 1588 OperandTraits<BinaryOperator>::op_begin(this), 1589 OperandTraits<BinaryOperator>::operands(this), 1590 InsertBefore) { 1591 Op<0>() = S1; 1592 Op<1>() = S2; 1593 init(AdjustIType(iType, Ty)); 1594 setName(Name); 1595} 1596 1597BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 1598 const Type *Ty, const Twine &Name, 1599 BasicBlock *InsertAtEnd) 1600 : Instruction(Ty, AdjustIType(iType, Ty), 1601 OperandTraits<BinaryOperator>::op_begin(this), 1602 OperandTraits<BinaryOperator>::operands(this), 1603 InsertAtEnd) { 1604 Op<0>() = S1; 1605 Op<1>() = S2; 1606 init(AdjustIType(iType, Ty)); 1607 setName(Name); 1608} 1609 1610 1611void BinaryOperator::init(BinaryOps iType) { 1612 Value *LHS = getOperand(0), *RHS = getOperand(1); 1613 LHS = LHS; RHS = RHS; // Silence warnings. 1614 assert(LHS->getType() == RHS->getType() && 1615 "Binary operator operand types must match!"); 1616#ifndef NDEBUG 1617 switch (iType) { 1618 case Add: case Sub: 1619 case Mul: 1620 assert(getType() == LHS->getType() && 1621 "Arithmetic operation should return same type as operands!"); 1622 assert(getType()->isIntOrIntVector() && 1623 "Tried to create an integer operation on a non-integer type!"); 1624 break; 1625 case FAdd: case FSub: 1626 case FMul: 1627 assert(getType() == LHS->getType() && 1628 "Arithmetic operation should return same type as operands!"); 1629 assert(getType()->isFPOrFPVector() && 1630 "Tried to create a floating-point operation on a " 1631 "non-floating-point type!"); 1632 break; 1633 case UDiv: 1634 case SDiv: 1635 assert(getType() == LHS->getType() && 1636 "Arithmetic operation should return same type as operands!"); 1637 assert((getType()->isInteger() || (isa<VectorType>(getType()) && 1638 cast<VectorType>(getType())->getElementType()->isInteger())) && 1639 "Incorrect operand type (not integer) for S/UDIV"); 1640 break; 1641 case FDiv: 1642 assert(getType() == LHS->getType() && 1643 "Arithmetic operation should return same type as operands!"); 1644 assert(getType()->isFPOrFPVector() && 1645 "Incorrect operand type (not floating point) for FDIV"); 1646 break; 1647 case URem: 1648 case SRem: 1649 assert(getType() == LHS->getType() && 1650 "Arithmetic operation should return same type as operands!"); 1651 assert((getType()->isInteger() || (isa<VectorType>(getType()) && 1652 cast<VectorType>(getType())->getElementType()->isInteger())) && 1653 "Incorrect operand type (not integer) for S/UREM"); 1654 break; 1655 case FRem: 1656 assert(getType() == LHS->getType() && 1657 "Arithmetic operation should return same type as operands!"); 1658 assert(getType()->isFPOrFPVector() && 1659 "Incorrect operand type (not floating point) for FREM"); 1660 break; 1661 case Shl: 1662 case LShr: 1663 case AShr: 1664 assert(getType() == LHS->getType() && 1665 "Shift operation should return same type as operands!"); 1666 assert((getType()->isInteger() || 1667 (isa<VectorType>(getType()) && 1668 cast<VectorType>(getType())->getElementType()->isInteger())) && 1669 "Tried to create a shift operation on a non-integral type!"); 1670 break; 1671 case And: case Or: 1672 case Xor: 1673 assert(getType() == LHS->getType() && 1674 "Logical operation should return same type as operands!"); 1675 assert((getType()->isInteger() || 1676 (isa<VectorType>(getType()) && 1677 cast<VectorType>(getType())->getElementType()->isInteger())) && 1678 "Tried to create a logical operation on a non-integral type!"); 1679 break; 1680 default: 1681 break; 1682 } 1683#endif 1684} 1685 1686BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 1687 const Twine &Name, 1688 Instruction *InsertBefore) { 1689 assert(S1->getType() == S2->getType() && 1690 "Cannot create binary operator with two operands of differing type!"); 1691 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore); 1692} 1693 1694BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2, 1695 const Twine &Name, 1696 BasicBlock *InsertAtEnd) { 1697 BinaryOperator *Res = Create(Op, S1, S2, Name); 1698 InsertAtEnd->getInstList().push_back(Res); 1699 return Res; 1700} 1701 1702BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 1703 Instruction *InsertBefore) { 1704 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 1705 return new BinaryOperator(Instruction::Sub, 1706 zero, Op, 1707 Op->getType(), Name, InsertBefore); 1708} 1709 1710BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name, 1711 BasicBlock *InsertAtEnd) { 1712 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 1713 return new BinaryOperator(Instruction::Sub, 1714 zero, Op, 1715 Op->getType(), Name, InsertAtEnd); 1716} 1717 1718BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name, 1719 Instruction *InsertBefore) { 1720 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 1721 return new BinaryOperator(Instruction::FSub, 1722 zero, Op, 1723 Op->getType(), Name, InsertBefore); 1724} 1725 1726BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name, 1727 BasicBlock *InsertAtEnd) { 1728 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType()); 1729 return new BinaryOperator(Instruction::FSub, 1730 zero, Op, 1731 Op->getType(), Name, InsertAtEnd); 1732} 1733 1734BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 1735 Instruction *InsertBefore) { 1736 Constant *C; 1737 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) { 1738 C = Constant::getAllOnesValue(PTy->getElementType()); 1739 C = ConstantVector::get( 1740 std::vector<Constant*>(PTy->getNumElements(), C)); 1741 } else { 1742 C = Constant::getAllOnesValue(Op->getType()); 1743 } 1744 1745 return new BinaryOperator(Instruction::Xor, Op, C, 1746 Op->getType(), Name, InsertBefore); 1747} 1748 1749BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name, 1750 BasicBlock *InsertAtEnd) { 1751 Constant *AllOnes; 1752 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) { 1753 // Create a vector of all ones values. 1754 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType()); 1755 AllOnes = ConstantVector::get( 1756 std::vector<Constant*>(PTy->getNumElements(), Elt)); 1757 } else { 1758 AllOnes = Constant::getAllOnesValue(Op->getType()); 1759 } 1760 1761 return new BinaryOperator(Instruction::Xor, Op, AllOnes, 1762 Op->getType(), Name, InsertAtEnd); 1763} 1764 1765 1766// isConstantAllOnes - Helper function for several functions below 1767static inline bool isConstantAllOnes(const Value *V) { 1768 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) 1769 return CI->isAllOnesValue(); 1770 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) 1771 return CV->isAllOnesValue(); 1772 return false; 1773} 1774 1775bool BinaryOperator::isNeg(const Value *V) { 1776 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 1777 if (Bop->getOpcode() == Instruction::Sub) 1778 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) 1779 return C->isNegativeZeroValue(); 1780 return false; 1781} 1782 1783bool BinaryOperator::isFNeg(const Value *V) { 1784 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 1785 if (Bop->getOpcode() == Instruction::FSub) 1786 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) 1787 return C->isNegativeZeroValue(); 1788 return false; 1789} 1790 1791bool BinaryOperator::isNot(const Value *V) { 1792 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V)) 1793 return (Bop->getOpcode() == Instruction::Xor && 1794 (isConstantAllOnes(Bop->getOperand(1)) || 1795 isConstantAllOnes(Bop->getOperand(0)))); 1796 return false; 1797} 1798 1799Value *BinaryOperator::getNegArgument(Value *BinOp) { 1800 return cast<BinaryOperator>(BinOp)->getOperand(1); 1801} 1802 1803const Value *BinaryOperator::getNegArgument(const Value *BinOp) { 1804 return getNegArgument(const_cast<Value*>(BinOp)); 1805} 1806 1807Value *BinaryOperator::getFNegArgument(Value *BinOp) { 1808 return cast<BinaryOperator>(BinOp)->getOperand(1); 1809} 1810 1811const Value *BinaryOperator::getFNegArgument(const Value *BinOp) { 1812 return getFNegArgument(const_cast<Value*>(BinOp)); 1813} 1814 1815Value *BinaryOperator::getNotArgument(Value *BinOp) { 1816 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!"); 1817 BinaryOperator *BO = cast<BinaryOperator>(BinOp); 1818 Value *Op0 = BO->getOperand(0); 1819 Value *Op1 = BO->getOperand(1); 1820 if (isConstantAllOnes(Op0)) return Op1; 1821 1822 assert(isConstantAllOnes(Op1)); 1823 return Op0; 1824} 1825 1826const Value *BinaryOperator::getNotArgument(const Value *BinOp) { 1827 return getNotArgument(const_cast<Value*>(BinOp)); 1828} 1829 1830 1831// swapOperands - Exchange the two operands to this instruction. This 1832// instruction is safe to use on any binary instruction and does not 1833// modify the semantics of the instruction. If the instruction is 1834// order dependent (SetLT f.e.) the opcode is changed. 1835// 1836bool BinaryOperator::swapOperands() { 1837 if (!isCommutative()) 1838 return true; // Can't commute operands 1839 Op<0>().swap(Op<1>()); 1840 return false; 1841} 1842 1843void BinaryOperator::setHasNoUnsignedWrap(bool b) { 1844 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b); 1845} 1846 1847void BinaryOperator::setHasNoSignedWrap(bool b) { 1848 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b); 1849} 1850 1851void BinaryOperator::setIsExact(bool b) { 1852 cast<SDivOperator>(this)->setIsExact(b); 1853} 1854 1855bool BinaryOperator::hasNoUnsignedWrap() const { 1856 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap(); 1857} 1858 1859bool BinaryOperator::hasNoSignedWrap() const { 1860 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap(); 1861} 1862 1863bool BinaryOperator::isExact() const { 1864 return cast<SDivOperator>(this)->isExact(); 1865} 1866 1867//===----------------------------------------------------------------------===// 1868// CastInst Class 1869//===----------------------------------------------------------------------===// 1870 1871// Just determine if this cast only deals with integral->integral conversion. 1872bool CastInst::isIntegerCast() const { 1873 switch (getOpcode()) { 1874 default: return false; 1875 case Instruction::ZExt: 1876 case Instruction::SExt: 1877 case Instruction::Trunc: 1878 return true; 1879 case Instruction::BitCast: 1880 return getOperand(0)->getType()->isInteger() && getType()->isInteger(); 1881 } 1882} 1883 1884bool CastInst::isLosslessCast() const { 1885 // Only BitCast can be lossless, exit fast if we're not BitCast 1886 if (getOpcode() != Instruction::BitCast) 1887 return false; 1888 1889 // Identity cast is always lossless 1890 const Type* SrcTy = getOperand(0)->getType(); 1891 const Type* DstTy = getType(); 1892 if (SrcTy == DstTy) 1893 return true; 1894 1895 // Pointer to pointer is always lossless. 1896 if (isa<PointerType>(SrcTy)) 1897 return isa<PointerType>(DstTy); 1898 return false; // Other types have no identity values 1899} 1900 1901/// This function determines if the CastInst does not require any bits to be 1902/// changed in order to effect the cast. Essentially, it identifies cases where 1903/// no code gen is necessary for the cast, hence the name no-op cast. For 1904/// example, the following are all no-op casts: 1905/// # bitcast i32* %x to i8* 1906/// # bitcast <2 x i32> %x to <4 x i16> 1907/// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only 1908/// @brief Determine if a cast is a no-op. 1909bool CastInst::isNoopCast(const Type *IntPtrTy) const { 1910 switch (getOpcode()) { 1911 default: 1912 assert(!"Invalid CastOp"); 1913 case Instruction::Trunc: 1914 case Instruction::ZExt: 1915 case Instruction::SExt: 1916 case Instruction::FPTrunc: 1917 case Instruction::FPExt: 1918 case Instruction::UIToFP: 1919 case Instruction::SIToFP: 1920 case Instruction::FPToUI: 1921 case Instruction::FPToSI: 1922 return false; // These always modify bits 1923 case Instruction::BitCast: 1924 return true; // BitCast never modifies bits. 1925 case Instruction::PtrToInt: 1926 return IntPtrTy->getScalarSizeInBits() == 1927 getType()->getScalarSizeInBits(); 1928 case Instruction::IntToPtr: 1929 return IntPtrTy->getScalarSizeInBits() == 1930 getOperand(0)->getType()->getScalarSizeInBits(); 1931 } 1932} 1933 1934/// This function determines if a pair of casts can be eliminated and what 1935/// opcode should be used in the elimination. This assumes that there are two 1936/// instructions like this: 1937/// * %F = firstOpcode SrcTy %x to MidTy 1938/// * %S = secondOpcode MidTy %F to DstTy 1939/// The function returns a resultOpcode so these two casts can be replaced with: 1940/// * %Replacement = resultOpcode %SrcTy %x to DstTy 1941/// If no such cast is permited, the function returns 0. 1942unsigned CastInst::isEliminableCastPair( 1943 Instruction::CastOps firstOp, Instruction::CastOps secondOp, 1944 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy) 1945{ 1946 // Define the 144 possibilities for these two cast instructions. The values 1947 // in this matrix determine what to do in a given situation and select the 1948 // case in the switch below. The rows correspond to firstOp, the columns 1949 // correspond to secondOp. In looking at the table below, keep in mind 1950 // the following cast properties: 1951 // 1952 // Size Compare Source Destination 1953 // Operator Src ? Size Type Sign Type Sign 1954 // -------- ------------ ------------------- --------------------- 1955 // TRUNC > Integer Any Integral Any 1956 // ZEXT < Integral Unsigned Integer Any 1957 // SEXT < Integral Signed Integer Any 1958 // FPTOUI n/a FloatPt n/a Integral Unsigned 1959 // FPTOSI n/a FloatPt n/a Integral Signed 1960 // UITOFP n/a Integral Unsigned FloatPt n/a 1961 // SITOFP n/a Integral Signed FloatPt n/a 1962 // FPTRUNC > FloatPt n/a FloatPt n/a 1963 // FPEXT < FloatPt n/a FloatPt n/a 1964 // PTRTOINT n/a Pointer n/a Integral Unsigned 1965 // INTTOPTR n/a Integral Unsigned Pointer n/a 1966 // BITCONVERT = FirstClass n/a FirstClass n/a 1967 // 1968 // NOTE: some transforms are safe, but we consider them to be non-profitable. 1969 // For example, we could merge "fptoui double to i32" + "zext i32 to i64", 1970 // into "fptoui double to i64", but this loses information about the range 1971 // of the produced value (we no longer know the top-part is all zeros). 1972 // Further this conversion is often much more expensive for typical hardware, 1973 // and causes issues when building libgcc. We disallow fptosi+sext for the 1974 // same reason. 1975 const unsigned numCastOps = 1976 Instruction::CastOpsEnd - Instruction::CastOpsBegin; 1977 static const uint8_t CastResults[numCastOps][numCastOps] = { 1978 // T F F U S F F P I B -+ 1979 // R Z S P P I I T P 2 N T | 1980 // U E E 2 2 2 2 R E I T C +- secondOp 1981 // N X X U S F F N X N 2 V | 1982 // C T T I I P P C T T P T -+ 1983 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+ 1984 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt | 1985 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt | 1986 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI | 1987 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI | 1988 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp 1989 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP | 1990 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc | 1991 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt | 1992 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt | 1993 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr | 1994 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+ 1995 }; 1996 1997 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin] 1998 [secondOp-Instruction::CastOpsBegin]; 1999 switch (ElimCase) { 2000 case 0: 2001 // categorically disallowed 2002 return 0; 2003 case 1: 2004 // allowed, use first cast's opcode 2005 return firstOp; 2006 case 2: 2007 // allowed, use second cast's opcode 2008 return secondOp; 2009 case 3: 2010 // no-op cast in second op implies firstOp as long as the DestTy 2011 // is integer 2012 if (DstTy->isInteger()) 2013 return firstOp; 2014 return 0; 2015 case 4: 2016 // no-op cast in second op implies firstOp as long as the DestTy 2017 // is floating point 2018 if (DstTy->isFloatingPoint()) 2019 return firstOp; 2020 return 0; 2021 case 5: 2022 // no-op cast in first op implies secondOp as long as the SrcTy 2023 // is an integer 2024 if (SrcTy->isInteger()) 2025 return secondOp; 2026 return 0; 2027 case 6: 2028 // no-op cast in first op implies secondOp as long as the SrcTy 2029 // is a floating point 2030 if (SrcTy->isFloatingPoint()) 2031 return secondOp; 2032 return 0; 2033 case 7: { 2034 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size 2035 if (!IntPtrTy) 2036 return 0; 2037 unsigned PtrSize = IntPtrTy->getScalarSizeInBits(); 2038 unsigned MidSize = MidTy->getScalarSizeInBits(); 2039 if (MidSize >= PtrSize) 2040 return Instruction::BitCast; 2041 return 0; 2042 } 2043 case 8: { 2044 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size 2045 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy) 2046 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy) 2047 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2048 unsigned DstSize = DstTy->getScalarSizeInBits(); 2049 if (SrcSize == DstSize) 2050 return Instruction::BitCast; 2051 else if (SrcSize < DstSize) 2052 return firstOp; 2053 return secondOp; 2054 } 2055 case 9: // zext, sext -> zext, because sext can't sign extend after zext 2056 return Instruction::ZExt; 2057 case 10: 2058 // fpext followed by ftrunc is allowed if the bit size returned to is 2059 // the same as the original, in which case its just a bitcast 2060 if (SrcTy == DstTy) 2061 return Instruction::BitCast; 2062 return 0; // If the types are not the same we can't eliminate it. 2063 case 11: 2064 // bitcast followed by ptrtoint is allowed as long as the bitcast 2065 // is a pointer to pointer cast. 2066 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy)) 2067 return secondOp; 2068 return 0; 2069 case 12: 2070 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast 2071 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy)) 2072 return firstOp; 2073 return 0; 2074 case 13: { 2075 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize 2076 if (!IntPtrTy) 2077 return 0; 2078 unsigned PtrSize = IntPtrTy->getScalarSizeInBits(); 2079 unsigned SrcSize = SrcTy->getScalarSizeInBits(); 2080 unsigned DstSize = DstTy->getScalarSizeInBits(); 2081 if (SrcSize <= PtrSize && SrcSize == DstSize) 2082 return Instruction::BitCast; 2083 return 0; 2084 } 2085 case 99: 2086 // cast combination can't happen (error in input). This is for all cases 2087 // where the MidTy is not the same for the two cast instructions. 2088 assert(!"Invalid Cast Combination"); 2089 return 0; 2090 default: 2091 assert(!"Error in CastResults table!!!"); 2092 return 0; 2093 } 2094 return 0; 2095} 2096 2097CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty, 2098 const Twine &Name, Instruction *InsertBefore) { 2099 // Construct and return the appropriate CastInst subclass 2100 switch (op) { 2101 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore); 2102 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore); 2103 case SExt: return new SExtInst (S, Ty, Name, InsertBefore); 2104 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore); 2105 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore); 2106 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore); 2107 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore); 2108 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore); 2109 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore); 2110 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore); 2111 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore); 2112 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore); 2113 default: 2114 assert(!"Invalid opcode provided"); 2115 } 2116 return 0; 2117} 2118 2119CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty, 2120 const Twine &Name, BasicBlock *InsertAtEnd) { 2121 // Construct and return the appropriate CastInst subclass 2122 switch (op) { 2123 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd); 2124 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd); 2125 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd); 2126 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd); 2127 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd); 2128 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd); 2129 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd); 2130 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd); 2131 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd); 2132 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd); 2133 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd); 2134 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd); 2135 default: 2136 assert(!"Invalid opcode provided"); 2137 } 2138 return 0; 2139} 2140 2141CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 2142 const Twine &Name, 2143 Instruction *InsertBefore) { 2144 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2145 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2146 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore); 2147} 2148 2149CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 2150 const Twine &Name, 2151 BasicBlock *InsertAtEnd) { 2152 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2153 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2154 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd); 2155} 2156 2157CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 2158 const Twine &Name, 2159 Instruction *InsertBefore) { 2160 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2161 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2162 return Create(Instruction::SExt, S, Ty, Name, InsertBefore); 2163} 2164 2165CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 2166 const Twine &Name, 2167 BasicBlock *InsertAtEnd) { 2168 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2169 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2170 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd); 2171} 2172 2173CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty, 2174 const Twine &Name, 2175 Instruction *InsertBefore) { 2176 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2177 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2178 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore); 2179} 2180 2181CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty, 2182 const Twine &Name, 2183 BasicBlock *InsertAtEnd) { 2184 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits()) 2185 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2186 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd); 2187} 2188 2189CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty, 2190 const Twine &Name, 2191 BasicBlock *InsertAtEnd) { 2192 assert(isa<PointerType>(S->getType()) && "Invalid cast"); 2193 assert((Ty->isInteger() || isa<PointerType>(Ty)) && 2194 "Invalid cast"); 2195 2196 if (Ty->isInteger()) 2197 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd); 2198 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd); 2199} 2200 2201/// @brief Create a BitCast or a PtrToInt cast instruction 2202CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty, 2203 const Twine &Name, 2204 Instruction *InsertBefore) { 2205 assert(isa<PointerType>(S->getType()) && "Invalid cast"); 2206 assert((Ty->isInteger() || isa<PointerType>(Ty)) && 2207 "Invalid cast"); 2208 2209 if (Ty->isInteger()) 2210 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore); 2211 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore); 2212} 2213 2214CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 2215 bool isSigned, const Twine &Name, 2216 Instruction *InsertBefore) { 2217 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast"); 2218 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2219 unsigned DstBits = Ty->getScalarSizeInBits(); 2220 Instruction::CastOps opcode = 2221 (SrcBits == DstBits ? Instruction::BitCast : 2222 (SrcBits > DstBits ? Instruction::Trunc : 2223 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2224 return Create(opcode, C, Ty, Name, InsertBefore); 2225} 2226 2227CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 2228 bool isSigned, const Twine &Name, 2229 BasicBlock *InsertAtEnd) { 2230 assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() && 2231 "Invalid cast"); 2232 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2233 unsigned DstBits = Ty->getScalarSizeInBits(); 2234 Instruction::CastOps opcode = 2235 (SrcBits == DstBits ? Instruction::BitCast : 2236 (SrcBits > DstBits ? Instruction::Trunc : 2237 (isSigned ? Instruction::SExt : Instruction::ZExt))); 2238 return Create(opcode, C, Ty, Name, InsertAtEnd); 2239} 2240 2241CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 2242 const Twine &Name, 2243 Instruction *InsertBefore) { 2244 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() && 2245 "Invalid cast"); 2246 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2247 unsigned DstBits = Ty->getScalarSizeInBits(); 2248 Instruction::CastOps opcode = 2249 (SrcBits == DstBits ? Instruction::BitCast : 2250 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 2251 return Create(opcode, C, Ty, Name, InsertBefore); 2252} 2253 2254CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 2255 const Twine &Name, 2256 BasicBlock *InsertAtEnd) { 2257 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() && 2258 "Invalid cast"); 2259 unsigned SrcBits = C->getType()->getScalarSizeInBits(); 2260 unsigned DstBits = Ty->getScalarSizeInBits(); 2261 Instruction::CastOps opcode = 2262 (SrcBits == DstBits ? Instruction::BitCast : 2263 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt)); 2264 return Create(opcode, C, Ty, Name, InsertAtEnd); 2265} 2266 2267// Check whether it is valid to call getCastOpcode for these types. 2268// This routine must be kept in sync with getCastOpcode. 2269bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) { 2270 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType()) 2271 return false; 2272 2273 if (SrcTy == DestTy) 2274 return true; 2275 2276 // Get the bit sizes, we'll need these 2277 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr 2278 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr 2279 2280 // Run through the possibilities ... 2281 if (DestTy->isInteger()) { // Casting to integral 2282 if (SrcTy->isInteger()) { // Casting from integral 2283 return true; 2284 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt 2285 return true; 2286 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) { 2287 // Casting from vector 2288 return DestBits == PTy->getBitWidth(); 2289 } else { // Casting from something else 2290 return isa<PointerType>(SrcTy); 2291 } 2292 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt 2293 if (SrcTy->isInteger()) { // Casting from integral 2294 return true; 2295 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt 2296 return true; 2297 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) { 2298 // Casting from vector 2299 return DestBits == PTy->getBitWidth(); 2300 } else { // Casting from something else 2301 return false; 2302 } 2303 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) { 2304 // Casting to vector 2305 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) { 2306 // Casting from vector 2307 return DestPTy->getBitWidth() == SrcPTy->getBitWidth(); 2308 } else { // Casting from something else 2309 return DestPTy->getBitWidth() == SrcBits; 2310 } 2311 } else if (isa<PointerType>(DestTy)) { // Casting to pointer 2312 if (isa<PointerType>(SrcTy)) { // Casting from pointer 2313 return true; 2314 } else if (SrcTy->isInteger()) { // Casting from integral 2315 return true; 2316 } else { // Casting from something else 2317 return false; 2318 } 2319 } else { // Casting to something else 2320 return false; 2321 } 2322} 2323 2324// Provide a way to get a "cast" where the cast opcode is inferred from the 2325// types and size of the operand. This, basically, is a parallel of the 2326// logic in the castIsValid function below. This axiom should hold: 2327// castIsValid( getCastOpcode(Val, Ty), Val, Ty) 2328// should not assert in castIsValid. In other words, this produces a "correct" 2329// casting opcode for the arguments passed to it. 2330// This routine must be kept in sync with isCastable. 2331Instruction::CastOps 2332CastInst::getCastOpcode( 2333 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) { 2334 // Get the bit sizes, we'll need these 2335 const Type *SrcTy = Src->getType(); 2336 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr 2337 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr 2338 2339 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() && 2340 "Only first class types are castable!"); 2341 2342 // Run through the possibilities ... 2343 if (DestTy->isInteger()) { // Casting to integral 2344 if (SrcTy->isInteger()) { // Casting from integral 2345 if (DestBits < SrcBits) 2346 return Trunc; // int -> smaller int 2347 else if (DestBits > SrcBits) { // its an extension 2348 if (SrcIsSigned) 2349 return SExt; // signed -> SEXT 2350 else 2351 return ZExt; // unsigned -> ZEXT 2352 } else { 2353 return BitCast; // Same size, No-op cast 2354 } 2355 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt 2356 if (DestIsSigned) 2357 return FPToSI; // FP -> sint 2358 else 2359 return FPToUI; // FP -> uint 2360 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) { 2361 assert(DestBits == PTy->getBitWidth() && 2362 "Casting vector to integer of different width"); 2363 PTy = NULL; 2364 return BitCast; // Same size, no-op cast 2365 } else { 2366 assert(isa<PointerType>(SrcTy) && 2367 "Casting from a value that is not first-class type"); 2368 return PtrToInt; // ptr -> int 2369 } 2370 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt 2371 if (SrcTy->isInteger()) { // Casting from integral 2372 if (SrcIsSigned) 2373 return SIToFP; // sint -> FP 2374 else 2375 return UIToFP; // uint -> FP 2376 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt 2377 if (DestBits < SrcBits) { 2378 return FPTrunc; // FP -> smaller FP 2379 } else if (DestBits > SrcBits) { 2380 return FPExt; // FP -> larger FP 2381 } else { 2382 return BitCast; // same size, no-op cast 2383 } 2384 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) { 2385 assert(DestBits == PTy->getBitWidth() && 2386 "Casting vector to floating point of different width"); 2387 PTy = NULL; 2388 return BitCast; // same size, no-op cast 2389 } else { 2390 llvm_unreachable("Casting pointer or non-first class to float"); 2391 } 2392 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) { 2393 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) { 2394 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() && 2395 "Casting vector to vector of different widths"); 2396 SrcPTy = NULL; 2397 return BitCast; // vector -> vector 2398 } else if (DestPTy->getBitWidth() == SrcBits) { 2399 return BitCast; // float/int -> vector 2400 } else { 2401 assert(!"Illegal cast to vector (wrong type or size)"); 2402 } 2403 } else if (isa<PointerType>(DestTy)) { 2404 if (isa<PointerType>(SrcTy)) { 2405 return BitCast; // ptr -> ptr 2406 } else if (SrcTy->isInteger()) { 2407 return IntToPtr; // int -> ptr 2408 } else { 2409 assert(!"Casting pointer to other than pointer or int"); 2410 } 2411 } else { 2412 assert(!"Casting to type that is not first-class"); 2413 } 2414 2415 // If we fall through to here we probably hit an assertion cast above 2416 // and assertions are not turned on. Anything we return is an error, so 2417 // BitCast is as good a choice as any. 2418 return BitCast; 2419} 2420 2421//===----------------------------------------------------------------------===// 2422// CastInst SubClass Constructors 2423//===----------------------------------------------------------------------===// 2424 2425/// Check that the construction parameters for a CastInst are correct. This 2426/// could be broken out into the separate constructors but it is useful to have 2427/// it in one place and to eliminate the redundant code for getting the sizes 2428/// of the types involved. 2429bool 2430CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) { 2431 2432 // Check for type sanity on the arguments 2433 const Type *SrcTy = S->getType(); 2434 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType()) 2435 return false; 2436 2437 // Get the size of the types in bits, we'll need this later 2438 unsigned SrcBitSize = SrcTy->getScalarSizeInBits(); 2439 unsigned DstBitSize = DstTy->getScalarSizeInBits(); 2440 2441 // Switch on the opcode provided 2442 switch (op) { 2443 default: return false; // This is an input error 2444 case Instruction::Trunc: 2445 return SrcTy->isIntOrIntVector() && 2446 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize; 2447 case Instruction::ZExt: 2448 return SrcTy->isIntOrIntVector() && 2449 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize; 2450 case Instruction::SExt: 2451 return SrcTy->isIntOrIntVector() && 2452 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize; 2453 case Instruction::FPTrunc: 2454 return SrcTy->isFPOrFPVector() && 2455 DstTy->isFPOrFPVector() && 2456 SrcBitSize > DstBitSize; 2457 case Instruction::FPExt: 2458 return SrcTy->isFPOrFPVector() && 2459 DstTy->isFPOrFPVector() && 2460 SrcBitSize < DstBitSize; 2461 case Instruction::UIToFP: 2462 case Instruction::SIToFP: 2463 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) { 2464 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 2465 return SVTy->getElementType()->isIntOrIntVector() && 2466 DVTy->getElementType()->isFPOrFPVector() && 2467 SVTy->getNumElements() == DVTy->getNumElements(); 2468 } 2469 } 2470 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector(); 2471 case Instruction::FPToUI: 2472 case Instruction::FPToSI: 2473 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) { 2474 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 2475 return SVTy->getElementType()->isFPOrFPVector() && 2476 DVTy->getElementType()->isIntOrIntVector() && 2477 SVTy->getNumElements() == DVTy->getNumElements(); 2478 } 2479 } 2480 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector(); 2481 case Instruction::PtrToInt: 2482 return isa<PointerType>(SrcTy) && DstTy->isInteger(); 2483 case Instruction::IntToPtr: 2484 return SrcTy->isInteger() && isa<PointerType>(DstTy); 2485 case Instruction::BitCast: 2486 // BitCast implies a no-op cast of type only. No bits change. 2487 // However, you can't cast pointers to anything but pointers. 2488 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy)) 2489 return false; 2490 2491 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all 2492 // these cases, the cast is okay if the source and destination bit widths 2493 // are identical. 2494 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits(); 2495 } 2496} 2497 2498TruncInst::TruncInst( 2499 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2500) : CastInst(Ty, Trunc, S, Name, InsertBefore) { 2501 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 2502} 2503 2504TruncInst::TruncInst( 2505 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2506) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 2507 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc"); 2508} 2509 2510ZExtInst::ZExtInst( 2511 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2512) : CastInst(Ty, ZExt, S, Name, InsertBefore) { 2513 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 2514} 2515 2516ZExtInst::ZExtInst( 2517 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2518) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 2519 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt"); 2520} 2521SExtInst::SExtInst( 2522 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2523) : CastInst(Ty, SExt, S, Name, InsertBefore) { 2524 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 2525} 2526 2527SExtInst::SExtInst( 2528 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2529) : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 2530 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt"); 2531} 2532 2533FPTruncInst::FPTruncInst( 2534 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2535) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 2536 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 2537} 2538 2539FPTruncInst::FPTruncInst( 2540 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2541) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 2542 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc"); 2543} 2544 2545FPExtInst::FPExtInst( 2546 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2547) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 2548 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 2549} 2550 2551FPExtInst::FPExtInst( 2552 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2553) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 2554 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt"); 2555} 2556 2557UIToFPInst::UIToFPInst( 2558 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2559) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 2560 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 2561} 2562 2563UIToFPInst::UIToFPInst( 2564 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2565) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 2566 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP"); 2567} 2568 2569SIToFPInst::SIToFPInst( 2570 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2571) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 2572 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 2573} 2574 2575SIToFPInst::SIToFPInst( 2576 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2577) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 2578 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP"); 2579} 2580 2581FPToUIInst::FPToUIInst( 2582 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2583) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 2584 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 2585} 2586 2587FPToUIInst::FPToUIInst( 2588 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2589) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 2590 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI"); 2591} 2592 2593FPToSIInst::FPToSIInst( 2594 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2595) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 2596 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 2597} 2598 2599FPToSIInst::FPToSIInst( 2600 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2601) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 2602 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI"); 2603} 2604 2605PtrToIntInst::PtrToIntInst( 2606 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2607) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 2608 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 2609} 2610 2611PtrToIntInst::PtrToIntInst( 2612 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2613) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 2614 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt"); 2615} 2616 2617IntToPtrInst::IntToPtrInst( 2618 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2619) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 2620 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 2621} 2622 2623IntToPtrInst::IntToPtrInst( 2624 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2625) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 2626 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr"); 2627} 2628 2629BitCastInst::BitCastInst( 2630 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore 2631) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 2632 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 2633} 2634 2635BitCastInst::BitCastInst( 2636 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd 2637) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 2638 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast"); 2639} 2640 2641//===----------------------------------------------------------------------===// 2642// CmpInst Classes 2643//===----------------------------------------------------------------------===// 2644 2645CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate, 2646 Value *LHS, Value *RHS, const Twine &Name, 2647 Instruction *InsertBefore) 2648 : Instruction(ty, op, 2649 OperandTraits<CmpInst>::op_begin(this), 2650 OperandTraits<CmpInst>::operands(this), 2651 InsertBefore) { 2652 Op<0>() = LHS; 2653 Op<1>() = RHS; 2654 SubclassData = predicate; 2655 setName(Name); 2656} 2657 2658CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate, 2659 Value *LHS, Value *RHS, const Twine &Name, 2660 BasicBlock *InsertAtEnd) 2661 : Instruction(ty, op, 2662 OperandTraits<CmpInst>::op_begin(this), 2663 OperandTraits<CmpInst>::operands(this), 2664 InsertAtEnd) { 2665 Op<0>() = LHS; 2666 Op<1>() = RHS; 2667 SubclassData = predicate; 2668 setName(Name); 2669} 2670 2671CmpInst * 2672CmpInst::Create(OtherOps Op, unsigned short predicate, 2673 Value *S1, Value *S2, 2674 const Twine &Name, Instruction *InsertBefore) { 2675 if (Op == Instruction::ICmp) { 2676 if (InsertBefore) 2677 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate), 2678 S1, S2, Name); 2679 else 2680 return new ICmpInst(CmpInst::Predicate(predicate), 2681 S1, S2, Name); 2682 } 2683 2684 if (InsertBefore) 2685 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate), 2686 S1, S2, Name); 2687 else 2688 return new FCmpInst(CmpInst::Predicate(predicate), 2689 S1, S2, Name); 2690} 2691 2692CmpInst * 2693CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 2694 const Twine &Name, BasicBlock *InsertAtEnd) { 2695 if (Op == Instruction::ICmp) { 2696 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 2697 S1, S2, Name); 2698 } 2699 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate), 2700 S1, S2, Name); 2701} 2702 2703void CmpInst::swapOperands() { 2704 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 2705 IC->swapOperands(); 2706 else 2707 cast<FCmpInst>(this)->swapOperands(); 2708} 2709 2710bool CmpInst::isCommutative() { 2711 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 2712 return IC->isCommutative(); 2713 return cast<FCmpInst>(this)->isCommutative(); 2714} 2715 2716bool CmpInst::isEquality() { 2717 if (ICmpInst *IC = dyn_cast<ICmpInst>(this)) 2718 return IC->isEquality(); 2719 return cast<FCmpInst>(this)->isEquality(); 2720} 2721 2722 2723CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) { 2724 switch (pred) { 2725 default: assert(!"Unknown cmp predicate!"); 2726 case ICMP_EQ: return ICMP_NE; 2727 case ICMP_NE: return ICMP_EQ; 2728 case ICMP_UGT: return ICMP_ULE; 2729 case ICMP_ULT: return ICMP_UGE; 2730 case ICMP_UGE: return ICMP_ULT; 2731 case ICMP_ULE: return ICMP_UGT; 2732 case ICMP_SGT: return ICMP_SLE; 2733 case ICMP_SLT: return ICMP_SGE; 2734 case ICMP_SGE: return ICMP_SLT; 2735 case ICMP_SLE: return ICMP_SGT; 2736 2737 case FCMP_OEQ: return FCMP_UNE; 2738 case FCMP_ONE: return FCMP_UEQ; 2739 case FCMP_OGT: return FCMP_ULE; 2740 case FCMP_OLT: return FCMP_UGE; 2741 case FCMP_OGE: return FCMP_ULT; 2742 case FCMP_OLE: return FCMP_UGT; 2743 case FCMP_UEQ: return FCMP_ONE; 2744 case FCMP_UNE: return FCMP_OEQ; 2745 case FCMP_UGT: return FCMP_OLE; 2746 case FCMP_ULT: return FCMP_OGE; 2747 case FCMP_UGE: return FCMP_OLT; 2748 case FCMP_ULE: return FCMP_OGT; 2749 case FCMP_ORD: return FCMP_UNO; 2750 case FCMP_UNO: return FCMP_ORD; 2751 case FCMP_TRUE: return FCMP_FALSE; 2752 case FCMP_FALSE: return FCMP_TRUE; 2753 } 2754} 2755 2756ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) { 2757 switch (pred) { 2758 default: assert(! "Unknown icmp predicate!"); 2759 case ICMP_EQ: case ICMP_NE: 2760 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 2761 return pred; 2762 case ICMP_UGT: return ICMP_SGT; 2763 case ICMP_ULT: return ICMP_SLT; 2764 case ICMP_UGE: return ICMP_SGE; 2765 case ICMP_ULE: return ICMP_SLE; 2766 } 2767} 2768 2769ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) { 2770 switch (pred) { 2771 default: assert(! "Unknown icmp predicate!"); 2772 case ICMP_EQ: case ICMP_NE: 2773 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 2774 return pred; 2775 case ICMP_SGT: return ICMP_UGT; 2776 case ICMP_SLT: return ICMP_ULT; 2777 case ICMP_SGE: return ICMP_UGE; 2778 case ICMP_SLE: return ICMP_ULE; 2779 } 2780} 2781 2782bool ICmpInst::isSignedPredicate(Predicate pred) { 2783 switch (pred) { 2784 default: assert(! "Unknown icmp predicate!"); 2785 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 2786 return true; 2787 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT: 2788 case ICMP_UGE: case ICMP_ULE: 2789 return false; 2790 } 2791} 2792 2793/// Initialize a set of values that all satisfy the condition with C. 2794/// 2795ConstantRange 2796ICmpInst::makeConstantRange(Predicate pred, const APInt &C) { 2797 APInt Lower(C); 2798 APInt Upper(C); 2799 uint32_t BitWidth = C.getBitWidth(); 2800 switch (pred) { 2801 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!"); 2802 case ICmpInst::ICMP_EQ: Upper++; break; 2803 case ICmpInst::ICMP_NE: Lower++; break; 2804 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break; 2805 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break; 2806 case ICmpInst::ICMP_UGT: 2807 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max) 2808 break; 2809 case ICmpInst::ICMP_SGT: 2810 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max) 2811 break; 2812 case ICmpInst::ICMP_ULE: 2813 Lower = APInt::getMinValue(BitWidth); Upper++; 2814 break; 2815 case ICmpInst::ICMP_SLE: 2816 Lower = APInt::getSignedMinValue(BitWidth); Upper++; 2817 break; 2818 case ICmpInst::ICMP_UGE: 2819 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max) 2820 break; 2821 case ICmpInst::ICMP_SGE: 2822 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max) 2823 break; 2824 } 2825 return ConstantRange(Lower, Upper); 2826} 2827 2828CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) { 2829 switch (pred) { 2830 default: assert(!"Unknown cmp predicate!"); 2831 case ICMP_EQ: case ICMP_NE: 2832 return pred; 2833 case ICMP_SGT: return ICMP_SLT; 2834 case ICMP_SLT: return ICMP_SGT; 2835 case ICMP_SGE: return ICMP_SLE; 2836 case ICMP_SLE: return ICMP_SGE; 2837 case ICMP_UGT: return ICMP_ULT; 2838 case ICMP_ULT: return ICMP_UGT; 2839 case ICMP_UGE: return ICMP_ULE; 2840 case ICMP_ULE: return ICMP_UGE; 2841 2842 case FCMP_FALSE: case FCMP_TRUE: 2843 case FCMP_OEQ: case FCMP_ONE: 2844 case FCMP_UEQ: case FCMP_UNE: 2845 case FCMP_ORD: case FCMP_UNO: 2846 return pred; 2847 case FCMP_OGT: return FCMP_OLT; 2848 case FCMP_OLT: return FCMP_OGT; 2849 case FCMP_OGE: return FCMP_OLE; 2850 case FCMP_OLE: return FCMP_OGE; 2851 case FCMP_UGT: return FCMP_ULT; 2852 case FCMP_ULT: return FCMP_UGT; 2853 case FCMP_UGE: return FCMP_ULE; 2854 case FCMP_ULE: return FCMP_UGE; 2855 } 2856} 2857 2858bool CmpInst::isUnsigned(unsigned short predicate) { 2859 switch (predicate) { 2860 default: return false; 2861 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 2862 case ICmpInst::ICMP_UGE: return true; 2863 } 2864} 2865 2866bool CmpInst::isSigned(unsigned short predicate){ 2867 switch (predicate) { 2868 default: return false; 2869 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 2870 case ICmpInst::ICMP_SGE: return true; 2871 } 2872} 2873 2874bool CmpInst::isOrdered(unsigned short predicate) { 2875 switch (predicate) { 2876 default: return false; 2877 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 2878 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 2879 case FCmpInst::FCMP_ORD: return true; 2880 } 2881} 2882 2883bool CmpInst::isUnordered(unsigned short predicate) { 2884 switch (predicate) { 2885 default: return false; 2886 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 2887 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 2888 case FCmpInst::FCMP_UNO: return true; 2889 } 2890} 2891 2892//===----------------------------------------------------------------------===// 2893// SwitchInst Implementation 2894//===----------------------------------------------------------------------===// 2895 2896void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) { 2897 assert(Value && Default); 2898 ReservedSpace = 2+NumCases*2; 2899 NumOperands = 2; 2900 OperandList = allocHungoffUses(ReservedSpace); 2901 2902 OperandList[0] = Value; 2903 OperandList[1] = Default; 2904} 2905 2906/// SwitchInst ctor - Create a new switch instruction, specifying a value to 2907/// switch on and a default destination. The number of additional cases can 2908/// be specified here to make memory allocation more efficient. This 2909/// constructor can also autoinsert before another instruction. 2910SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 2911 Instruction *InsertBefore) 2912 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch, 2913 0, 0, InsertBefore) { 2914 init(Value, Default, NumCases); 2915} 2916 2917/// SwitchInst ctor - Create a new switch instruction, specifying a value to 2918/// switch on and a default destination. The number of additional cases can 2919/// be specified here to make memory allocation more efficient. This 2920/// constructor also autoinserts at the end of the specified BasicBlock. 2921SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases, 2922 BasicBlock *InsertAtEnd) 2923 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch, 2924 0, 0, InsertAtEnd) { 2925 init(Value, Default, NumCases); 2926} 2927 2928SwitchInst::SwitchInst(const SwitchInst &SI) 2929 : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch, 2930 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) { 2931 Use *OL = OperandList, *InOL = SI.OperandList; 2932 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) { 2933 OL[i] = InOL[i]; 2934 OL[i+1] = InOL[i+1]; 2935 } 2936 SubclassOptionalData = SI.SubclassOptionalData; 2937} 2938 2939SwitchInst::~SwitchInst() { 2940 dropHungoffUses(OperandList); 2941} 2942 2943 2944/// addCase - Add an entry to the switch instruction... 2945/// 2946void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) { 2947 unsigned OpNo = NumOperands; 2948 if (OpNo+2 > ReservedSpace) 2949 resizeOperands(0); // Get more space! 2950 // Initialize some new operands. 2951 assert(OpNo+1 < ReservedSpace && "Growing didn't work!"); 2952 NumOperands = OpNo+2; 2953 OperandList[OpNo] = OnVal; 2954 OperandList[OpNo+1] = Dest; 2955} 2956 2957/// removeCase - This method removes the specified successor from the switch 2958/// instruction. Note that this cannot be used to remove the default 2959/// destination (successor #0). 2960/// 2961void SwitchInst::removeCase(unsigned idx) { 2962 assert(idx != 0 && "Cannot remove the default case!"); 2963 assert(idx*2 < getNumOperands() && "Successor index out of range!!!"); 2964 2965 unsigned NumOps = getNumOperands(); 2966 Use *OL = OperandList; 2967 2968 // Move everything after this operand down. 2969 // 2970 // FIXME: we could just swap with the end of the list, then erase. However, 2971 // client might not expect this to happen. The code as it is thrashes the 2972 // use/def lists, which is kinda lame. 2973 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) { 2974 OL[i-2] = OL[i]; 2975 OL[i-2+1] = OL[i+1]; 2976 } 2977 2978 // Nuke the last value. 2979 OL[NumOps-2].set(0); 2980 OL[NumOps-2+1].set(0); 2981 NumOperands = NumOps-2; 2982} 2983 2984/// resizeOperands - resize operands - This adjusts the length of the operands 2985/// list according to the following behavior: 2986/// 1. If NumOps == 0, grow the operand list in response to a push_back style 2987/// of operation. This grows the number of ops by 3 times. 2988/// 2. If NumOps > NumOperands, reserve space for NumOps operands. 2989/// 3. If NumOps == NumOperands, trim the reserved space. 2990/// 2991void SwitchInst::resizeOperands(unsigned NumOps) { 2992 unsigned e = getNumOperands(); 2993 if (NumOps == 0) { 2994 NumOps = e*3; 2995 } else if (NumOps*2 > NumOperands) { 2996 // No resize needed. 2997 if (ReservedSpace >= NumOps) return; 2998 } else if (NumOps == NumOperands) { 2999 if (ReservedSpace == NumOps) return; 3000 } else { 3001 return; 3002 } 3003 3004 ReservedSpace = NumOps; 3005 Use *NewOps = allocHungoffUses(NumOps); 3006 Use *OldOps = OperandList; 3007 for (unsigned i = 0; i != e; ++i) { 3008 NewOps[i] = OldOps[i]; 3009 } 3010 OperandList = NewOps; 3011 if (OldOps) Use::zap(OldOps, OldOps + e, true); 3012} 3013 3014 3015BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const { 3016 return getSuccessor(idx); 3017} 3018unsigned SwitchInst::getNumSuccessorsV() const { 3019 return getNumSuccessors(); 3020} 3021void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) { 3022 setSuccessor(idx, B); 3023} 3024 3025// Define these methods here so vtables don't get emitted into every translation 3026// unit that uses these classes. 3027 3028GetElementPtrInst *GetElementPtrInst::clone() const { 3029 GetElementPtrInst *New = new(getNumOperands()) GetElementPtrInst(*this); 3030 New->SubclassOptionalData = SubclassOptionalData; 3031 if (hasMetadata()) { 3032 LLVMContext &Context = getContext(); 3033 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3034 } 3035 return New; 3036} 3037 3038BinaryOperator *BinaryOperator::clone() const { 3039 BinaryOperator *New = Create(getOpcode(), Op<0>(), Op<1>()); 3040 New->SubclassOptionalData = SubclassOptionalData; 3041 if (hasMetadata()) { 3042 LLVMContext &Context = getContext(); 3043 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3044 } 3045 return New; 3046} 3047 3048FCmpInst* FCmpInst::clone() const { 3049 FCmpInst *New = new FCmpInst(getPredicate(), Op<0>(), Op<1>()); 3050 New->SubclassOptionalData = SubclassOptionalData; 3051 if (hasMetadata()) { 3052 LLVMContext &Context = getContext(); 3053 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3054 } 3055 return New; 3056} 3057ICmpInst* ICmpInst::clone() const { 3058 ICmpInst *New = new ICmpInst(getPredicate(), Op<0>(), Op<1>()); 3059 New->SubclassOptionalData = SubclassOptionalData; 3060 if (hasMetadata()) { 3061 LLVMContext &Context = getContext(); 3062 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3063 } 3064 return New; 3065} 3066 3067ExtractValueInst *ExtractValueInst::clone() const { 3068 ExtractValueInst *New = new ExtractValueInst(*this); 3069 New->SubclassOptionalData = SubclassOptionalData; 3070 if (hasMetadata()) { 3071 LLVMContext &Context = getContext(); 3072 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3073 } 3074 return New; 3075} 3076InsertValueInst *InsertValueInst::clone() const { 3077 InsertValueInst *New = new InsertValueInst(*this); 3078 New->SubclassOptionalData = SubclassOptionalData; 3079 if (hasMetadata()) { 3080 LLVMContext &Context = getContext(); 3081 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3082 } 3083 return New; 3084} 3085 3086AllocaInst *AllocaInst::clone() const { 3087 AllocaInst *New = new AllocaInst(getAllocatedType(), 3088 (Value*)getOperand(0), 3089 getAlignment()); 3090 New->SubclassOptionalData = SubclassOptionalData; 3091 if (hasMetadata()) { 3092 LLVMContext &Context = getContext(); 3093 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3094 } 3095 return New; 3096} 3097 3098FreeInst *FreeInst::clone() const { 3099 FreeInst *New = new FreeInst(getOperand(0)); 3100 New->SubclassOptionalData = SubclassOptionalData; 3101 if (hasMetadata()) { 3102 LLVMContext &Context = getContext(); 3103 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3104 } 3105 return New; 3106} 3107 3108LoadInst *LoadInst::clone() const { 3109 LoadInst *New = new LoadInst(getOperand(0), 3110 Twine(), isVolatile(), 3111 getAlignment()); 3112 New->SubclassOptionalData = SubclassOptionalData; 3113 if (hasMetadata()) { 3114 LLVMContext &Context = getContext(); 3115 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3116 } 3117 return New; 3118} 3119 3120StoreInst *StoreInst::clone() const { 3121 StoreInst *New = new StoreInst(getOperand(0), getOperand(1), 3122 isVolatile(), getAlignment()); 3123 New->SubclassOptionalData = SubclassOptionalData; 3124 if (hasMetadata()) { 3125 LLVMContext &Context = getContext(); 3126 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3127 } 3128 return New; 3129} 3130 3131TruncInst *TruncInst::clone() const { 3132 TruncInst *New = new TruncInst(getOperand(0), getType()); 3133 New->SubclassOptionalData = SubclassOptionalData; 3134 if (hasMetadata()) { 3135 LLVMContext &Context = getContext(); 3136 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3137 } 3138 return New; 3139} 3140 3141ZExtInst *ZExtInst::clone() const { 3142 ZExtInst *New = new ZExtInst(getOperand(0), getType()); 3143 New->SubclassOptionalData = SubclassOptionalData; 3144 if (hasMetadata()) { 3145 LLVMContext &Context = getContext(); 3146 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3147 } 3148 return New; 3149} 3150 3151SExtInst *SExtInst::clone() const { 3152 SExtInst *New = new SExtInst(getOperand(0), getType()); 3153 New->SubclassOptionalData = SubclassOptionalData; 3154 if (hasMetadata()) { 3155 LLVMContext &Context = getContext(); 3156 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3157 } 3158 return New; 3159} 3160 3161FPTruncInst *FPTruncInst::clone() const { 3162 FPTruncInst *New = new FPTruncInst(getOperand(0), getType()); 3163 New->SubclassOptionalData = SubclassOptionalData; 3164 if (hasMetadata()) { 3165 LLVMContext &Context = getContext(); 3166 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3167 } 3168 return New; 3169} 3170 3171FPExtInst *FPExtInst::clone() const { 3172 FPExtInst *New = new FPExtInst(getOperand(0), getType()); 3173 New->SubclassOptionalData = SubclassOptionalData; 3174 if (hasMetadata()) { 3175 LLVMContext &Context = getContext(); 3176 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3177 } 3178 return New; 3179} 3180 3181UIToFPInst *UIToFPInst::clone() const { 3182 UIToFPInst *New = new UIToFPInst(getOperand(0), getType()); 3183 New->SubclassOptionalData = SubclassOptionalData; 3184 if (hasMetadata()) { 3185 LLVMContext &Context = getContext(); 3186 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3187 } 3188 return New; 3189} 3190 3191SIToFPInst *SIToFPInst::clone() const { 3192 SIToFPInst *New = new SIToFPInst(getOperand(0), getType()); 3193 New->SubclassOptionalData = SubclassOptionalData; 3194 if (hasMetadata()) { 3195 LLVMContext &Context = getContext(); 3196 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3197 } 3198 return New; 3199} 3200 3201FPToUIInst *FPToUIInst::clone() const { 3202 FPToUIInst *New = new FPToUIInst(getOperand(0), getType()); 3203 New->SubclassOptionalData = SubclassOptionalData; 3204 if (hasMetadata()) { 3205 LLVMContext &Context = getContext(); 3206 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3207 } 3208 return New; 3209} 3210 3211FPToSIInst *FPToSIInst::clone() const { 3212 FPToSIInst *New = new FPToSIInst(getOperand(0), getType()); 3213 New->SubclassOptionalData = SubclassOptionalData; 3214 if (hasMetadata()) { 3215 LLVMContext &Context = getContext(); 3216 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3217 } 3218 return New; 3219} 3220 3221PtrToIntInst *PtrToIntInst::clone() const { 3222 PtrToIntInst *New = new PtrToIntInst(getOperand(0), getType()); 3223 New->SubclassOptionalData = SubclassOptionalData; 3224 if (hasMetadata()) { 3225 LLVMContext &Context = getContext(); 3226 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3227 } 3228 return New; 3229} 3230 3231IntToPtrInst *IntToPtrInst::clone() const { 3232 IntToPtrInst *New = new IntToPtrInst(getOperand(0), getType()); 3233 New->SubclassOptionalData = SubclassOptionalData; 3234 if (hasMetadata()) { 3235 LLVMContext &Context = getContext(); 3236 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3237 } 3238 return New; 3239} 3240 3241BitCastInst *BitCastInst::clone() const { 3242 BitCastInst *New = new BitCastInst(getOperand(0), getType()); 3243 New->SubclassOptionalData = SubclassOptionalData; 3244 if (hasMetadata()) { 3245 LLVMContext &Context = getContext(); 3246 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3247 } 3248 return New; 3249} 3250 3251CallInst *CallInst::clone() const { 3252 CallInst *New = new(getNumOperands()) CallInst(*this); 3253 New->SubclassOptionalData = SubclassOptionalData; 3254 if (hasMetadata()) { 3255 LLVMContext &Context = getContext(); 3256 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3257 } 3258 return New; 3259} 3260 3261SelectInst *SelectInst::clone() const { 3262 SelectInst *New = SelectInst::Create(getOperand(0), 3263 getOperand(1), 3264 getOperand(2)); 3265 New->SubclassOptionalData = SubclassOptionalData; 3266 if (hasMetadata()) { 3267 LLVMContext &Context = getContext(); 3268 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3269 } 3270 return New; 3271} 3272 3273VAArgInst *VAArgInst::clone() const { 3274 VAArgInst *New = new VAArgInst(getOperand(0), getType()); 3275 New->SubclassOptionalData = SubclassOptionalData; 3276 if (hasMetadata()) { 3277 LLVMContext &Context = getContext(); 3278 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3279 } 3280 return New; 3281} 3282 3283ExtractElementInst *ExtractElementInst::clone() const { 3284 ExtractElementInst *New = ExtractElementInst::Create(getOperand(0), 3285 getOperand(1)); 3286 New->SubclassOptionalData = SubclassOptionalData; 3287 if (hasMetadata()) { 3288 LLVMContext &Context = getContext(); 3289 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3290 } 3291 return New; 3292} 3293 3294InsertElementInst *InsertElementInst::clone() const { 3295 InsertElementInst *New = InsertElementInst::Create(getOperand(0), 3296 getOperand(1), 3297 getOperand(2)); 3298 New->SubclassOptionalData = SubclassOptionalData; 3299 if (hasMetadata()) { 3300 LLVMContext &Context = getContext(); 3301 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3302 } 3303 return New; 3304} 3305 3306ShuffleVectorInst *ShuffleVectorInst::clone() const { 3307 ShuffleVectorInst *New = new ShuffleVectorInst(getOperand(0), 3308 getOperand(1), 3309 getOperand(2)); 3310 New->SubclassOptionalData = SubclassOptionalData; 3311 if (hasMetadata()) { 3312 LLVMContext &Context = getContext(); 3313 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3314 } 3315 return New; 3316} 3317 3318PHINode *PHINode::clone() const { 3319 PHINode *New = new PHINode(*this); 3320 New->SubclassOptionalData = SubclassOptionalData; 3321 if (hasMetadata()) { 3322 LLVMContext &Context = getContext(); 3323 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3324 } 3325 return New; 3326} 3327 3328ReturnInst *ReturnInst::clone() const { 3329 ReturnInst *New = new(getNumOperands()) ReturnInst(*this); 3330 New->SubclassOptionalData = SubclassOptionalData; 3331 if (hasMetadata()) { 3332 LLVMContext &Context = getContext(); 3333 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3334 } 3335 return New; 3336} 3337 3338BranchInst *BranchInst::clone() const { 3339 unsigned Ops(getNumOperands()); 3340 BranchInst *New = new(Ops, Ops == 1) BranchInst(*this); 3341 New->SubclassOptionalData = SubclassOptionalData; 3342 if (hasMetadata()) { 3343 LLVMContext &Context = getContext(); 3344 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3345 } 3346 return New; 3347} 3348 3349SwitchInst *SwitchInst::clone() const { 3350 SwitchInst *New = new SwitchInst(*this); 3351 New->SubclassOptionalData = SubclassOptionalData; 3352 if (hasMetadata()) { 3353 LLVMContext &Context = getContext(); 3354 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3355 } 3356 return New; 3357} 3358 3359InvokeInst *InvokeInst::clone() const { 3360 InvokeInst *New = new(getNumOperands()) InvokeInst(*this); 3361 New->SubclassOptionalData = SubclassOptionalData; 3362 if (hasMetadata()) { 3363 LLVMContext &Context = getContext(); 3364 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3365 } 3366 return New; 3367} 3368 3369UnwindInst *UnwindInst::clone() const { 3370 LLVMContext &Context = getContext(); 3371 UnwindInst *New = new UnwindInst(Context); 3372 New->SubclassOptionalData = SubclassOptionalData; 3373 if (hasMetadata()) 3374 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3375 return New; 3376} 3377 3378UnreachableInst *UnreachableInst::clone() const { 3379 LLVMContext &Context = getContext(); 3380 UnreachableInst *New = new UnreachableInst(Context); 3381 New->SubclassOptionalData = SubclassOptionalData; 3382 if (hasMetadata()) 3383 Context.pImpl->TheMetadata.ValueIsCloned(this, New); 3384 return New; 3385} 3386