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