1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/MathExtras.h"
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 User::op_iterator CallSite::getCallee() const {
33 Instruction *II(getInstruction());
35 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
36 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
39 //===----------------------------------------------------------------------===//
40 // TerminatorInst Class
41 //===----------------------------------------------------------------------===//
43 // Out of line virtual method, so the vtable, etc has a home.
44 TerminatorInst::~TerminatorInst() {
47 //===----------------------------------------------------------------------===//
48 // UnaryInstruction Class
49 //===----------------------------------------------------------------------===//
51 // Out of line virtual method, so the vtable, etc has a home.
52 UnaryInstruction::~UnaryInstruction() {
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 /// areInvalidOperands - Return a string if the specified operands are invalid
60 /// for a select operation, otherwise return null.
61 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
62 if (Op1->getType() != Op2->getType())
63 return "both values to select must have same type";
65 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
67 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
68 return "vector select condition element type must be i1";
69 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
71 return "selected values for vector select must be vectors";
72 if (ET->getNumElements() != VT->getNumElements())
73 return "vector select requires selected vectors to have "
74 "the same vector length as select condition";
75 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
76 return "select condition must be i1 or <n x i1>";
82 //===----------------------------------------------------------------------===//
84 //===----------------------------------------------------------------------===//
86 PHINode::PHINode(const PHINode &PN)
87 : Instruction(PN.getType(), Instruction::PHI,
88 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
89 ReservedSpace(PN.getNumOperands()) {
90 std::copy(PN.op_begin(), PN.op_end(), op_begin());
91 std::copy(PN.block_begin(), PN.block_end(), block_begin());
92 SubclassOptionalData = PN.SubclassOptionalData;
99 Use *PHINode::allocHungoffUses(unsigned N) const {
100 // Allocate the array of Uses of the incoming values, followed by a pointer
101 // (with bottom bit set) to the User, followed by the array of pointers to
102 // the incoming basic blocks.
103 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
104 + N * sizeof(BasicBlock*);
105 Use *Begin = static_cast<Use*>(::operator new(size));
106 Use *End = Begin + N;
107 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
108 return Use::initTags(Begin, End);
111 // removeIncomingValue - Remove an incoming value. This is useful if a
112 // predecessor basic block is deleted.
113 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
114 Value *Removed = getIncomingValue(Idx);
116 // Move everything after this operand down.
118 // FIXME: we could just swap with the end of the list, then erase. However,
119 // clients might not expect this to happen. The code as it is thrashes the
120 // use/def lists, which is kinda lame.
121 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
122 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
124 // Nuke the last value.
128 // If the PHI node is dead, because it has zero entries, nuke it now.
129 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
130 // If anyone is using this PHI, make them use a dummy value instead...
131 replaceAllUsesWith(UndefValue::get(getType()));
137 /// growOperands - grow operands - This grows the operand list in response
138 /// to a push_back style of operation. This grows the number of ops by 1.5
141 void PHINode::growOperands() {
142 unsigned e = getNumOperands();
143 unsigned NumOps = e + e / 2;
144 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
146 Use *OldOps = op_begin();
147 BasicBlock **OldBlocks = block_begin();
149 ReservedSpace = NumOps;
150 OperandList = allocHungoffUses(ReservedSpace);
152 std::copy(OldOps, OldOps + e, op_begin());
153 std::copy(OldBlocks, OldBlocks + e, block_begin());
155 Use::zap(OldOps, OldOps + e, true);
158 /// hasConstantValue - If the specified PHI node always merges together the same
159 /// value, return the value, otherwise return null.
160 Value *PHINode::hasConstantValue() const {
161 // Exploit the fact that phi nodes always have at least one entry.
162 Value *ConstantValue = getIncomingValue(0);
163 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
164 if (getIncomingValue(i) != ConstantValue)
165 return 0; // Incoming values not all the same.
166 return ConstantValue;
169 //===----------------------------------------------------------------------===//
170 // LandingPadInst Implementation
171 //===----------------------------------------------------------------------===//
173 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
174 unsigned NumReservedValues, const Twine &NameStr,
175 Instruction *InsertBefore)
176 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
177 init(PersonalityFn, 1 + NumReservedValues, NameStr);
180 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
181 unsigned NumReservedValues, const Twine &NameStr,
182 BasicBlock *InsertAtEnd)
183 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
184 init(PersonalityFn, 1 + NumReservedValues, NameStr);
187 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
188 : Instruction(LP.getType(), Instruction::LandingPad,
189 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
190 ReservedSpace(LP.getNumOperands()) {
191 Use *OL = OperandList, *InOL = LP.OperandList;
192 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
195 setCleanup(LP.isCleanup());
198 LandingPadInst::~LandingPadInst() {
202 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
203 unsigned NumReservedClauses,
204 const Twine &NameStr,
205 Instruction *InsertBefore) {
206 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
210 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
211 unsigned NumReservedClauses,
212 const Twine &NameStr,
213 BasicBlock *InsertAtEnd) {
214 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
218 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
219 const Twine &NameStr) {
220 ReservedSpace = NumReservedValues;
222 OperandList = allocHungoffUses(ReservedSpace);
223 OperandList[0] = PersFn;
228 /// growOperands - grow operands - This grows the operand list in response to a
229 /// push_back style of operation. This grows the number of ops by 2 times.
230 void LandingPadInst::growOperands(unsigned Size) {
231 unsigned e = getNumOperands();
232 if (ReservedSpace >= e + Size) return;
233 ReservedSpace = (e + Size / 2) * 2;
235 Use *NewOps = allocHungoffUses(ReservedSpace);
236 Use *OldOps = OperandList;
237 for (unsigned i = 0; i != e; ++i)
238 NewOps[i] = OldOps[i];
240 OperandList = NewOps;
241 Use::zap(OldOps, OldOps + e, true);
244 void LandingPadInst::addClause(Value *Val) {
245 unsigned OpNo = getNumOperands();
247 assert(OpNo < ReservedSpace && "Growing didn't work!");
249 OperandList[OpNo] = Val;
252 //===----------------------------------------------------------------------===//
253 // CallInst Implementation
254 //===----------------------------------------------------------------------===//
256 CallInst::~CallInst() {
259 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
260 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
265 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
267 assert((Args.size() == FTy->getNumParams() ||
268 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
269 "Calling a function with bad signature!");
271 for (unsigned i = 0; i != Args.size(); ++i)
272 assert((i >= FTy->getNumParams() ||
273 FTy->getParamType(i) == Args[i]->getType()) &&
274 "Calling a function with a bad signature!");
277 std::copy(Args.begin(), Args.end(), op_begin());
281 void CallInst::init(Value *Func, const Twine &NameStr) {
282 assert(NumOperands == 1 && "NumOperands not set up?");
287 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
289 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
295 CallInst::CallInst(Value *Func, const Twine &Name,
296 Instruction *InsertBefore)
297 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
298 ->getElementType())->getReturnType(),
300 OperandTraits<CallInst>::op_end(this) - 1,
305 CallInst::CallInst(Value *Func, const Twine &Name,
306 BasicBlock *InsertAtEnd)
307 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
308 ->getElementType())->getReturnType(),
310 OperandTraits<CallInst>::op_end(this) - 1,
315 CallInst::CallInst(const CallInst &CI)
316 : Instruction(CI.getType(), Instruction::Call,
317 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
318 CI.getNumOperands()) {
319 setAttributes(CI.getAttributes());
320 setTailCall(CI.isTailCall());
321 setCallingConv(CI.getCallingConv());
323 std::copy(CI.op_begin(), CI.op_end(), op_begin());
324 SubclassOptionalData = CI.SubclassOptionalData;
327 void CallInst::addAttribute(unsigned i, Attributes attr) {
328 AttrListPtr PAL = getAttributes();
329 PAL = PAL.addAttr(i, attr);
333 void CallInst::removeAttribute(unsigned i, Attributes attr) {
334 AttrListPtr PAL = getAttributes();
335 PAL = PAL.removeAttr(i, attr);
339 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
340 if (AttributeList.paramHasAttr(i, attr))
342 if (const Function *F = getCalledFunction())
343 return F->paramHasAttr(i, attr);
347 /// IsConstantOne - Return true only if val is constant int 1
348 static bool IsConstantOne(Value *val) {
349 assert(val && "IsConstantOne does not work with NULL val");
350 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
353 static Instruction *createMalloc(Instruction *InsertBefore,
354 BasicBlock *InsertAtEnd, Type *IntPtrTy,
355 Type *AllocTy, Value *AllocSize,
356 Value *ArraySize, Function *MallocF,
358 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
359 "createMalloc needs either InsertBefore or InsertAtEnd");
361 // malloc(type) becomes:
362 // bitcast (i8* malloc(typeSize)) to type*
363 // malloc(type, arraySize) becomes:
364 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
366 ArraySize = ConstantInt::get(IntPtrTy, 1);
367 else if (ArraySize->getType() != IntPtrTy) {
369 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
372 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
376 if (!IsConstantOne(ArraySize)) {
377 if (IsConstantOne(AllocSize)) {
378 AllocSize = ArraySize; // Operand * 1 = Operand
379 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
380 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
382 // Malloc arg is constant product of type size and array size
383 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
385 // Multiply type size by the array size...
387 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
388 "mallocsize", InsertBefore);
390 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
391 "mallocsize", InsertAtEnd);
395 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
396 // Create the call to Malloc.
397 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
398 Module* M = BB->getParent()->getParent();
399 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
400 Value *MallocFunc = MallocF;
402 // prototype malloc as "void *malloc(size_t)"
403 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
404 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
405 CallInst *MCall = NULL;
406 Instruction *Result = NULL;
408 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
410 if (Result->getType() != AllocPtrType)
411 // Create a cast instruction to convert to the right type...
412 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
414 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
416 if (Result->getType() != AllocPtrType) {
417 InsertAtEnd->getInstList().push_back(MCall);
418 // Create a cast instruction to convert to the right type...
419 Result = new BitCastInst(MCall, AllocPtrType, Name);
422 MCall->setTailCall();
423 if (Function *F = dyn_cast<Function>(MallocFunc)) {
424 MCall->setCallingConv(F->getCallingConv());
425 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
427 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
432 /// CreateMalloc - Generate the IR for a call to malloc:
433 /// 1. Compute the malloc call's argument as the specified type's size,
434 /// possibly multiplied by the array size if the array size is not
436 /// 2. Call malloc with that argument.
437 /// 3. Bitcast the result of the malloc call to the specified type.
438 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
439 Type *IntPtrTy, Type *AllocTy,
440 Value *AllocSize, Value *ArraySize,
443 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
444 ArraySize, MallocF, Name);
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
451 /// 2. Call malloc with that argument.
452 /// 3. Bitcast the result of the malloc call to the specified type.
453 /// Note: This function does not add the bitcast to the basic block, that is the
454 /// responsibility of the caller.
455 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
456 Type *IntPtrTy, Type *AllocTy,
457 Value *AllocSize, Value *ArraySize,
458 Function *MallocF, const Twine &Name) {
459 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
460 ArraySize, MallocF, Name);
463 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
464 BasicBlock *InsertAtEnd) {
465 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
466 "createFree needs either InsertBefore or InsertAtEnd");
467 assert(Source->getType()->isPointerTy() &&
468 "Can not free something of nonpointer type!");
470 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
471 Module* M = BB->getParent()->getParent();
473 Type *VoidTy = Type::getVoidTy(M->getContext());
474 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
475 // prototype free as "void free(void*)"
476 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
477 CallInst* Result = NULL;
478 Value *PtrCast = Source;
480 if (Source->getType() != IntPtrTy)
481 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
482 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
484 if (Source->getType() != IntPtrTy)
485 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
486 Result = CallInst::Create(FreeFunc, PtrCast, "");
488 Result->setTailCall();
489 if (Function *F = dyn_cast<Function>(FreeFunc))
490 Result->setCallingConv(F->getCallingConv());
495 /// CreateFree - Generate the IR for a call to the builtin free function.
496 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
497 return createFree(Source, InsertBefore, NULL);
500 /// CreateFree - Generate the IR for a call to the builtin free function.
501 /// Note: This function does not add the call to the basic block, that is the
502 /// responsibility of the caller.
503 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
504 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
505 assert(FreeCall && "CreateFree did not create a CallInst");
509 //===----------------------------------------------------------------------===//
510 // InvokeInst Implementation
511 //===----------------------------------------------------------------------===//
513 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
514 ArrayRef<Value *> Args, const Twine &NameStr) {
515 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
518 Op<-1>() = IfException;
522 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
524 assert(((Args.size() == FTy->getNumParams()) ||
525 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
526 "Invoking a function with bad signature");
528 for (unsigned i = 0, e = Args.size(); i != e; i++)
529 assert((i >= FTy->getNumParams() ||
530 FTy->getParamType(i) == Args[i]->getType()) &&
531 "Invoking a function with a bad signature!");
534 std::copy(Args.begin(), Args.end(), op_begin());
538 InvokeInst::InvokeInst(const InvokeInst &II)
539 : TerminatorInst(II.getType(), Instruction::Invoke,
540 OperandTraits<InvokeInst>::op_end(this)
541 - II.getNumOperands(),
542 II.getNumOperands()) {
543 setAttributes(II.getAttributes());
544 setCallingConv(II.getCallingConv());
545 std::copy(II.op_begin(), II.op_end(), op_begin());
546 SubclassOptionalData = II.SubclassOptionalData;
549 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
550 return getSuccessor(idx);
552 unsigned InvokeInst::getNumSuccessorsV() const {
553 return getNumSuccessors();
555 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
556 return setSuccessor(idx, B);
559 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
560 if (AttributeList.paramHasAttr(i, attr))
562 if (const Function *F = getCalledFunction())
563 return F->paramHasAttr(i, attr);
567 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
568 AttrListPtr PAL = getAttributes();
569 PAL = PAL.addAttr(i, attr);
573 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
574 AttrListPtr PAL = getAttributes();
575 PAL = PAL.removeAttr(i, attr);
579 LandingPadInst *InvokeInst::getLandingPadInst() const {
580 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
583 //===----------------------------------------------------------------------===//
584 // ReturnInst Implementation
585 //===----------------------------------------------------------------------===//
587 ReturnInst::ReturnInst(const ReturnInst &RI)
588 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
589 OperandTraits<ReturnInst>::op_end(this) -
591 RI.getNumOperands()) {
592 if (RI.getNumOperands())
593 Op<0>() = RI.Op<0>();
594 SubclassOptionalData = RI.SubclassOptionalData;
597 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
598 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
599 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
604 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
605 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
606 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
611 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
612 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
613 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
616 unsigned ReturnInst::getNumSuccessorsV() const {
617 return getNumSuccessors();
620 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
621 /// emit the vtable for the class in this translation unit.
622 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
623 llvm_unreachable("ReturnInst has no successors!");
626 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
627 llvm_unreachable("ReturnInst has no successors!");
630 ReturnInst::~ReturnInst() {
633 //===----------------------------------------------------------------------===//
634 // UnwindInst Implementation
635 //===----------------------------------------------------------------------===//
637 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
638 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
639 0, 0, InsertBefore) {
641 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
642 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
647 unsigned UnwindInst::getNumSuccessorsV() const {
648 return getNumSuccessors();
651 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
652 llvm_unreachable("UnwindInst has no successors!");
655 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
656 llvm_unreachable("UnwindInst has no successors!");
659 //===----------------------------------------------------------------------===//
660 // ResumeInst Implementation
661 //===----------------------------------------------------------------------===//
663 ResumeInst::ResumeInst(const ResumeInst &RI)
664 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
665 OperandTraits<ResumeInst>::op_begin(this), 1) {
666 Op<0>() = RI.Op<0>();
669 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
670 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
671 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
675 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
676 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
677 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
681 unsigned ResumeInst::getNumSuccessorsV() const {
682 return getNumSuccessors();
685 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
686 llvm_unreachable("ResumeInst has no successors!");
689 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
690 llvm_unreachable("ResumeInst has no successors!");
693 //===----------------------------------------------------------------------===//
694 // UnreachableInst Implementation
695 //===----------------------------------------------------------------------===//
697 UnreachableInst::UnreachableInst(LLVMContext &Context,
698 Instruction *InsertBefore)
699 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
700 0, 0, InsertBefore) {
702 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
703 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
707 unsigned UnreachableInst::getNumSuccessorsV() const {
708 return getNumSuccessors();
711 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
712 llvm_unreachable("UnwindInst has no successors!");
715 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
716 llvm_unreachable("UnwindInst has no successors!");
719 //===----------------------------------------------------------------------===//
720 // BranchInst Implementation
721 //===----------------------------------------------------------------------===//
723 void BranchInst::AssertOK() {
725 assert(getCondition()->getType()->isIntegerTy(1) &&
726 "May only branch on boolean predicates!");
729 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
730 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
731 OperandTraits<BranchInst>::op_end(this) - 1,
733 assert(IfTrue != 0 && "Branch destination may not be null!");
736 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
737 Instruction *InsertBefore)
738 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
739 OperandTraits<BranchInst>::op_end(this) - 3,
749 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
750 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
751 OperandTraits<BranchInst>::op_end(this) - 1,
753 assert(IfTrue != 0 && "Branch destination may not be null!");
757 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
758 BasicBlock *InsertAtEnd)
759 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
760 OperandTraits<BranchInst>::op_end(this) - 3,
771 BranchInst::BranchInst(const BranchInst &BI) :
772 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
773 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
774 BI.getNumOperands()) {
775 Op<-1>() = BI.Op<-1>();
776 if (BI.getNumOperands() != 1) {
777 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
778 Op<-3>() = BI.Op<-3>();
779 Op<-2>() = BI.Op<-2>();
781 SubclassOptionalData = BI.SubclassOptionalData;
784 void BranchInst::swapSuccessors() {
785 assert(isConditional() &&
786 "Cannot swap successors of an unconditional branch");
787 Op<-1>().swap(Op<-2>());
789 // Update profile metadata if present and it matches our structural
791 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
792 if (!ProfileData || ProfileData->getNumOperands() != 3)
795 // The first operand is the name. Fetch them backwards and build a new one.
797 ProfileData->getOperand(0),
798 ProfileData->getOperand(2),
799 ProfileData->getOperand(1)
801 setMetadata(LLVMContext::MD_prof,
802 MDNode::get(ProfileData->getContext(), Ops));
805 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
806 return getSuccessor(idx);
808 unsigned BranchInst::getNumSuccessorsV() const {
809 return getNumSuccessors();
811 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
812 setSuccessor(idx, B);
816 //===----------------------------------------------------------------------===//
817 // AllocaInst Implementation
818 //===----------------------------------------------------------------------===//
820 static Value *getAISize(LLVMContext &Context, Value *Amt) {
822 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
824 assert(!isa<BasicBlock>(Amt) &&
825 "Passed basic block into allocation size parameter! Use other ctor");
826 assert(Amt->getType()->isIntegerTy() &&
827 "Allocation array size is not an integer!");
832 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
833 const Twine &Name, Instruction *InsertBefore)
834 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
835 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
837 assert(!Ty->isVoidTy() && "Cannot allocate void!");
841 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
842 const Twine &Name, BasicBlock *InsertAtEnd)
843 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
844 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
846 assert(!Ty->isVoidTy() && "Cannot allocate void!");
850 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
851 Instruction *InsertBefore)
852 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
853 getAISize(Ty->getContext(), 0), InsertBefore) {
855 assert(!Ty->isVoidTy() && "Cannot allocate void!");
859 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
860 BasicBlock *InsertAtEnd)
861 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
862 getAISize(Ty->getContext(), 0), InsertAtEnd) {
864 assert(!Ty->isVoidTy() && "Cannot allocate void!");
868 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
869 const Twine &Name, Instruction *InsertBefore)
870 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
871 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
873 assert(!Ty->isVoidTy() && "Cannot allocate void!");
877 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
878 const Twine &Name, BasicBlock *InsertAtEnd)
879 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
880 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
882 assert(!Ty->isVoidTy() && "Cannot allocate void!");
886 // Out of line virtual method, so the vtable, etc has a home.
887 AllocaInst::~AllocaInst() {
890 void AllocaInst::setAlignment(unsigned Align) {
891 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
892 assert(Align <= MaximumAlignment &&
893 "Alignment is greater than MaximumAlignment!");
894 setInstructionSubclassData(Log2_32(Align) + 1);
895 assert(getAlignment() == Align && "Alignment representation error!");
898 bool AllocaInst::isArrayAllocation() const {
899 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
904 Type *AllocaInst::getAllocatedType() const {
905 return getType()->getElementType();
908 /// isStaticAlloca - Return true if this alloca is in the entry block of the
909 /// function and is a constant size. If so, the code generator will fold it
910 /// into the prolog/epilog code, so it is basically free.
911 bool AllocaInst::isStaticAlloca() const {
912 // Must be constant size.
913 if (!isa<ConstantInt>(getArraySize())) return false;
915 // Must be in the entry block.
916 const BasicBlock *Parent = getParent();
917 return Parent == &Parent->getParent()->front();
920 //===----------------------------------------------------------------------===//
921 // LoadInst Implementation
922 //===----------------------------------------------------------------------===//
924 void LoadInst::AssertOK() {
925 assert(getOperand(0)->getType()->isPointerTy() &&
926 "Ptr must have pointer type.");
927 assert(!(isAtomic() && getAlignment() == 0) &&
928 "Alignment required for atomic load");
931 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
932 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
933 Load, Ptr, InsertBef) {
936 setAtomic(NotAtomic);
941 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
942 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
943 Load, Ptr, InsertAE) {
946 setAtomic(NotAtomic);
951 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
952 Instruction *InsertBef)
953 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
954 Load, Ptr, InsertBef) {
955 setVolatile(isVolatile);
957 setAtomic(NotAtomic);
962 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
963 BasicBlock *InsertAE)
964 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
965 Load, Ptr, InsertAE) {
966 setVolatile(isVolatile);
968 setAtomic(NotAtomic);
973 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
974 unsigned Align, Instruction *InsertBef)
975 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
976 Load, Ptr, InsertBef) {
977 setVolatile(isVolatile);
979 setAtomic(NotAtomic);
984 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
985 unsigned Align, BasicBlock *InsertAE)
986 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
987 Load, Ptr, InsertAE) {
988 setVolatile(isVolatile);
990 setAtomic(NotAtomic);
995 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
996 unsigned Align, AtomicOrdering Order,
997 SynchronizationScope SynchScope,
998 Instruction *InsertBef)
999 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1000 Load, Ptr, InsertBef) {
1001 setVolatile(isVolatile);
1002 setAlignment(Align);
1003 setAtomic(Order, SynchScope);
1008 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1009 unsigned Align, AtomicOrdering Order,
1010 SynchronizationScope SynchScope,
1011 BasicBlock *InsertAE)
1012 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1013 Load, Ptr, InsertAE) {
1014 setVolatile(isVolatile);
1015 setAlignment(Align);
1016 setAtomic(Order, SynchScope);
1021 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1022 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1023 Load, Ptr, InsertBef) {
1026 setAtomic(NotAtomic);
1028 if (Name && Name[0]) setName(Name);
1031 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1032 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1033 Load, Ptr, InsertAE) {
1036 setAtomic(NotAtomic);
1038 if (Name && Name[0]) setName(Name);
1041 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1042 Instruction *InsertBef)
1043 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1044 Load, Ptr, InsertBef) {
1045 setVolatile(isVolatile);
1047 setAtomic(NotAtomic);
1049 if (Name && Name[0]) setName(Name);
1052 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1053 BasicBlock *InsertAE)
1054 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1055 Load, Ptr, InsertAE) {
1056 setVolatile(isVolatile);
1058 setAtomic(NotAtomic);
1060 if (Name && Name[0]) setName(Name);
1063 void LoadInst::setAlignment(unsigned Align) {
1064 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1065 assert(Align <= MaximumAlignment &&
1066 "Alignment is greater than MaximumAlignment!");
1067 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1068 ((Log2_32(Align)+1)<<1));
1069 assert(getAlignment() == Align && "Alignment representation error!");
1072 //===----------------------------------------------------------------------===//
1073 // StoreInst Implementation
1074 //===----------------------------------------------------------------------===//
1076 void StoreInst::AssertOK() {
1077 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1078 assert(getOperand(1)->getType()->isPointerTy() &&
1079 "Ptr must have pointer type!");
1080 assert(getOperand(0)->getType() ==
1081 cast<PointerType>(getOperand(1)->getType())->getElementType()
1082 && "Ptr must be a pointer to Val type!");
1083 assert(!(isAtomic() && getAlignment() == 0) &&
1084 "Alignment required for atomic load");
1088 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1089 : Instruction(Type::getVoidTy(val->getContext()), Store,
1090 OperandTraits<StoreInst>::op_begin(this),
1091 OperandTraits<StoreInst>::operands(this),
1097 setAtomic(NotAtomic);
1101 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1102 : Instruction(Type::getVoidTy(val->getContext()), Store,
1103 OperandTraits<StoreInst>::op_begin(this),
1104 OperandTraits<StoreInst>::operands(this),
1110 setAtomic(NotAtomic);
1114 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1115 Instruction *InsertBefore)
1116 : Instruction(Type::getVoidTy(val->getContext()), Store,
1117 OperandTraits<StoreInst>::op_begin(this),
1118 OperandTraits<StoreInst>::operands(this),
1122 setVolatile(isVolatile);
1124 setAtomic(NotAtomic);
1128 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1129 unsigned Align, Instruction *InsertBefore)
1130 : Instruction(Type::getVoidTy(val->getContext()), Store,
1131 OperandTraits<StoreInst>::op_begin(this),
1132 OperandTraits<StoreInst>::operands(this),
1136 setVolatile(isVolatile);
1137 setAlignment(Align);
1138 setAtomic(NotAtomic);
1142 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1143 unsigned Align, AtomicOrdering Order,
1144 SynchronizationScope SynchScope,
1145 Instruction *InsertBefore)
1146 : Instruction(Type::getVoidTy(val->getContext()), Store,
1147 OperandTraits<StoreInst>::op_begin(this),
1148 OperandTraits<StoreInst>::operands(this),
1152 setVolatile(isVolatile);
1153 setAlignment(Align);
1154 setAtomic(Order, SynchScope);
1158 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1159 BasicBlock *InsertAtEnd)
1160 : Instruction(Type::getVoidTy(val->getContext()), Store,
1161 OperandTraits<StoreInst>::op_begin(this),
1162 OperandTraits<StoreInst>::operands(this),
1166 setVolatile(isVolatile);
1168 setAtomic(NotAtomic);
1172 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1173 unsigned Align, BasicBlock *InsertAtEnd)
1174 : Instruction(Type::getVoidTy(val->getContext()), Store,
1175 OperandTraits<StoreInst>::op_begin(this),
1176 OperandTraits<StoreInst>::operands(this),
1180 setVolatile(isVolatile);
1181 setAlignment(Align);
1182 setAtomic(NotAtomic);
1186 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1187 unsigned Align, AtomicOrdering Order,
1188 SynchronizationScope SynchScope,
1189 BasicBlock *InsertAtEnd)
1190 : Instruction(Type::getVoidTy(val->getContext()), Store,
1191 OperandTraits<StoreInst>::op_begin(this),
1192 OperandTraits<StoreInst>::operands(this),
1196 setVolatile(isVolatile);
1197 setAlignment(Align);
1198 setAtomic(Order, SynchScope);
1202 void StoreInst::setAlignment(unsigned Align) {
1203 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1204 assert(Align <= MaximumAlignment &&
1205 "Alignment is greater than MaximumAlignment!");
1206 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1207 ((Log2_32(Align)+1) << 1));
1208 assert(getAlignment() == Align && "Alignment representation error!");
1211 //===----------------------------------------------------------------------===//
1212 // AtomicCmpXchgInst Implementation
1213 //===----------------------------------------------------------------------===//
1215 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1216 AtomicOrdering Ordering,
1217 SynchronizationScope SynchScope) {
1221 setOrdering(Ordering);
1222 setSynchScope(SynchScope);
1224 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1225 "All operands must be non-null!");
1226 assert(getOperand(0)->getType()->isPointerTy() &&
1227 "Ptr must have pointer type!");
1228 assert(getOperand(1)->getType() ==
1229 cast<PointerType>(getOperand(0)->getType())->getElementType()
1230 && "Ptr must be a pointer to Cmp type!");
1231 assert(getOperand(2)->getType() ==
1232 cast<PointerType>(getOperand(0)->getType())->getElementType()
1233 && "Ptr must be a pointer to NewVal type!");
1234 assert(Ordering != NotAtomic &&
1235 "AtomicCmpXchg instructions must be atomic!");
1238 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1239 AtomicOrdering Ordering,
1240 SynchronizationScope SynchScope,
1241 Instruction *InsertBefore)
1242 : Instruction(Cmp->getType(), AtomicCmpXchg,
1243 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1244 OperandTraits<AtomicCmpXchgInst>::operands(this),
1246 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1249 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1250 AtomicOrdering Ordering,
1251 SynchronizationScope SynchScope,
1252 BasicBlock *InsertAtEnd)
1253 : Instruction(Cmp->getType(), AtomicCmpXchg,
1254 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1255 OperandTraits<AtomicCmpXchgInst>::operands(this),
1257 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1260 //===----------------------------------------------------------------------===//
1261 // AtomicRMWInst Implementation
1262 //===----------------------------------------------------------------------===//
1264 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1265 AtomicOrdering Ordering,
1266 SynchronizationScope SynchScope) {
1269 setOperation(Operation);
1270 setOrdering(Ordering);
1271 setSynchScope(SynchScope);
1273 assert(getOperand(0) && getOperand(1) &&
1274 "All operands must be non-null!");
1275 assert(getOperand(0)->getType()->isPointerTy() &&
1276 "Ptr must have pointer type!");
1277 assert(getOperand(1)->getType() ==
1278 cast<PointerType>(getOperand(0)->getType())->getElementType()
1279 && "Ptr must be a pointer to Val type!");
1280 assert(Ordering != NotAtomic &&
1281 "AtomicRMW instructions must be atomic!");
1284 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1285 AtomicOrdering Ordering,
1286 SynchronizationScope SynchScope,
1287 Instruction *InsertBefore)
1288 : Instruction(Val->getType(), AtomicRMW,
1289 OperandTraits<AtomicRMWInst>::op_begin(this),
1290 OperandTraits<AtomicRMWInst>::operands(this),
1292 Init(Operation, Ptr, Val, Ordering, SynchScope);
1295 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1296 AtomicOrdering Ordering,
1297 SynchronizationScope SynchScope,
1298 BasicBlock *InsertAtEnd)
1299 : Instruction(Val->getType(), AtomicRMW,
1300 OperandTraits<AtomicRMWInst>::op_begin(this),
1301 OperandTraits<AtomicRMWInst>::operands(this),
1303 Init(Operation, Ptr, Val, Ordering, SynchScope);
1306 //===----------------------------------------------------------------------===//
1307 // FenceInst Implementation
1308 //===----------------------------------------------------------------------===//
1310 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1311 SynchronizationScope SynchScope,
1312 Instruction *InsertBefore)
1313 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1314 setOrdering(Ordering);
1315 setSynchScope(SynchScope);
1318 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1319 SynchronizationScope SynchScope,
1320 BasicBlock *InsertAtEnd)
1321 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1322 setOrdering(Ordering);
1323 setSynchScope(SynchScope);
1326 //===----------------------------------------------------------------------===//
1327 // GetElementPtrInst Implementation
1328 //===----------------------------------------------------------------------===//
1330 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1331 const Twine &Name) {
1332 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1333 OperandList[0] = Ptr;
1334 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1338 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1339 : Instruction(GEPI.getType(), GetElementPtr,
1340 OperandTraits<GetElementPtrInst>::op_end(this)
1341 - GEPI.getNumOperands(),
1342 GEPI.getNumOperands()) {
1343 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1344 SubclassOptionalData = GEPI.SubclassOptionalData;
1347 /// getIndexedType - Returns the type of the element that would be accessed with
1348 /// a gep instruction with the specified parameters.
1350 /// The Idxs pointer should point to a continuous piece of memory containing the
1351 /// indices, either as Value* or uint64_t.
1353 /// A null type is returned if the indices are invalid for the specified
1356 template <typename IndexTy>
1357 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1358 if (Ptr->isVectorTy()) {
1359 assert(IdxList.size() == 1 &&
1360 "GEP with vector pointers must have a single index");
1361 PointerType *PTy = dyn_cast<PointerType>(
1362 cast<VectorType>(Ptr)->getElementType());
1363 assert(PTy && "Gep with invalid vector pointer found");
1364 return PTy->getElementType();
1367 PointerType *PTy = dyn_cast<PointerType>(Ptr);
1368 if (!PTy) return 0; // Type isn't a pointer type!
1369 Type *Agg = PTy->getElementType();
1371 // Handle the special case of the empty set index set, which is always valid.
1372 if (IdxList.empty())
1375 // If there is at least one index, the top level type must be sized, otherwise
1376 // it cannot be 'stepped over'.
1377 if (!Agg->isSized())
1380 unsigned CurIdx = 1;
1381 for (; CurIdx != IdxList.size(); ++CurIdx) {
1382 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1383 if (!CT || CT->isPointerTy()) return 0;
1384 IndexTy Index = IdxList[CurIdx];
1385 if (!CT->indexValid(Index)) return 0;
1386 Agg = CT->getTypeAtIndex(Index);
1388 return CurIdx == IdxList.size() ? Agg : 0;
1391 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1392 return getIndexedTypeInternal(Ptr, IdxList);
1395 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1396 ArrayRef<Constant *> IdxList) {
1397 return getIndexedTypeInternal(Ptr, IdxList);
1400 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1401 return getIndexedTypeInternal(Ptr, IdxList);
1404 unsigned GetElementPtrInst::getAddressSpace(Value *Ptr) {
1405 Type *Ty = Ptr->getType();
1407 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1408 Ty = VTy->getElementType();
1410 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1411 return PTy->getAddressSpace();
1413 assert(false && "Invalid GEP pointer type");
1417 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1418 /// zeros. If so, the result pointer and the first operand have the same
1419 /// value, just potentially different types.
1420 bool GetElementPtrInst::hasAllZeroIndices() const {
1421 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1422 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1423 if (!CI->isZero()) return false;
1431 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1432 /// constant integers. If so, the result pointer and the first operand have
1433 /// a constant offset between them.
1434 bool GetElementPtrInst::hasAllConstantIndices() const {
1435 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1436 if (!isa<ConstantInt>(getOperand(i)))
1442 void GetElementPtrInst::setIsInBounds(bool B) {
1443 cast<GEPOperator>(this)->setIsInBounds(B);
1446 bool GetElementPtrInst::isInBounds() const {
1447 return cast<GEPOperator>(this)->isInBounds();
1450 //===----------------------------------------------------------------------===//
1451 // ExtractElementInst Implementation
1452 //===----------------------------------------------------------------------===//
1454 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1456 Instruction *InsertBef)
1457 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1459 OperandTraits<ExtractElementInst>::op_begin(this),
1461 assert(isValidOperands(Val, Index) &&
1462 "Invalid extractelement instruction operands!");
1468 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1470 BasicBlock *InsertAE)
1471 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1473 OperandTraits<ExtractElementInst>::op_begin(this),
1475 assert(isValidOperands(Val, Index) &&
1476 "Invalid extractelement instruction operands!");
1484 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1485 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1491 //===----------------------------------------------------------------------===//
1492 // InsertElementInst Implementation
1493 //===----------------------------------------------------------------------===//
1495 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1497 Instruction *InsertBef)
1498 : Instruction(Vec->getType(), InsertElement,
1499 OperandTraits<InsertElementInst>::op_begin(this),
1501 assert(isValidOperands(Vec, Elt, Index) &&
1502 "Invalid insertelement instruction operands!");
1509 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1511 BasicBlock *InsertAE)
1512 : Instruction(Vec->getType(), InsertElement,
1513 OperandTraits<InsertElementInst>::op_begin(this),
1515 assert(isValidOperands(Vec, Elt, Index) &&
1516 "Invalid insertelement instruction operands!");
1524 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1525 const Value *Index) {
1526 if (!Vec->getType()->isVectorTy())
1527 return false; // First operand of insertelement must be vector type.
1529 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1530 return false;// Second operand of insertelement must be vector element type.
1532 if (!Index->getType()->isIntegerTy(32))
1533 return false; // Third operand of insertelement must be i32.
1538 //===----------------------------------------------------------------------===//
1539 // ShuffleVectorInst Implementation
1540 //===----------------------------------------------------------------------===//
1542 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1544 Instruction *InsertBefore)
1545 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1546 cast<VectorType>(Mask->getType())->getNumElements()),
1548 OperandTraits<ShuffleVectorInst>::op_begin(this),
1549 OperandTraits<ShuffleVectorInst>::operands(this),
1551 assert(isValidOperands(V1, V2, Mask) &&
1552 "Invalid shuffle vector instruction operands!");
1559 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1561 BasicBlock *InsertAtEnd)
1562 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1563 cast<VectorType>(Mask->getType())->getNumElements()),
1565 OperandTraits<ShuffleVectorInst>::op_begin(this),
1566 OperandTraits<ShuffleVectorInst>::operands(this),
1568 assert(isValidOperands(V1, V2, Mask) &&
1569 "Invalid shuffle vector instruction operands!");
1577 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1578 const Value *Mask) {
1579 // V1 and V2 must be vectors of the same type.
1580 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1583 // Mask must be vector of i32.
1584 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1585 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1588 // Check to see if Mask is valid.
1589 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1592 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1593 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1594 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1595 if (ConstantInt *CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1596 if (CI->uge(V1Size*2))
1598 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1605 if (const ConstantDataSequential *CDS =
1606 dyn_cast<ConstantDataSequential>(Mask)) {
1607 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1608 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1609 if (CDS->getElementAsInteger(i) >= V1Size*2)
1614 // The bitcode reader can create a place holder for a forward reference
1615 // used as the shuffle mask. When this occurs, the shuffle mask will
1616 // fall into this case and fail. To avoid this error, do this bit of
1617 // ugliness to allow such a mask pass.
1618 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1619 if (CE->getOpcode() == Instruction::UserOp1)
1625 /// getMaskValue - Return the index from the shuffle mask for the specified
1626 /// output result. This is either -1 if the element is undef or a number less
1627 /// than 2*numelements.
1628 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1629 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1630 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1631 return CDS->getElementAsInteger(i);
1632 Constant *C = Mask->getAggregateElement(i);
1633 if (isa<UndefValue>(C))
1635 return cast<ConstantInt>(C)->getZExtValue();
1638 /// getShuffleMask - Return the full mask for this instruction, where each
1639 /// element is the element number and undef's are returned as -1.
1640 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1641 SmallVectorImpl<int> &Result) {
1642 unsigned NumElts = Mask->getType()->getVectorNumElements();
1644 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1645 for (unsigned i = 0; i != NumElts; ++i)
1646 Result.push_back(CDS->getElementAsInteger(i));
1649 for (unsigned i = 0; i != NumElts; ++i) {
1650 Constant *C = Mask->getAggregateElement(i);
1651 Result.push_back(isa<UndefValue>(C) ? -1 :
1652 cast<ConstantInt>(C)->getZExtValue());
1657 //===----------------------------------------------------------------------===//
1658 // InsertValueInst Class
1659 //===----------------------------------------------------------------------===//
1661 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1662 const Twine &Name) {
1663 assert(NumOperands == 2 && "NumOperands not initialized?");
1665 // There's no fundamental reason why we require at least one index
1666 // (other than weirdness with &*IdxBegin being invalid; see
1667 // getelementptr's init routine for example). But there's no
1668 // present need to support it.
1669 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1671 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1672 Val->getType() && "Inserted value must match indexed type!");
1676 Indices.append(Idxs.begin(), Idxs.end());
1680 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1681 : Instruction(IVI.getType(), InsertValue,
1682 OperandTraits<InsertValueInst>::op_begin(this), 2),
1683 Indices(IVI.Indices) {
1684 Op<0>() = IVI.getOperand(0);
1685 Op<1>() = IVI.getOperand(1);
1686 SubclassOptionalData = IVI.SubclassOptionalData;
1689 //===----------------------------------------------------------------------===//
1690 // ExtractValueInst Class
1691 //===----------------------------------------------------------------------===//
1693 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1694 assert(NumOperands == 1 && "NumOperands not initialized?");
1696 // There's no fundamental reason why we require at least one index.
1697 // But there's no present need to support it.
1698 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1700 Indices.append(Idxs.begin(), Idxs.end());
1704 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1705 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1706 Indices(EVI.Indices) {
1707 SubclassOptionalData = EVI.SubclassOptionalData;
1710 // getIndexedType - Returns the type of the element that would be extracted
1711 // with an extractvalue instruction with the specified parameters.
1713 // A null type is returned if the indices are invalid for the specified
1716 Type *ExtractValueInst::getIndexedType(Type *Agg,
1717 ArrayRef<unsigned> Idxs) {
1718 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1719 unsigned Index = Idxs[CurIdx];
1720 // We can't use CompositeType::indexValid(Index) here.
1721 // indexValid() always returns true for arrays because getelementptr allows
1722 // out-of-bounds indices. Since we don't allow those for extractvalue and
1723 // insertvalue we need to check array indexing manually.
1724 // Since the only other types we can index into are struct types it's just
1725 // as easy to check those manually as well.
1726 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1727 if (Index >= AT->getNumElements())
1729 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1730 if (Index >= ST->getNumElements())
1733 // Not a valid type to index into.
1737 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1739 return const_cast<Type*>(Agg);
1742 //===----------------------------------------------------------------------===//
1743 // BinaryOperator Class
1744 //===----------------------------------------------------------------------===//
1746 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1747 Type *Ty, const Twine &Name,
1748 Instruction *InsertBefore)
1749 : Instruction(Ty, iType,
1750 OperandTraits<BinaryOperator>::op_begin(this),
1751 OperandTraits<BinaryOperator>::operands(this),
1759 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1760 Type *Ty, const Twine &Name,
1761 BasicBlock *InsertAtEnd)
1762 : Instruction(Ty, iType,
1763 OperandTraits<BinaryOperator>::op_begin(this),
1764 OperandTraits<BinaryOperator>::operands(this),
1773 void BinaryOperator::init(BinaryOps iType) {
1774 Value *LHS = getOperand(0), *RHS = getOperand(1);
1775 (void)LHS; (void)RHS; // Silence warnings.
1776 assert(LHS->getType() == RHS->getType() &&
1777 "Binary operator operand types must match!");
1782 assert(getType() == LHS->getType() &&
1783 "Arithmetic operation should return same type as operands!");
1784 assert(getType()->isIntOrIntVectorTy() &&
1785 "Tried to create an integer operation on a non-integer type!");
1787 case FAdd: case FSub:
1789 assert(getType() == LHS->getType() &&
1790 "Arithmetic operation should return same type as operands!");
1791 assert(getType()->isFPOrFPVectorTy() &&
1792 "Tried to create a floating-point operation on a "
1793 "non-floating-point type!");
1797 assert(getType() == LHS->getType() &&
1798 "Arithmetic operation should return same type as operands!");
1799 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1800 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1801 "Incorrect operand type (not integer) for S/UDIV");
1804 assert(getType() == LHS->getType() &&
1805 "Arithmetic operation should return same type as operands!");
1806 assert(getType()->isFPOrFPVectorTy() &&
1807 "Incorrect operand type (not floating point) for FDIV");
1811 assert(getType() == LHS->getType() &&
1812 "Arithmetic operation should return same type as operands!");
1813 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1814 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1815 "Incorrect operand type (not integer) for S/UREM");
1818 assert(getType() == LHS->getType() &&
1819 "Arithmetic operation should return same type as operands!");
1820 assert(getType()->isFPOrFPVectorTy() &&
1821 "Incorrect operand type (not floating point) for FREM");
1826 assert(getType() == LHS->getType() &&
1827 "Shift operation should return same type as operands!");
1828 assert((getType()->isIntegerTy() ||
1829 (getType()->isVectorTy() &&
1830 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1831 "Tried to create a shift operation on a non-integral type!");
1835 assert(getType() == LHS->getType() &&
1836 "Logical operation should return same type as operands!");
1837 assert((getType()->isIntegerTy() ||
1838 (getType()->isVectorTy() &&
1839 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1840 "Tried to create a logical operation on a non-integral type!");
1848 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1850 Instruction *InsertBefore) {
1851 assert(S1->getType() == S2->getType() &&
1852 "Cannot create binary operator with two operands of differing type!");
1853 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1856 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1858 BasicBlock *InsertAtEnd) {
1859 BinaryOperator *Res = Create(Op, S1, S2, Name);
1860 InsertAtEnd->getInstList().push_back(Res);
1864 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1865 Instruction *InsertBefore) {
1866 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1867 return new BinaryOperator(Instruction::Sub,
1869 Op->getType(), Name, InsertBefore);
1872 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1873 BasicBlock *InsertAtEnd) {
1874 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1875 return new BinaryOperator(Instruction::Sub,
1877 Op->getType(), Name, InsertAtEnd);
1880 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1881 Instruction *InsertBefore) {
1882 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1883 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1886 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1887 BasicBlock *InsertAtEnd) {
1888 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1889 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1892 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1893 Instruction *InsertBefore) {
1894 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1895 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1898 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1899 BasicBlock *InsertAtEnd) {
1900 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1901 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1904 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1905 Instruction *InsertBefore) {
1906 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1907 return new BinaryOperator(Instruction::FSub, zero, Op,
1908 Op->getType(), Name, InsertBefore);
1911 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1912 BasicBlock *InsertAtEnd) {
1913 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1914 return new BinaryOperator(Instruction::FSub, zero, Op,
1915 Op->getType(), Name, InsertAtEnd);
1918 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1919 Instruction *InsertBefore) {
1920 Constant *C = Constant::getAllOnesValue(Op->getType());
1921 return new BinaryOperator(Instruction::Xor, Op, C,
1922 Op->getType(), Name, InsertBefore);
1925 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1926 BasicBlock *InsertAtEnd) {
1927 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
1928 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1929 Op->getType(), Name, InsertAtEnd);
1933 // isConstantAllOnes - Helper function for several functions below
1934 static inline bool isConstantAllOnes(const Value *V) {
1935 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1936 return CI->isAllOnesValue();
1937 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1938 return CV->isAllOnesValue();
1942 bool BinaryOperator::isNeg(const Value *V) {
1943 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1944 if (Bop->getOpcode() == Instruction::Sub)
1945 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1946 return C->isNegativeZeroValue();
1950 bool BinaryOperator::isFNeg(const Value *V) {
1951 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1952 if (Bop->getOpcode() == Instruction::FSub)
1953 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1954 return C->isNegativeZeroValue();
1958 bool BinaryOperator::isNot(const Value *V) {
1959 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1960 return (Bop->getOpcode() == Instruction::Xor &&
1961 (isConstantAllOnes(Bop->getOperand(1)) ||
1962 isConstantAllOnes(Bop->getOperand(0))));
1966 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1967 return cast<BinaryOperator>(BinOp)->getOperand(1);
1970 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1971 return getNegArgument(const_cast<Value*>(BinOp));
1974 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1975 return cast<BinaryOperator>(BinOp)->getOperand(1);
1978 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1979 return getFNegArgument(const_cast<Value*>(BinOp));
1982 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1983 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1984 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1985 Value *Op0 = BO->getOperand(0);
1986 Value *Op1 = BO->getOperand(1);
1987 if (isConstantAllOnes(Op0)) return Op1;
1989 assert(isConstantAllOnes(Op1));
1993 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1994 return getNotArgument(const_cast<Value*>(BinOp));
1998 // swapOperands - Exchange the two operands to this instruction. This
1999 // instruction is safe to use on any binary instruction and does not
2000 // modify the semantics of the instruction. If the instruction is
2001 // order dependent (SetLT f.e.) the opcode is changed.
2003 bool BinaryOperator::swapOperands() {
2004 if (!isCommutative())
2005 return true; // Can't commute operands
2006 Op<0>().swap(Op<1>());
2010 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2011 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2014 void BinaryOperator::setHasNoSignedWrap(bool b) {
2015 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2018 void BinaryOperator::setIsExact(bool b) {
2019 cast<PossiblyExactOperator>(this)->setIsExact(b);
2022 bool BinaryOperator::hasNoUnsignedWrap() const {
2023 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2026 bool BinaryOperator::hasNoSignedWrap() const {
2027 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2030 bool BinaryOperator::isExact() const {
2031 return cast<PossiblyExactOperator>(this)->isExact();
2034 //===----------------------------------------------------------------------===//
2036 //===----------------------------------------------------------------------===//
2038 void CastInst::anchor() {}
2040 // Just determine if this cast only deals with integral->integral conversion.
2041 bool CastInst::isIntegerCast() const {
2042 switch (getOpcode()) {
2043 default: return false;
2044 case Instruction::ZExt:
2045 case Instruction::SExt:
2046 case Instruction::Trunc:
2048 case Instruction::BitCast:
2049 return getOperand(0)->getType()->isIntegerTy() &&
2050 getType()->isIntegerTy();
2054 bool CastInst::isLosslessCast() const {
2055 // Only BitCast can be lossless, exit fast if we're not BitCast
2056 if (getOpcode() != Instruction::BitCast)
2059 // Identity cast is always lossless
2060 Type* SrcTy = getOperand(0)->getType();
2061 Type* DstTy = getType();
2065 // Pointer to pointer is always lossless.
2066 if (SrcTy->isPointerTy())
2067 return DstTy->isPointerTy();
2068 return false; // Other types have no identity values
2071 /// This function determines if the CastInst does not require any bits to be
2072 /// changed in order to effect the cast. Essentially, it identifies cases where
2073 /// no code gen is necessary for the cast, hence the name no-op cast. For
2074 /// example, the following are all no-op casts:
2075 /// # bitcast i32* %x to i8*
2076 /// # bitcast <2 x i32> %x to <4 x i16>
2077 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2078 /// @brief Determine if the described cast is a no-op.
2079 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2085 assert(0 && "Invalid CastOp");
2086 case Instruction::Trunc:
2087 case Instruction::ZExt:
2088 case Instruction::SExt:
2089 case Instruction::FPTrunc:
2090 case Instruction::FPExt:
2091 case Instruction::UIToFP:
2092 case Instruction::SIToFP:
2093 case Instruction::FPToUI:
2094 case Instruction::FPToSI:
2095 return false; // These always modify bits
2096 case Instruction::BitCast:
2097 return true; // BitCast never modifies bits.
2098 case Instruction::PtrToInt:
2099 return IntPtrTy->getScalarSizeInBits() ==
2100 DestTy->getScalarSizeInBits();
2101 case Instruction::IntToPtr:
2102 return IntPtrTy->getScalarSizeInBits() ==
2103 SrcTy->getScalarSizeInBits();
2107 /// @brief Determine if a cast is a no-op.
2108 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2109 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2112 /// This function determines if a pair of casts can be eliminated and what
2113 /// opcode should be used in the elimination. This assumes that there are two
2114 /// instructions like this:
2115 /// * %F = firstOpcode SrcTy %x to MidTy
2116 /// * %S = secondOpcode MidTy %F to DstTy
2117 /// The function returns a resultOpcode so these two casts can be replaced with:
2118 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2119 /// If no such cast is permited, the function returns 0.
2120 unsigned CastInst::isEliminableCastPair(
2121 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2122 Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy) {
2123 // Define the 144 possibilities for these two cast instructions. The values
2124 // in this matrix determine what to do in a given situation and select the
2125 // case in the switch below. The rows correspond to firstOp, the columns
2126 // correspond to secondOp. In looking at the table below, keep in mind
2127 // the following cast properties:
2129 // Size Compare Source Destination
2130 // Operator Src ? Size Type Sign Type Sign
2131 // -------- ------------ ------------------- ---------------------
2132 // TRUNC > Integer Any Integral Any
2133 // ZEXT < Integral Unsigned Integer Any
2134 // SEXT < Integral Signed Integer Any
2135 // FPTOUI n/a FloatPt n/a Integral Unsigned
2136 // FPTOSI n/a FloatPt n/a Integral Signed
2137 // UITOFP n/a Integral Unsigned FloatPt n/a
2138 // SITOFP n/a Integral Signed FloatPt n/a
2139 // FPTRUNC > FloatPt n/a FloatPt n/a
2140 // FPEXT < FloatPt n/a FloatPt n/a
2141 // PTRTOINT n/a Pointer n/a Integral Unsigned
2142 // INTTOPTR n/a Integral Unsigned Pointer n/a
2143 // BITCAST = FirstClass n/a FirstClass n/a
2145 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2146 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2147 // into "fptoui double to i64", but this loses information about the range
2148 // of the produced value (we no longer know the top-part is all zeros).
2149 // Further this conversion is often much more expensive for typical hardware,
2150 // and causes issues when building libgcc. We disallow fptosi+sext for the
2152 const unsigned numCastOps =
2153 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2154 static const uint8_t CastResults[numCastOps][numCastOps] = {
2155 // T F F U S F F P I B -+
2156 // R Z S P P I I T P 2 N T |
2157 // U E E 2 2 2 2 R E I T C +- secondOp
2158 // N X X U S F F N X N 2 V |
2159 // C T T I I P P C T T P T -+
2160 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2161 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2162 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2163 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2164 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2165 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2166 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2167 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2168 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2169 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2170 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2171 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2174 // If either of the casts are a bitcast from scalar to vector, disallow the
2175 // merging. However, bitcast of A->B->A are allowed.
2176 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2177 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2178 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2180 // Check if any of the bitcasts convert scalars<->vectors.
2181 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2182 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2183 // Unless we are bitcasing to the original type, disallow optimizations.
2184 if (!chainedBitcast) return 0;
2186 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2187 [secondOp-Instruction::CastOpsBegin];
2190 // categorically disallowed
2193 // allowed, use first cast's opcode
2196 // allowed, use second cast's opcode
2199 // no-op cast in second op implies firstOp as long as the DestTy
2200 // is integer and we are not converting between a vector and a
2202 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2206 // no-op cast in second op implies firstOp as long as the DestTy
2207 // is floating point.
2208 if (DstTy->isFloatingPointTy())
2212 // no-op cast in first op implies secondOp as long as the SrcTy
2214 if (SrcTy->isIntegerTy())
2218 // no-op cast in first op implies secondOp as long as the SrcTy
2219 // is a floating point.
2220 if (SrcTy->isFloatingPointTy())
2224 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2227 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2228 unsigned MidSize = MidTy->getScalarSizeInBits();
2229 if (MidSize >= PtrSize)
2230 return Instruction::BitCast;
2234 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2235 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2236 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2237 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2238 unsigned DstSize = DstTy->getScalarSizeInBits();
2239 if (SrcSize == DstSize)
2240 return Instruction::BitCast;
2241 else if (SrcSize < DstSize)
2245 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2246 return Instruction::ZExt;
2248 // fpext followed by ftrunc is allowed if the bit size returned to is
2249 // the same as the original, in which case its just a bitcast
2251 return Instruction::BitCast;
2252 return 0; // If the types are not the same we can't eliminate it.
2254 // bitcast followed by ptrtoint is allowed as long as the bitcast
2255 // is a pointer to pointer cast.
2256 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2260 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2261 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2265 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2268 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2269 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2270 unsigned DstSize = DstTy->getScalarSizeInBits();
2271 if (SrcSize <= PtrSize && SrcSize == DstSize)
2272 return Instruction::BitCast;
2276 // cast combination can't happen (error in input). This is for all cases
2277 // where the MidTy is not the same for the two cast instructions.
2278 assert(0 && "Invalid Cast Combination");
2281 assert(0 && "Error in CastResults table!!!");
2286 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2287 const Twine &Name, Instruction *InsertBefore) {
2288 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2289 // Construct and return the appropriate CastInst subclass
2291 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2292 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2293 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2294 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2295 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2296 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2297 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2298 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2299 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2300 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2301 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2302 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2304 assert(0 && "Invalid opcode provided");
2309 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2310 const Twine &Name, BasicBlock *InsertAtEnd) {
2311 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2312 // Construct and return the appropriate CastInst subclass
2314 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2315 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2316 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2317 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2318 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2319 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2320 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2321 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2322 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2323 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2324 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2325 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2327 assert(0 && "Invalid opcode provided");
2332 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2334 Instruction *InsertBefore) {
2335 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2336 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2337 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2340 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2342 BasicBlock *InsertAtEnd) {
2343 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2344 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2345 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2348 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2350 Instruction *InsertBefore) {
2351 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2352 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2353 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2356 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2358 BasicBlock *InsertAtEnd) {
2359 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2360 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2361 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2364 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2366 Instruction *InsertBefore) {
2367 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2368 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2369 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2372 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2374 BasicBlock *InsertAtEnd) {
2375 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2376 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2377 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2380 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2382 BasicBlock *InsertAtEnd) {
2383 assert(S->getType()->isPointerTy() && "Invalid cast");
2384 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2387 if (Ty->isIntegerTy())
2388 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2389 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2392 /// @brief Create a BitCast or a PtrToInt cast instruction
2393 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2395 Instruction *InsertBefore) {
2396 assert(S->getType()->isPointerTy() && "Invalid cast");
2397 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2400 if (Ty->isIntegerTy())
2401 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2402 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2405 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2406 bool isSigned, const Twine &Name,
2407 Instruction *InsertBefore) {
2408 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2409 "Invalid integer cast");
2410 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2411 unsigned DstBits = Ty->getScalarSizeInBits();
2412 Instruction::CastOps opcode =
2413 (SrcBits == DstBits ? Instruction::BitCast :
2414 (SrcBits > DstBits ? Instruction::Trunc :
2415 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2416 return Create(opcode, C, Ty, Name, InsertBefore);
2419 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2420 bool isSigned, const Twine &Name,
2421 BasicBlock *InsertAtEnd) {
2422 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2424 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2425 unsigned DstBits = Ty->getScalarSizeInBits();
2426 Instruction::CastOps opcode =
2427 (SrcBits == DstBits ? Instruction::BitCast :
2428 (SrcBits > DstBits ? Instruction::Trunc :
2429 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2430 return Create(opcode, C, Ty, Name, InsertAtEnd);
2433 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2435 Instruction *InsertBefore) {
2436 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2438 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2439 unsigned DstBits = Ty->getScalarSizeInBits();
2440 Instruction::CastOps opcode =
2441 (SrcBits == DstBits ? Instruction::BitCast :
2442 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2443 return Create(opcode, C, Ty, Name, InsertBefore);
2446 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2448 BasicBlock *InsertAtEnd) {
2449 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2451 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2452 unsigned DstBits = Ty->getScalarSizeInBits();
2453 Instruction::CastOps opcode =
2454 (SrcBits == DstBits ? Instruction::BitCast :
2455 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2456 return Create(opcode, C, Ty, Name, InsertAtEnd);
2459 // Check whether it is valid to call getCastOpcode for these types.
2460 // This routine must be kept in sync with getCastOpcode.
2461 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2462 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2465 if (SrcTy == DestTy)
2468 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2469 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2470 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2471 // An element by element cast. Valid if casting the elements is valid.
2472 SrcTy = SrcVecTy->getElementType();
2473 DestTy = DestVecTy->getElementType();
2476 // Get the bit sizes, we'll need these
2477 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2478 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2480 // Run through the possibilities ...
2481 if (DestTy->isIntegerTy()) { // Casting to integral
2482 if (SrcTy->isIntegerTy()) { // Casting from integral
2484 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2486 } else if (SrcTy->isVectorTy()) { // Casting from vector
2487 return DestBits == SrcBits;
2488 } else { // Casting from something else
2489 return SrcTy->isPointerTy();
2491 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2492 if (SrcTy->isIntegerTy()) { // Casting from integral
2494 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2496 } else if (SrcTy->isVectorTy()) { // Casting from vector
2497 return DestBits == SrcBits;
2498 } else { // Casting from something else
2501 } else if (DestTy->isVectorTy()) { // Casting to vector
2502 return DestBits == SrcBits;
2503 } else if (DestTy->isPointerTy()) { // Casting to pointer
2504 if (SrcTy->isPointerTy()) { // Casting from pointer
2506 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2508 } else { // Casting from something else
2511 } else if (DestTy->isX86_MMXTy()) {
2512 if (SrcTy->isVectorTy()) {
2513 return DestBits == SrcBits; // 64-bit vector to MMX
2517 } else { // Casting to something else
2522 // Provide a way to get a "cast" where the cast opcode is inferred from the
2523 // types and size of the operand. This, basically, is a parallel of the
2524 // logic in the castIsValid function below. This axiom should hold:
2525 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2526 // should not assert in castIsValid. In other words, this produces a "correct"
2527 // casting opcode for the arguments passed to it.
2528 // This routine must be kept in sync with isCastable.
2529 Instruction::CastOps
2530 CastInst::getCastOpcode(
2531 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2532 Type *SrcTy = Src->getType();
2534 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2535 "Only first class types are castable!");
2537 if (SrcTy == DestTy)
2540 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2541 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2542 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2543 // An element by element cast. Find the appropriate opcode based on the
2545 SrcTy = SrcVecTy->getElementType();
2546 DestTy = DestVecTy->getElementType();
2549 // Get the bit sizes, we'll need these
2550 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2551 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2553 // Run through the possibilities ...
2554 if (DestTy->isIntegerTy()) { // Casting to integral
2555 if (SrcTy->isIntegerTy()) { // Casting from integral
2556 if (DestBits < SrcBits)
2557 return Trunc; // int -> smaller int
2558 else if (DestBits > SrcBits) { // its an extension
2560 return SExt; // signed -> SEXT
2562 return ZExt; // unsigned -> ZEXT
2564 return BitCast; // Same size, No-op cast
2566 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2568 return FPToSI; // FP -> sint
2570 return FPToUI; // FP -> uint
2571 } else if (SrcTy->isVectorTy()) {
2572 assert(DestBits == SrcBits &&
2573 "Casting vector to integer of different width");
2574 return BitCast; // Same size, no-op cast
2576 assert(SrcTy->isPointerTy() &&
2577 "Casting from a value that is not first-class type");
2578 return PtrToInt; // ptr -> int
2580 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2581 if (SrcTy->isIntegerTy()) { // Casting from integral
2583 return SIToFP; // sint -> FP
2585 return UIToFP; // uint -> FP
2586 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2587 if (DestBits < SrcBits) {
2588 return FPTrunc; // FP -> smaller FP
2589 } else if (DestBits > SrcBits) {
2590 return FPExt; // FP -> larger FP
2592 return BitCast; // same size, no-op cast
2594 } else if (SrcTy->isVectorTy()) {
2595 assert(DestBits == SrcBits &&
2596 "Casting vector to floating point of different width");
2597 return BitCast; // same size, no-op cast
2599 llvm_unreachable("Casting pointer or non-first class to float");
2601 } else if (DestTy->isVectorTy()) {
2602 assert(DestBits == SrcBits &&
2603 "Illegal cast to vector (wrong type or size)");
2605 } else if (DestTy->isPointerTy()) {
2606 if (SrcTy->isPointerTy()) {
2607 return BitCast; // ptr -> ptr
2608 } else if (SrcTy->isIntegerTy()) {
2609 return IntToPtr; // int -> ptr
2611 assert(0 && "Casting pointer to other than pointer or int");
2613 } else if (DestTy->isX86_MMXTy()) {
2614 if (SrcTy->isVectorTy()) {
2615 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2616 return BitCast; // 64-bit vector to MMX
2618 assert(0 && "Illegal cast to X86_MMX");
2621 assert(0 && "Casting to type that is not first-class");
2624 // If we fall through to here we probably hit an assertion cast above
2625 // and assertions are not turned on. Anything we return is an error, so
2626 // BitCast is as good a choice as any.
2630 //===----------------------------------------------------------------------===//
2631 // CastInst SubClass Constructors
2632 //===----------------------------------------------------------------------===//
2634 /// Check that the construction parameters for a CastInst are correct. This
2635 /// could be broken out into the separate constructors but it is useful to have
2636 /// it in one place and to eliminate the redundant code for getting the sizes
2637 /// of the types involved.
2639 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2641 // Check for type sanity on the arguments
2642 Type *SrcTy = S->getType();
2643 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2644 SrcTy->isAggregateType() || DstTy->isAggregateType())
2647 // Get the size of the types in bits, we'll need this later
2648 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2649 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2651 // If these are vector types, get the lengths of the vectors (using zero for
2652 // scalar types means that checking that vector lengths match also checks that
2653 // scalars are not being converted to vectors or vectors to scalars).
2654 unsigned SrcLength = SrcTy->isVectorTy() ?
2655 cast<VectorType>(SrcTy)->getNumElements() : 0;
2656 unsigned DstLength = DstTy->isVectorTy() ?
2657 cast<VectorType>(DstTy)->getNumElements() : 0;
2659 // Switch on the opcode provided
2661 default: return false; // This is an input error
2662 case Instruction::Trunc:
2663 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2664 SrcLength == DstLength && SrcBitSize > DstBitSize;
2665 case Instruction::ZExt:
2666 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2667 SrcLength == DstLength && SrcBitSize < DstBitSize;
2668 case Instruction::SExt:
2669 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2670 SrcLength == DstLength && SrcBitSize < DstBitSize;
2671 case Instruction::FPTrunc:
2672 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2673 SrcLength == DstLength && SrcBitSize > DstBitSize;
2674 case Instruction::FPExt:
2675 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2676 SrcLength == DstLength && SrcBitSize < DstBitSize;
2677 case Instruction::UIToFP:
2678 case Instruction::SIToFP:
2679 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2680 SrcLength == DstLength;
2681 case Instruction::FPToUI:
2682 case Instruction::FPToSI:
2683 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2684 SrcLength == DstLength;
2685 case Instruction::PtrToInt:
2686 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2688 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2689 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2691 return SrcTy->getScalarType()->isPointerTy() &&
2692 DstTy->getScalarType()->isIntegerTy();
2693 case Instruction::IntToPtr:
2694 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2696 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2697 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2699 return SrcTy->getScalarType()->isIntegerTy() &&
2700 DstTy->getScalarType()->isPointerTy();
2701 case Instruction::BitCast:
2702 // BitCast implies a no-op cast of type only. No bits change.
2703 // However, you can't cast pointers to anything but pointers.
2704 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2707 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2708 // these cases, the cast is okay if the source and destination bit widths
2710 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2714 TruncInst::TruncInst(
2715 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2716 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2717 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2720 TruncInst::TruncInst(
2721 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2722 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2723 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2727 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2728 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2729 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2733 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2734 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2735 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2738 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2739 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2740 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2744 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2745 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2746 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2749 FPTruncInst::FPTruncInst(
2750 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2751 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2752 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2755 FPTruncInst::FPTruncInst(
2756 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2757 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2758 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2761 FPExtInst::FPExtInst(
2762 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2763 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2764 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2767 FPExtInst::FPExtInst(
2768 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2769 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2770 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2773 UIToFPInst::UIToFPInst(
2774 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2775 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2776 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2779 UIToFPInst::UIToFPInst(
2780 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2781 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2782 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2785 SIToFPInst::SIToFPInst(
2786 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2787 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2788 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2791 SIToFPInst::SIToFPInst(
2792 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2793 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2794 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2797 FPToUIInst::FPToUIInst(
2798 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2799 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2800 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2803 FPToUIInst::FPToUIInst(
2804 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2805 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2806 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2809 FPToSIInst::FPToSIInst(
2810 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2811 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2812 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2815 FPToSIInst::FPToSIInst(
2816 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2817 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2818 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2821 PtrToIntInst::PtrToIntInst(
2822 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2823 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2824 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2827 PtrToIntInst::PtrToIntInst(
2828 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2829 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2830 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2833 IntToPtrInst::IntToPtrInst(
2834 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2835 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2836 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2839 IntToPtrInst::IntToPtrInst(
2840 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2841 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2842 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2845 BitCastInst::BitCastInst(
2846 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2847 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2848 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2851 BitCastInst::BitCastInst(
2852 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2853 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2854 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2857 //===----------------------------------------------------------------------===//
2859 //===----------------------------------------------------------------------===//
2861 void CmpInst::Anchor() const {}
2863 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2864 Value *LHS, Value *RHS, const Twine &Name,
2865 Instruction *InsertBefore)
2866 : Instruction(ty, op,
2867 OperandTraits<CmpInst>::op_begin(this),
2868 OperandTraits<CmpInst>::operands(this),
2872 setPredicate((Predicate)predicate);
2876 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2877 Value *LHS, Value *RHS, const Twine &Name,
2878 BasicBlock *InsertAtEnd)
2879 : Instruction(ty, op,
2880 OperandTraits<CmpInst>::op_begin(this),
2881 OperandTraits<CmpInst>::operands(this),
2885 setPredicate((Predicate)predicate);
2890 CmpInst::Create(OtherOps Op, unsigned short predicate,
2891 Value *S1, Value *S2,
2892 const Twine &Name, Instruction *InsertBefore) {
2893 if (Op == Instruction::ICmp) {
2895 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2898 return new ICmpInst(CmpInst::Predicate(predicate),
2903 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2906 return new FCmpInst(CmpInst::Predicate(predicate),
2911 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2912 const Twine &Name, BasicBlock *InsertAtEnd) {
2913 if (Op == Instruction::ICmp) {
2914 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2917 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2921 void CmpInst::swapOperands() {
2922 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2925 cast<FCmpInst>(this)->swapOperands();
2928 bool CmpInst::isCommutative() const {
2929 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2930 return IC->isCommutative();
2931 return cast<FCmpInst>(this)->isCommutative();
2934 bool CmpInst::isEquality() const {
2935 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2936 return IC->isEquality();
2937 return cast<FCmpInst>(this)->isEquality();
2941 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2943 default: assert(0 && "Unknown cmp predicate!");
2944 case ICMP_EQ: return ICMP_NE;
2945 case ICMP_NE: return ICMP_EQ;
2946 case ICMP_UGT: return ICMP_ULE;
2947 case ICMP_ULT: return ICMP_UGE;
2948 case ICMP_UGE: return ICMP_ULT;
2949 case ICMP_ULE: return ICMP_UGT;
2950 case ICMP_SGT: return ICMP_SLE;
2951 case ICMP_SLT: return ICMP_SGE;
2952 case ICMP_SGE: return ICMP_SLT;
2953 case ICMP_SLE: return ICMP_SGT;
2955 case FCMP_OEQ: return FCMP_UNE;
2956 case FCMP_ONE: return FCMP_UEQ;
2957 case FCMP_OGT: return FCMP_ULE;
2958 case FCMP_OLT: return FCMP_UGE;
2959 case FCMP_OGE: return FCMP_ULT;
2960 case FCMP_OLE: return FCMP_UGT;
2961 case FCMP_UEQ: return FCMP_ONE;
2962 case FCMP_UNE: return FCMP_OEQ;
2963 case FCMP_UGT: return FCMP_OLE;
2964 case FCMP_ULT: return FCMP_OGE;
2965 case FCMP_UGE: return FCMP_OLT;
2966 case FCMP_ULE: return FCMP_OGT;
2967 case FCMP_ORD: return FCMP_UNO;
2968 case FCMP_UNO: return FCMP_ORD;
2969 case FCMP_TRUE: return FCMP_FALSE;
2970 case FCMP_FALSE: return FCMP_TRUE;
2974 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2976 default: assert(0 && "Unknown icmp predicate!");
2977 case ICMP_EQ: case ICMP_NE:
2978 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2980 case ICMP_UGT: return ICMP_SGT;
2981 case ICMP_ULT: return ICMP_SLT;
2982 case ICMP_UGE: return ICMP_SGE;
2983 case ICMP_ULE: return ICMP_SLE;
2987 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2989 default: assert(0 && "Unknown icmp predicate!");
2990 case ICMP_EQ: case ICMP_NE:
2991 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2993 case ICMP_SGT: return ICMP_UGT;
2994 case ICMP_SLT: return ICMP_ULT;
2995 case ICMP_SGE: return ICMP_UGE;
2996 case ICMP_SLE: return ICMP_ULE;
3000 /// Initialize a set of values that all satisfy the condition with C.
3003 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3006 uint32_t BitWidth = C.getBitWidth();
3008 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3009 case ICmpInst::ICMP_EQ: Upper++; break;
3010 case ICmpInst::ICMP_NE: Lower++; break;
3011 case ICmpInst::ICMP_ULT:
3012 Lower = APInt::getMinValue(BitWidth);
3013 // Check for an empty-set condition.
3015 return ConstantRange(BitWidth, /*isFullSet=*/false);
3017 case ICmpInst::ICMP_SLT:
3018 Lower = APInt::getSignedMinValue(BitWidth);
3019 // Check for an empty-set condition.
3021 return ConstantRange(BitWidth, /*isFullSet=*/false);
3023 case ICmpInst::ICMP_UGT:
3024 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3025 // Check for an empty-set condition.
3027 return ConstantRange(BitWidth, /*isFullSet=*/false);
3029 case ICmpInst::ICMP_SGT:
3030 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3031 // Check for an empty-set condition.
3033 return ConstantRange(BitWidth, /*isFullSet=*/false);
3035 case ICmpInst::ICMP_ULE:
3036 Lower = APInt::getMinValue(BitWidth); Upper++;
3037 // Check for a full-set condition.
3039 return ConstantRange(BitWidth, /*isFullSet=*/true);
3041 case ICmpInst::ICMP_SLE:
3042 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
3043 // Check for a full-set condition.
3045 return ConstantRange(BitWidth, /*isFullSet=*/true);
3047 case ICmpInst::ICMP_UGE:
3048 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3049 // Check for a full-set condition.
3051 return ConstantRange(BitWidth, /*isFullSet=*/true);
3053 case ICmpInst::ICMP_SGE:
3054 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3055 // Check for a full-set condition.
3057 return ConstantRange(BitWidth, /*isFullSet=*/true);
3060 return ConstantRange(Lower, Upper);
3063 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3065 default: assert(0 && "Unknown cmp predicate!");
3066 case ICMP_EQ: case ICMP_NE:
3068 case ICMP_SGT: return ICMP_SLT;
3069 case ICMP_SLT: return ICMP_SGT;
3070 case ICMP_SGE: return ICMP_SLE;
3071 case ICMP_SLE: return ICMP_SGE;
3072 case ICMP_UGT: return ICMP_ULT;
3073 case ICMP_ULT: return ICMP_UGT;
3074 case ICMP_UGE: return ICMP_ULE;
3075 case ICMP_ULE: return ICMP_UGE;
3077 case FCMP_FALSE: case FCMP_TRUE:
3078 case FCMP_OEQ: case FCMP_ONE:
3079 case FCMP_UEQ: case FCMP_UNE:
3080 case FCMP_ORD: case FCMP_UNO:
3082 case FCMP_OGT: return FCMP_OLT;
3083 case FCMP_OLT: return FCMP_OGT;
3084 case FCMP_OGE: return FCMP_OLE;
3085 case FCMP_OLE: return FCMP_OGE;
3086 case FCMP_UGT: return FCMP_ULT;
3087 case FCMP_ULT: return FCMP_UGT;
3088 case FCMP_UGE: return FCMP_ULE;
3089 case FCMP_ULE: return FCMP_UGE;
3093 bool CmpInst::isUnsigned(unsigned short predicate) {
3094 switch (predicate) {
3095 default: return false;
3096 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3097 case ICmpInst::ICMP_UGE: return true;
3101 bool CmpInst::isSigned(unsigned short predicate) {
3102 switch (predicate) {
3103 default: return false;
3104 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3105 case ICmpInst::ICMP_SGE: return true;
3109 bool CmpInst::isOrdered(unsigned short predicate) {
3110 switch (predicate) {
3111 default: return false;
3112 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3113 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3114 case FCmpInst::FCMP_ORD: return true;
3118 bool CmpInst::isUnordered(unsigned short predicate) {
3119 switch (predicate) {
3120 default: return false;
3121 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3122 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3123 case FCmpInst::FCMP_UNO: return true;
3127 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3129 default: return false;
3130 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3131 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3135 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3137 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3138 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3139 default: return false;
3144 //===----------------------------------------------------------------------===//
3145 // SwitchInst Implementation
3146 //===----------------------------------------------------------------------===//
3148 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3149 assert(Value && Default && NumReserved);
3150 ReservedSpace = NumReserved;
3152 OperandList = allocHungoffUses(ReservedSpace);
3154 OperandList[0] = Value;
3155 OperandList[1] = Default;
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 can also autoinsert before another instruction.
3162 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3163 Instruction *InsertBefore)
3164 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3165 0, 0, InsertBefore) {
3166 init(Value, Default, 2+NumCases*2);
3169 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3170 /// switch on and a default destination. The number of additional cases can
3171 /// be specified here to make memory allocation more efficient. This
3172 /// constructor also autoinserts at the end of the specified BasicBlock.
3173 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3174 BasicBlock *InsertAtEnd)
3175 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3176 0, 0, InsertAtEnd) {
3177 init(Value, Default, 2+NumCases*2);
3180 SwitchInst::SwitchInst(const SwitchInst &SI)
3181 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3182 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3183 NumOperands = SI.getNumOperands();
3184 Use *OL = OperandList, *InOL = SI.OperandList;
3185 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3187 OL[i+1] = InOL[i+1];
3189 SubclassOptionalData = SI.SubclassOptionalData;
3192 SwitchInst::~SwitchInst() {
3197 /// addCase - Add an entry to the switch instruction...
3199 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3200 unsigned OpNo = NumOperands;
3201 if (OpNo+2 > ReservedSpace)
3202 growOperands(); // Get more space!
3203 // Initialize some new operands.
3204 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3205 NumOperands = OpNo+2;
3206 OperandList[OpNo] = OnVal;
3207 OperandList[OpNo+1] = Dest;
3210 /// removeCase - This method removes the specified successor from the switch
3211 /// instruction. Note that this cannot be used to remove the default
3212 /// destination (successor #0).
3214 void SwitchInst::removeCase(unsigned idx) {
3215 assert(idx != 0 && "Cannot remove the default case!");
3216 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3218 unsigned NumOps = getNumOperands();
3219 Use *OL = OperandList;
3221 // Overwrite this case with the end of the list.
3222 if ((idx + 1) * 2 != NumOps) {
3223 OL[idx * 2] = OL[NumOps - 2];
3224 OL[idx * 2 + 1] = OL[NumOps - 1];
3227 // Nuke the last value.
3228 OL[NumOps-2].set(0);
3229 OL[NumOps-2+1].set(0);
3230 NumOperands = NumOps-2;
3233 /// growOperands - grow operands - This grows the operand list in response
3234 /// to a push_back style of operation. This grows the number of ops by 3 times.
3236 void SwitchInst::growOperands() {
3237 unsigned e = getNumOperands();
3238 unsigned NumOps = e*3;
3240 ReservedSpace = NumOps;
3241 Use *NewOps = allocHungoffUses(NumOps);
3242 Use *OldOps = OperandList;
3243 for (unsigned i = 0; i != e; ++i) {
3244 NewOps[i] = OldOps[i];
3246 OperandList = NewOps;
3247 Use::zap(OldOps, OldOps + e, true);
3251 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3252 return getSuccessor(idx);
3254 unsigned SwitchInst::getNumSuccessorsV() const {
3255 return getNumSuccessors();
3257 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3258 setSuccessor(idx, B);
3261 //===----------------------------------------------------------------------===//
3262 // IndirectBrInst Implementation
3263 //===----------------------------------------------------------------------===//
3265 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3266 assert(Address && Address->getType()->isPointerTy() &&
3267 "Address of indirectbr must be a pointer");
3268 ReservedSpace = 1+NumDests;
3270 OperandList = allocHungoffUses(ReservedSpace);
3272 OperandList[0] = Address;
3276 /// growOperands - grow operands - This grows the operand list in response
3277 /// to a push_back style of operation. This grows the number of ops by 2 times.
3279 void IndirectBrInst::growOperands() {
3280 unsigned e = getNumOperands();
3281 unsigned NumOps = e*2;
3283 ReservedSpace = NumOps;
3284 Use *NewOps = allocHungoffUses(NumOps);
3285 Use *OldOps = OperandList;
3286 for (unsigned i = 0; i != e; ++i)
3287 NewOps[i] = OldOps[i];
3288 OperandList = NewOps;
3289 Use::zap(OldOps, OldOps + e, true);
3292 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3293 Instruction *InsertBefore)
3294 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3295 0, 0, InsertBefore) {
3296 init(Address, NumCases);
3299 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3300 BasicBlock *InsertAtEnd)
3301 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3302 0, 0, InsertAtEnd) {
3303 init(Address, NumCases);
3306 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3307 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3308 allocHungoffUses(IBI.getNumOperands()),
3309 IBI.getNumOperands()) {
3310 Use *OL = OperandList, *InOL = IBI.OperandList;
3311 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3313 SubclassOptionalData = IBI.SubclassOptionalData;
3316 IndirectBrInst::~IndirectBrInst() {
3320 /// addDestination - Add a destination.
3322 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3323 unsigned OpNo = NumOperands;
3324 if (OpNo+1 > ReservedSpace)
3325 growOperands(); // Get more space!
3326 // Initialize some new operands.
3327 assert(OpNo < ReservedSpace && "Growing didn't work!");
3328 NumOperands = OpNo+1;
3329 OperandList[OpNo] = DestBB;
3332 /// removeDestination - This method removes the specified successor from the
3333 /// indirectbr instruction.
3334 void IndirectBrInst::removeDestination(unsigned idx) {
3335 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3337 unsigned NumOps = getNumOperands();
3338 Use *OL = OperandList;
3340 // Replace this value with the last one.
3341 OL[idx+1] = OL[NumOps-1];
3343 // Nuke the last value.
3344 OL[NumOps-1].set(0);
3345 NumOperands = NumOps-1;
3348 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3349 return getSuccessor(idx);
3351 unsigned IndirectBrInst::getNumSuccessorsV() const {
3352 return getNumSuccessors();
3354 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3355 setSuccessor(idx, B);
3358 //===----------------------------------------------------------------------===//
3359 // clone_impl() implementations
3360 //===----------------------------------------------------------------------===//
3362 // Define these methods here so vtables don't get emitted into every translation
3363 // unit that uses these classes.
3365 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3366 return new (getNumOperands()) GetElementPtrInst(*this);
3369 BinaryOperator *BinaryOperator::clone_impl() const {
3370 return Create(getOpcode(), Op<0>(), Op<1>());
3373 FCmpInst* FCmpInst::clone_impl() const {
3374 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3377 ICmpInst* ICmpInst::clone_impl() const {
3378 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3381 ExtractValueInst *ExtractValueInst::clone_impl() const {
3382 return new ExtractValueInst(*this);
3385 InsertValueInst *InsertValueInst::clone_impl() const {
3386 return new InsertValueInst(*this);
3389 AllocaInst *AllocaInst::clone_impl() const {
3390 return new AllocaInst(getAllocatedType(),
3391 (Value*)getOperand(0),
3395 LoadInst *LoadInst::clone_impl() const {
3396 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3397 getAlignment(), getOrdering(), getSynchScope());
3400 StoreInst *StoreInst::clone_impl() const {
3401 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3402 getAlignment(), getOrdering(), getSynchScope());
3406 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3407 AtomicCmpXchgInst *Result =
3408 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3409 getOrdering(), getSynchScope());
3410 Result->setVolatile(isVolatile());
3414 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3415 AtomicRMWInst *Result =
3416 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3417 getOrdering(), getSynchScope());
3418 Result->setVolatile(isVolatile());
3422 FenceInst *FenceInst::clone_impl() const {
3423 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3426 TruncInst *TruncInst::clone_impl() const {
3427 return new TruncInst(getOperand(0), getType());
3430 ZExtInst *ZExtInst::clone_impl() const {
3431 return new ZExtInst(getOperand(0), getType());
3434 SExtInst *SExtInst::clone_impl() const {
3435 return new SExtInst(getOperand(0), getType());
3438 FPTruncInst *FPTruncInst::clone_impl() const {
3439 return new FPTruncInst(getOperand(0), getType());
3442 FPExtInst *FPExtInst::clone_impl() const {
3443 return new FPExtInst(getOperand(0), getType());
3446 UIToFPInst *UIToFPInst::clone_impl() const {
3447 return new UIToFPInst(getOperand(0), getType());
3450 SIToFPInst *SIToFPInst::clone_impl() const {
3451 return new SIToFPInst(getOperand(0), getType());
3454 FPToUIInst *FPToUIInst::clone_impl() const {
3455 return new FPToUIInst(getOperand(0), getType());
3458 FPToSIInst *FPToSIInst::clone_impl() const {
3459 return new FPToSIInst(getOperand(0), getType());
3462 PtrToIntInst *PtrToIntInst::clone_impl() const {
3463 return new PtrToIntInst(getOperand(0), getType());
3466 IntToPtrInst *IntToPtrInst::clone_impl() const {
3467 return new IntToPtrInst(getOperand(0), getType());
3470 BitCastInst *BitCastInst::clone_impl() const {
3471 return new BitCastInst(getOperand(0), getType());
3474 CallInst *CallInst::clone_impl() const {
3475 return new(getNumOperands()) CallInst(*this);
3478 SelectInst *SelectInst::clone_impl() const {
3479 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3482 VAArgInst *VAArgInst::clone_impl() const {
3483 return new VAArgInst(getOperand(0), getType());
3486 ExtractElementInst *ExtractElementInst::clone_impl() const {
3487 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3490 InsertElementInst *InsertElementInst::clone_impl() const {
3491 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3494 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3495 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3498 PHINode *PHINode::clone_impl() const {
3499 return new PHINode(*this);
3502 LandingPadInst *LandingPadInst::clone_impl() const {
3503 return new LandingPadInst(*this);
3506 ReturnInst *ReturnInst::clone_impl() const {
3507 return new(getNumOperands()) ReturnInst(*this);
3510 BranchInst *BranchInst::clone_impl() const {
3511 return new(getNumOperands()) BranchInst(*this);
3514 SwitchInst *SwitchInst::clone_impl() const {
3515 return new SwitchInst(*this);
3518 IndirectBrInst *IndirectBrInst::clone_impl() const {
3519 return new IndirectBrInst(*this);
3523 InvokeInst *InvokeInst::clone_impl() const {
3524 return new(getNumOperands()) InvokeInst(*this);
3527 ResumeInst *ResumeInst::clone_impl() const {
3528 return new(1) ResumeInst(*this);
3531 UnwindInst *UnwindInst::clone_impl() const {
3532 LLVMContext &Context = getContext();
3533 return new UnwindInst(Context);
3536 UnreachableInst *UnreachableInst::clone_impl() const {
3537 LLVMContext &Context = getContext();
3538 return new UnreachableInst(Context);