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 "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/ConstantRange.h"
21 #include "llvm/Support/MathExtras.h"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 CallSite::CallSite(Instruction *C) {
29 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
32 unsigned CallSite::getCallingConv() const {
33 if (CallInst *CI = dyn_cast<CallInst>(I))
34 return CI->getCallingConv();
36 return cast<InvokeInst>(I)->getCallingConv();
38 void CallSite::setCallingConv(unsigned CC) {
39 if (CallInst *CI = dyn_cast<CallInst>(I))
40 CI->setCallingConv(CC);
42 cast<InvokeInst>(I)->setCallingConv(CC);
44 const PAListPtr &CallSite::getParamAttrs() const {
45 if (CallInst *CI = dyn_cast<CallInst>(I))
46 return CI->getParamAttrs();
48 return cast<InvokeInst>(I)->getParamAttrs();
50 void CallSite::setParamAttrs(const PAListPtr &PAL) {
51 if (CallInst *CI = dyn_cast<CallInst>(I))
52 CI->setParamAttrs(PAL);
54 cast<InvokeInst>(I)->setParamAttrs(PAL);
56 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
57 if (CallInst *CI = dyn_cast<CallInst>(I))
58 return CI->paramHasAttr(i, attr);
60 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
62 uint16_t CallSite::getParamAlignment(uint16_t i) const {
63 if (CallInst *CI = dyn_cast<CallInst>(I))
64 return CI->getParamAlignment(i);
66 return cast<InvokeInst>(I)->getParamAlignment(i);
69 bool CallSite::doesNotAccessMemory() const {
70 if (CallInst *CI = dyn_cast<CallInst>(I))
71 return CI->doesNotAccessMemory();
73 return cast<InvokeInst>(I)->doesNotAccessMemory();
75 bool CallSite::onlyReadsMemory() const {
76 if (CallInst *CI = dyn_cast<CallInst>(I))
77 return CI->onlyReadsMemory();
79 return cast<InvokeInst>(I)->onlyReadsMemory();
81 bool CallSite::doesNotThrow() const {
82 if (CallInst *CI = dyn_cast<CallInst>(I))
83 return CI->doesNotThrow();
85 return cast<InvokeInst>(I)->doesNotThrow();
87 void CallSite::setDoesNotThrow(bool doesNotThrow) {
88 if (CallInst *CI = dyn_cast<CallInst>(I))
89 CI->setDoesNotThrow(doesNotThrow);
91 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
94 bool CallSite::hasArgument(const Value *Arg) const {
95 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
101 //===----------------------------------------------------------------------===//
102 // TerminatorInst Class
103 //===----------------------------------------------------------------------===//
105 // Out of line virtual method, so the vtable, etc has a home.
106 TerminatorInst::~TerminatorInst() {
109 //===----------------------------------------------------------------------===//
110 // UnaryInstruction Class
111 //===----------------------------------------------------------------------===//
113 // Out of line virtual method, so the vtable, etc has a home.
114 UnaryInstruction::~UnaryInstruction() {
117 //===----------------------------------------------------------------------===//
119 //===----------------------------------------------------------------------===//
121 PHINode::PHINode(const PHINode &PN)
122 : Instruction(PN.getType(), Instruction::PHI,
123 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
124 ReservedSpace(PN.getNumOperands()) {
125 Use *OL = OperandList;
126 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
127 OL[i] = PN.getOperand(i);
128 OL[i+1] = PN.getOperand(i+1);
132 PHINode::~PHINode() {
134 dropHungoffUses(OperandList);
137 // removeIncomingValue - Remove an incoming value. This is useful if a
138 // predecessor basic block is deleted.
139 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
140 unsigned NumOps = getNumOperands();
141 Use *OL = OperandList;
142 assert(Idx*2 < NumOps && "BB not in PHI node!");
143 Value *Removed = OL[Idx*2];
145 // Move everything after this operand down.
147 // FIXME: we could just swap with the end of the list, then erase. However,
148 // client might not expect this to happen. The code as it is thrashes the
149 // use/def lists, which is kinda lame.
150 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
155 // Nuke the last value.
157 OL[NumOps-2+1].set(0);
158 NumOperands = NumOps-2;
160 // If the PHI node is dead, because it has zero entries, nuke it now.
161 if (NumOps == 2 && DeletePHIIfEmpty) {
162 // If anyone is using this PHI, make them use a dummy value instead...
163 replaceAllUsesWith(UndefValue::get(getType()));
169 /// resizeOperands - resize operands - This adjusts the length of the operands
170 /// list according to the following behavior:
171 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
172 /// of operation. This grows the number of ops by 1.5 times.
173 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
174 /// 3. If NumOps == NumOperands, trim the reserved space.
176 void PHINode::resizeOperands(unsigned NumOps) {
177 unsigned e = getNumOperands();
180 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
181 } else if (NumOps*2 > NumOperands) {
183 if (ReservedSpace >= NumOps) return;
184 } else if (NumOps == NumOperands) {
185 if (ReservedSpace == NumOps) return;
190 ReservedSpace = NumOps;
191 Use *OldOps = OperandList;
192 Use *NewOps = allocHungoffUses(NumOps);
193 std::copy(OldOps, OldOps + e, NewOps);
194 OperandList = NewOps;
195 if (OldOps) Use::zap(OldOps, OldOps + e, true);
198 /// hasConstantValue - If the specified PHI node always merges together the same
199 /// value, return the value, otherwise return null.
201 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
202 // If the PHI node only has one incoming value, eliminate the PHI node...
203 if (getNumIncomingValues() == 1) {
204 if (getIncomingValue(0) != this) // not X = phi X
205 return getIncomingValue(0);
207 return UndefValue::get(getType()); // Self cycle is dead.
210 // Otherwise if all of the incoming values are the same for the PHI, replace
211 // the PHI node with the incoming value.
214 bool HasUndefInput = false;
215 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
216 if (isa<UndefValue>(getIncomingValue(i))) {
217 HasUndefInput = true;
218 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
219 if (InVal && getIncomingValue(i) != InVal)
220 return 0; // Not the same, bail out.
222 InVal = getIncomingValue(i);
225 // The only case that could cause InVal to be null is if we have a PHI node
226 // that only has entries for itself. In this case, there is no entry into the
227 // loop, so kill the PHI.
229 if (InVal == 0) InVal = UndefValue::get(getType());
231 // If we have a PHI node like phi(X, undef, X), where X is defined by some
232 // instruction, we cannot always return X as the result of the PHI node. Only
233 // do this if X is not an instruction (thus it must dominate the PHI block),
234 // or if the client is prepared to deal with this possibility.
235 if (HasUndefInput && !AllowNonDominatingInstruction)
236 if (Instruction *IV = dyn_cast<Instruction>(InVal))
237 // If it's in the entry block, it dominates everything.
238 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
240 return 0; // Cannot guarantee that InVal dominates this PHINode.
242 // All of the incoming values are the same, return the value now.
247 //===----------------------------------------------------------------------===//
248 // CallInst Implementation
249 //===----------------------------------------------------------------------===//
251 CallInst::~CallInst() {
254 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
255 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
256 Use *OL = OperandList;
259 const FunctionType *FTy =
260 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
261 FTy = FTy; // silence warning.
263 assert((NumParams == FTy->getNumParams() ||
264 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
265 "Calling a function with bad signature!");
266 for (unsigned i = 0; i != NumParams; ++i) {
267 assert((i >= FTy->getNumParams() ||
268 FTy->getParamType(i) == Params[i]->getType()) &&
269 "Calling a function with a bad signature!");
274 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
275 assert(NumOperands == 3 && "NumOperands not set up?");
276 Use *OL = OperandList;
281 const FunctionType *FTy =
282 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
283 FTy = FTy; // silence warning.
285 assert((FTy->getNumParams() == 2 ||
286 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
287 "Calling a function with bad signature");
288 assert((0 >= FTy->getNumParams() ||
289 FTy->getParamType(0) == Actual1->getType()) &&
290 "Calling a function with a bad signature!");
291 assert((1 >= FTy->getNumParams() ||
292 FTy->getParamType(1) == Actual2->getType()) &&
293 "Calling a function with a bad signature!");
296 void CallInst::init(Value *Func, Value *Actual) {
297 assert(NumOperands == 2 && "NumOperands not set up?");
298 Use *OL = OperandList;
302 const FunctionType *FTy =
303 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
304 FTy = FTy; // silence warning.
306 assert((FTy->getNumParams() == 1 ||
307 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
308 "Calling a function with bad signature");
309 assert((0 == FTy->getNumParams() ||
310 FTy->getParamType(0) == Actual->getType()) &&
311 "Calling a function with a bad signature!");
314 void CallInst::init(Value *Func) {
315 assert(NumOperands == 1 && "NumOperands not set up?");
316 Use *OL = OperandList;
319 const FunctionType *FTy =
320 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
321 FTy = FTy; // silence warning.
323 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
326 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
327 Instruction *InsertBefore)
328 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
329 ->getElementType())->getReturnType(),
331 OperandTraits<CallInst>::op_end(this) - 2,
337 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
338 BasicBlock *InsertAtEnd)
339 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
340 ->getElementType())->getReturnType(),
342 OperandTraits<CallInst>::op_end(this) - 2,
347 CallInst::CallInst(Value *Func, const std::string &Name,
348 Instruction *InsertBefore)
349 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
350 ->getElementType())->getReturnType(),
352 OperandTraits<CallInst>::op_end(this) - 1,
358 CallInst::CallInst(Value *Func, const std::string &Name,
359 BasicBlock *InsertAtEnd)
360 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
361 ->getElementType())->getReturnType(),
363 OperandTraits<CallInst>::op_end(this) - 1,
369 CallInst::CallInst(const CallInst &CI)
370 : Instruction(CI.getType(), Instruction::Call,
371 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
372 CI.getNumOperands()) {
373 setParamAttrs(CI.getParamAttrs());
374 SubclassData = CI.SubclassData;
375 Use *OL = OperandList;
376 Use *InOL = CI.OperandList;
377 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
381 void CallInst::addParamAttr(unsigned i, ParameterAttributes attr) {
382 PAListPtr PAL = getParamAttrs();
383 PAL = PAL.addAttr(i, attr);
387 bool CallInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
388 if (ParamAttrs.paramHasAttr(i, attr))
390 if (const Function *F = getCalledFunction())
391 return F->paramHasAttr(i, attr);
395 void CallInst::setDoesNotThrow(bool doesNotThrow) {
396 PAListPtr PAL = getParamAttrs();
398 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
400 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
405 //===----------------------------------------------------------------------===//
406 // InvokeInst Implementation
407 //===----------------------------------------------------------------------===//
409 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
410 Value* const *Args, unsigned NumArgs) {
411 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
412 Use *OL = OperandList;
416 const FunctionType *FTy =
417 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
418 FTy = FTy; // silence warning.
420 assert(((NumArgs == FTy->getNumParams()) ||
421 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
422 "Calling a function with bad signature");
424 for (unsigned i = 0, e = NumArgs; i != e; i++) {
425 assert((i >= FTy->getNumParams() ||
426 FTy->getParamType(i) == Args[i]->getType()) &&
427 "Invoking a function with a bad signature!");
433 InvokeInst::InvokeInst(const InvokeInst &II)
434 : TerminatorInst(II.getType(), Instruction::Invoke,
435 OperandTraits<InvokeInst>::op_end(this)
436 - II.getNumOperands(),
437 II.getNumOperands()) {
438 setParamAttrs(II.getParamAttrs());
439 SubclassData = II.SubclassData;
440 Use *OL = OperandList, *InOL = II.OperandList;
441 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
445 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
446 return getSuccessor(idx);
448 unsigned InvokeInst::getNumSuccessorsV() const {
449 return getNumSuccessors();
451 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
452 return setSuccessor(idx, B);
455 bool InvokeInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
456 if (ParamAttrs.paramHasAttr(i, attr))
458 if (const Function *F = getCalledFunction())
459 return F->paramHasAttr(i, attr);
463 void InvokeInst::addParamAttr(unsigned i, ParameterAttributes attr) {
464 PAListPtr PAL = getParamAttrs();
465 PAL = PAL.addAttr(i, attr);
469 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
470 PAListPtr PAL = getParamAttrs();
472 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
474 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
479 //===----------------------------------------------------------------------===//
480 // ReturnInst Implementation
481 //===----------------------------------------------------------------------===//
483 ReturnInst::ReturnInst(const ReturnInst &RI)
484 : TerminatorInst(Type::VoidTy, Instruction::Ret,
485 OperandTraits<ReturnInst>::op_end(this)
486 - RI.getNumOperands(),
487 RI.getNumOperands()) {
488 unsigned N = RI.getNumOperands();
490 Op<0>() = RI.Op<0>();
492 Use *OL = OperandList;
493 for (unsigned i = 0; i < N; ++i)
494 OL[i] = RI.getOperand(i);
498 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
499 : TerminatorInst(Type::VoidTy, Instruction::Ret,
500 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
501 retVal != 0, InsertBefore) {
505 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
506 : TerminatorInst(Type::VoidTy, Instruction::Ret,
507 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
508 retVal != 0, InsertAtEnd) {
512 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
513 : TerminatorInst(Type::VoidTy, Instruction::Ret,
514 OperandTraits<ReturnInst>::op_end(this),
518 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
519 Instruction *InsertBefore)
520 : TerminatorInst(Type::VoidTy, Instruction::Ret,
521 OperandTraits<ReturnInst>::op_end(this) - N,
526 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
527 BasicBlock *InsertAtEnd)
528 : TerminatorInst(Type::VoidTy, Instruction::Ret,
529 OperandTraits<ReturnInst>::op_end(this) - N,
535 void ReturnInst::init(Value * const* retVals, unsigned N) {
536 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
539 if (NumOperands == 1) {
541 if (V->getType() == Type::VoidTy)
547 Use *OL = OperandList;
548 for (unsigned i = 0; i < NumOperands; ++i) {
549 Value *V = *retVals++;
550 assert(!isa<BasicBlock>(V) &&
551 "Cannot return basic block. Probably using the incorrect ctor");
556 unsigned ReturnInst::getNumSuccessorsV() const {
557 return getNumSuccessors();
560 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
561 /// emit the vtable for the class in this translation unit.
562 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
563 assert(0 && "ReturnInst has no successors!");
566 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
567 assert(0 && "ReturnInst has no successors!");
572 ReturnInst::~ReturnInst() {
575 //===----------------------------------------------------------------------===//
576 // UnwindInst Implementation
577 //===----------------------------------------------------------------------===//
579 UnwindInst::UnwindInst(Instruction *InsertBefore)
580 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
582 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
583 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
587 unsigned UnwindInst::getNumSuccessorsV() const {
588 return getNumSuccessors();
591 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
592 assert(0 && "UnwindInst has no successors!");
595 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
596 assert(0 && "UnwindInst has no successors!");
601 //===----------------------------------------------------------------------===//
602 // UnreachableInst Implementation
603 //===----------------------------------------------------------------------===//
605 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
606 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
608 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
609 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
612 unsigned UnreachableInst::getNumSuccessorsV() const {
613 return getNumSuccessors();
616 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
617 assert(0 && "UnwindInst has no successors!");
620 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
621 assert(0 && "UnwindInst has no successors!");
626 //===----------------------------------------------------------------------===//
627 // BranchInst Implementation
628 //===----------------------------------------------------------------------===//
630 void BranchInst::AssertOK() {
632 assert(getCondition()->getType() == Type::Int1Ty &&
633 "May only branch on boolean predicates!");
636 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
637 : TerminatorInst(Type::VoidTy, Instruction::Br,
638 OperandTraits<BranchInst>::op_end(this) - 1,
640 assert(IfTrue != 0 && "Branch destination may not be null!");
643 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
644 Instruction *InsertBefore)
645 : TerminatorInst(Type::VoidTy, Instruction::Br,
646 OperandTraits<BranchInst>::op_end(this) - 3,
656 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
657 : TerminatorInst(Type::VoidTy, Instruction::Br,
658 OperandTraits<BranchInst>::op_end(this) - 1,
660 assert(IfTrue != 0 && "Branch destination may not be null!");
664 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
665 BasicBlock *InsertAtEnd)
666 : TerminatorInst(Type::VoidTy, Instruction::Br,
667 OperandTraits<BranchInst>::op_end(this) - 3,
678 BranchInst::BranchInst(const BranchInst &BI) :
679 TerminatorInst(Type::VoidTy, Instruction::Br,
680 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
681 BI.getNumOperands()) {
682 OperandList[0] = BI.getOperand(0);
683 if (BI.getNumOperands() != 1) {
684 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
685 OperandList[1] = BI.getOperand(1);
686 OperandList[2] = BI.getOperand(2);
690 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
691 return getSuccessor(idx);
693 unsigned BranchInst::getNumSuccessorsV() const {
694 return getNumSuccessors();
696 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
697 setSuccessor(idx, B);
701 //===----------------------------------------------------------------------===//
702 // AllocationInst Implementation
703 //===----------------------------------------------------------------------===//
705 static Value *getAISize(Value *Amt) {
707 Amt = ConstantInt::get(Type::Int32Ty, 1);
709 assert(!isa<BasicBlock>(Amt) &&
710 "Passed basic block into allocation size parameter! Use other ctor");
711 assert(Amt->getType() == Type::Int32Ty &&
712 "Malloc/Allocation array size is not a 32-bit integer!");
717 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
718 unsigned Align, const std::string &Name,
719 Instruction *InsertBefore)
720 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
723 assert(Ty != Type::VoidTy && "Cannot allocate void!");
727 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
728 unsigned Align, const std::string &Name,
729 BasicBlock *InsertAtEnd)
730 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
733 assert(Ty != Type::VoidTy && "Cannot allocate void!");
737 // Out of line virtual method, so the vtable, etc has a home.
738 AllocationInst::~AllocationInst() {
741 void AllocationInst::setAlignment(unsigned Align) {
742 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
743 SubclassData = Log2_32(Align) + 1;
744 assert(getAlignment() == Align && "Alignment representation error!");
747 bool AllocationInst::isArrayAllocation() const {
748 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
749 return CI->getZExtValue() != 1;
753 const Type *AllocationInst::getAllocatedType() const {
754 return getType()->getElementType();
757 AllocaInst::AllocaInst(const AllocaInst &AI)
758 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
759 Instruction::Alloca, AI.getAlignment()) {
762 MallocInst::MallocInst(const MallocInst &MI)
763 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
764 Instruction::Malloc, MI.getAlignment()) {
767 //===----------------------------------------------------------------------===//
768 // FreeInst Implementation
769 //===----------------------------------------------------------------------===//
771 void FreeInst::AssertOK() {
772 assert(isa<PointerType>(getOperand(0)->getType()) &&
773 "Can not free something of nonpointer type!");
776 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
777 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
781 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
782 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
787 //===----------------------------------------------------------------------===//
788 // LoadInst Implementation
789 //===----------------------------------------------------------------------===//
791 void LoadInst::AssertOK() {
792 assert(isa<PointerType>(getOperand(0)->getType()) &&
793 "Ptr must have pointer type.");
796 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
797 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
798 Load, Ptr, InsertBef) {
805 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
806 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
807 Load, Ptr, InsertAE) {
814 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
815 Instruction *InsertBef)
816 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
817 Load, Ptr, InsertBef) {
818 setVolatile(isVolatile);
824 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
825 unsigned Align, Instruction *InsertBef)
826 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
827 Load, Ptr, InsertBef) {
828 setVolatile(isVolatile);
834 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
835 unsigned Align, BasicBlock *InsertAE)
836 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
837 Load, Ptr, InsertAE) {
838 setVolatile(isVolatile);
844 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
845 BasicBlock *InsertAE)
846 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
847 Load, Ptr, InsertAE) {
848 setVolatile(isVolatile);
856 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
857 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
858 Load, Ptr, InsertBef) {
862 if (Name && Name[0]) setName(Name);
865 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
866 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
867 Load, Ptr, InsertAE) {
871 if (Name && Name[0]) setName(Name);
874 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
875 Instruction *InsertBef)
876 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
877 Load, Ptr, InsertBef) {
878 setVolatile(isVolatile);
881 if (Name && Name[0]) setName(Name);
884 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
885 BasicBlock *InsertAE)
886 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
887 Load, Ptr, InsertAE) {
888 setVolatile(isVolatile);
891 if (Name && Name[0]) setName(Name);
894 void LoadInst::setAlignment(unsigned Align) {
895 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
896 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
899 //===----------------------------------------------------------------------===//
900 // StoreInst Implementation
901 //===----------------------------------------------------------------------===//
903 void StoreInst::AssertOK() {
904 assert(isa<PointerType>(getOperand(1)->getType()) &&
905 "Ptr must have pointer type!");
906 assert(getOperand(0)->getType() ==
907 cast<PointerType>(getOperand(1)->getType())->getElementType()
908 && "Ptr must be a pointer to Val type!");
912 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
913 : Instruction(Type::VoidTy, Store,
914 OperandTraits<StoreInst>::op_begin(this),
915 OperandTraits<StoreInst>::operands(this),
924 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
925 : Instruction(Type::VoidTy, Store,
926 OperandTraits<StoreInst>::op_begin(this),
927 OperandTraits<StoreInst>::operands(this),
936 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
937 Instruction *InsertBefore)
938 : Instruction(Type::VoidTy, Store,
939 OperandTraits<StoreInst>::op_begin(this),
940 OperandTraits<StoreInst>::operands(this),
944 setVolatile(isVolatile);
949 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
950 unsigned Align, Instruction *InsertBefore)
951 : Instruction(Type::VoidTy, Store,
952 OperandTraits<StoreInst>::op_begin(this),
953 OperandTraits<StoreInst>::operands(this),
957 setVolatile(isVolatile);
962 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
963 unsigned Align, BasicBlock *InsertAtEnd)
964 : Instruction(Type::VoidTy, Store,
965 OperandTraits<StoreInst>::op_begin(this),
966 OperandTraits<StoreInst>::operands(this),
970 setVolatile(isVolatile);
975 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
976 BasicBlock *InsertAtEnd)
977 : Instruction(Type::VoidTy, Store,
978 OperandTraits<StoreInst>::op_begin(this),
979 OperandTraits<StoreInst>::operands(this),
983 setVolatile(isVolatile);
988 void StoreInst::setAlignment(unsigned Align) {
989 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
990 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
993 //===----------------------------------------------------------------------===//
994 // GetElementPtrInst Implementation
995 //===----------------------------------------------------------------------===//
997 static unsigned retrieveAddrSpace(const Value *Val) {
998 return cast<PointerType>(Val->getType())->getAddressSpace();
1001 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1002 const std::string &Name) {
1003 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1004 Use *OL = OperandList;
1007 for (unsigned i = 0; i != NumIdx; ++i)
1013 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1014 assert(NumOperands == 2 && "NumOperands not initialized?");
1015 Use *OL = OperandList;
1022 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1023 : Instruction(GEPI.getType(), GetElementPtr,
1024 OperandTraits<GetElementPtrInst>::op_end(this)
1025 - GEPI.getNumOperands(),
1026 GEPI.getNumOperands()) {
1027 Use *OL = OperandList;
1028 Use *GEPIOL = GEPI.OperandList;
1029 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1033 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1034 const std::string &Name, Instruction *InBe)
1035 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1036 retrieveAddrSpace(Ptr)),
1038 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1040 init(Ptr, Idx, Name);
1043 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1044 const std::string &Name, BasicBlock *IAE)
1045 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1046 retrieveAddrSpace(Ptr)),
1048 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1050 init(Ptr, Idx, Name);
1053 // getIndexedType - Returns the type of the element that would be loaded with
1054 // a load instruction with the specified parameters.
1056 // A null type is returned if the indices are invalid for the specified
1059 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1062 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1063 if (!PTy) return 0; // Type isn't a pointer type!
1064 const Type *Agg = PTy->getElementType();
1066 // Handle the special case of the empty set index set...
1070 unsigned CurIdx = 1;
1071 for (; CurIdx != NumIdx; ++CurIdx) {
1072 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1073 if (!CT || isa<PointerType>(CT)) return 0;
1074 Value *Index = Idxs[CurIdx];
1075 if (!CT->indexValid(Index)) return 0;
1076 Agg = CT->getTypeAtIndex(Index);
1078 // If the new type forwards to another type, then it is in the middle
1079 // of being refined to another type (and hence, may have dropped all
1080 // references to what it was using before). So, use the new forwarded
1082 if (const Type *Ty = Agg->getForwardedType())
1085 return CurIdx == NumIdx ? Agg : 0;
1088 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1089 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1090 if (!PTy) return 0; // Type isn't a pointer type!
1092 // Check the pointer index.
1093 if (!PTy->indexValid(Idx)) return 0;
1095 return PTy->getElementType();
1099 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1100 /// zeros. If so, the result pointer and the first operand have the same
1101 /// value, just potentially different types.
1102 bool GetElementPtrInst::hasAllZeroIndices() const {
1103 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1104 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1105 if (!CI->isZero()) return false;
1113 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1114 /// constant integers. If so, the result pointer and the first operand have
1115 /// a constant offset between them.
1116 bool GetElementPtrInst::hasAllConstantIndices() const {
1117 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1118 if (!isa<ConstantInt>(getOperand(i)))
1125 //===----------------------------------------------------------------------===//
1126 // ExtractElementInst Implementation
1127 //===----------------------------------------------------------------------===//
1129 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1130 const std::string &Name,
1131 Instruction *InsertBef)
1132 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1134 OperandTraits<ExtractElementInst>::op_begin(this),
1136 assert(isValidOperands(Val, Index) &&
1137 "Invalid extractelement instruction operands!");
1143 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1144 const std::string &Name,
1145 Instruction *InsertBef)
1146 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1148 OperandTraits<ExtractElementInst>::op_begin(this),
1150 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1151 assert(isValidOperands(Val, Index) &&
1152 "Invalid extractelement instruction operands!");
1159 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1160 const std::string &Name,
1161 BasicBlock *InsertAE)
1162 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1164 OperandTraits<ExtractElementInst>::op_begin(this),
1166 assert(isValidOperands(Val, Index) &&
1167 "Invalid extractelement instruction operands!");
1174 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1175 const std::string &Name,
1176 BasicBlock *InsertAE)
1177 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1179 OperandTraits<ExtractElementInst>::op_begin(this),
1181 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1182 assert(isValidOperands(Val, Index) &&
1183 "Invalid extractelement instruction operands!");
1191 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1192 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1198 //===----------------------------------------------------------------------===//
1199 // InsertElementInst Implementation
1200 //===----------------------------------------------------------------------===//
1202 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1203 : Instruction(IE.getType(), InsertElement,
1204 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1205 Op<0>() = IE.Op<0>();
1206 Op<1>() = IE.Op<1>();
1207 Op<2>() = IE.Op<2>();
1209 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1210 const std::string &Name,
1211 Instruction *InsertBef)
1212 : Instruction(Vec->getType(), InsertElement,
1213 OperandTraits<InsertElementInst>::op_begin(this),
1215 assert(isValidOperands(Vec, Elt, Index) &&
1216 "Invalid insertelement instruction operands!");
1223 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1224 const std::string &Name,
1225 Instruction *InsertBef)
1226 : Instruction(Vec->getType(), InsertElement,
1227 OperandTraits<InsertElementInst>::op_begin(this),
1229 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1230 assert(isValidOperands(Vec, Elt, Index) &&
1231 "Invalid insertelement instruction operands!");
1239 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1240 const std::string &Name,
1241 BasicBlock *InsertAE)
1242 : Instruction(Vec->getType(), InsertElement,
1243 OperandTraits<InsertElementInst>::op_begin(this),
1245 assert(isValidOperands(Vec, Elt, Index) &&
1246 "Invalid insertelement instruction operands!");
1254 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1255 const std::string &Name,
1256 BasicBlock *InsertAE)
1257 : Instruction(Vec->getType(), InsertElement,
1258 OperandTraits<InsertElementInst>::op_begin(this),
1260 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1261 assert(isValidOperands(Vec, Elt, Index) &&
1262 "Invalid insertelement instruction operands!");
1270 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1271 const Value *Index) {
1272 if (!isa<VectorType>(Vec->getType()))
1273 return false; // First operand of insertelement must be vector type.
1275 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1276 return false;// Second operand of insertelement must be vector element type.
1278 if (Index->getType() != Type::Int32Ty)
1279 return false; // Third operand of insertelement must be uint.
1284 //===----------------------------------------------------------------------===//
1285 // ShuffleVectorInst Implementation
1286 //===----------------------------------------------------------------------===//
1288 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1289 : Instruction(SV.getType(), ShuffleVector,
1290 OperandTraits<ShuffleVectorInst>::op_begin(this),
1291 OperandTraits<ShuffleVectorInst>::operands(this)) {
1292 Op<0>() = SV.Op<0>();
1293 Op<1>() = SV.Op<1>();
1294 Op<2>() = SV.Op<2>();
1297 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1298 const std::string &Name,
1299 Instruction *InsertBefore)
1300 : Instruction(V1->getType(), ShuffleVector,
1301 OperandTraits<ShuffleVectorInst>::op_begin(this),
1302 OperandTraits<ShuffleVectorInst>::operands(this),
1304 assert(isValidOperands(V1, V2, Mask) &&
1305 "Invalid shuffle vector instruction operands!");
1312 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1313 const std::string &Name,
1314 BasicBlock *InsertAtEnd)
1315 : Instruction(V1->getType(), ShuffleVector,
1316 OperandTraits<ShuffleVectorInst>::op_begin(this),
1317 OperandTraits<ShuffleVectorInst>::operands(this),
1319 assert(isValidOperands(V1, V2, Mask) &&
1320 "Invalid shuffle vector instruction operands!");
1328 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1329 const Value *Mask) {
1330 if (!isa<VectorType>(V1->getType()) ||
1331 V1->getType() != V2->getType())
1334 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1335 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1336 MaskTy->getElementType() != Type::Int32Ty ||
1337 MaskTy->getNumElements() !=
1338 cast<VectorType>(V1->getType())->getNumElements())
1343 /// getMaskValue - Return the index from the shuffle mask for the specified
1344 /// output result. This is either -1 if the element is undef or a number less
1345 /// than 2*numelements.
1346 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1347 const Constant *Mask = cast<Constant>(getOperand(2));
1348 if (isa<UndefValue>(Mask)) return -1;
1349 if (isa<ConstantAggregateZero>(Mask)) return 0;
1350 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1351 assert(i < MaskCV->getNumOperands() && "Index out of range");
1353 if (isa<UndefValue>(MaskCV->getOperand(i)))
1355 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1358 //===----------------------------------------------------------------------===//
1359 // InsertValueInst Class
1360 //===----------------------------------------------------------------------===//
1362 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1363 unsigned NumIdx, const std::string &Name) {
1364 assert(NumOperands == 2 && "NumOperands not initialized?");
1368 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1372 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1373 const std::string &Name) {
1374 assert(NumOperands == 2 && "NumOperands not initialized?");
1378 Indices.push_back(Idx);
1382 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1383 : Instruction(IVI.getType(), InsertValue,
1384 OperandTraits<InsertValueInst>::op_begin(this), 2),
1385 Indices(IVI.Indices) {
1386 Op<0>() = IVI.getOperand(0);
1387 Op<1>() = IVI.getOperand(1);
1390 InsertValueInst::InsertValueInst(Value *Agg,
1393 const std::string &Name,
1394 Instruction *InsertBefore)
1395 : Instruction(Agg->getType(), InsertValue,
1396 OperandTraits<InsertValueInst>::op_begin(this),
1398 init(Agg, Val, Idx, Name);
1401 InsertValueInst::InsertValueInst(Value *Agg,
1404 const std::string &Name,
1405 BasicBlock *InsertAtEnd)
1406 : Instruction(Agg->getType(), InsertValue,
1407 OperandTraits<InsertValueInst>::op_begin(this),
1409 init(Agg, Val, Idx, Name);
1412 //===----------------------------------------------------------------------===//
1413 // ExtractValueInst Class
1414 //===----------------------------------------------------------------------===//
1416 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1417 const std::string &Name) {
1418 assert(NumOperands == 1 && "NumOperands not initialized?");
1420 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1424 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
1425 assert(NumOperands == 1 && "NumOperands not initialized?");
1427 Indices.push_back(Idx);
1431 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1432 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1433 Indices(EVI.Indices) {
1436 // getIndexedType - Returns the type of the element that would be extracted
1437 // with an extractvalue instruction with the specified parameters.
1439 // A null type is returned if the indices are invalid for the specified
1442 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1443 const unsigned *Idxs,
1445 unsigned CurIdx = 0;
1446 for (; CurIdx != NumIdx; ++CurIdx) {
1447 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1448 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1449 unsigned Index = Idxs[CurIdx];
1450 if (!CT->indexValid(Index)) return 0;
1451 Agg = CT->getTypeAtIndex(Index);
1453 // If the new type forwards to another type, then it is in the middle
1454 // of being refined to another type (and hence, may have dropped all
1455 // references to what it was using before). So, use the new forwarded
1457 if (const Type *Ty = Agg->getForwardedType())
1460 return CurIdx == NumIdx ? Agg : 0;
1463 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1465 return getIndexedType(Agg, &Idx, 1);
1468 //===----------------------------------------------------------------------===//
1469 // BinaryOperator Class
1470 //===----------------------------------------------------------------------===//
1472 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1473 const Type *Ty, const std::string &Name,
1474 Instruction *InsertBefore)
1475 : Instruction(Ty, iType,
1476 OperandTraits<BinaryOperator>::op_begin(this),
1477 OperandTraits<BinaryOperator>::operands(this),
1485 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1486 const Type *Ty, const std::string &Name,
1487 BasicBlock *InsertAtEnd)
1488 : Instruction(Ty, iType,
1489 OperandTraits<BinaryOperator>::op_begin(this),
1490 OperandTraits<BinaryOperator>::operands(this),
1499 void BinaryOperator::init(BinaryOps iType) {
1500 Value *LHS = getOperand(0), *RHS = getOperand(1);
1501 LHS = LHS; RHS = RHS; // Silence warnings.
1502 assert(LHS->getType() == RHS->getType() &&
1503 "Binary operator operand types must match!");
1508 assert(getType() == LHS->getType() &&
1509 "Arithmetic operation should return same type as operands!");
1510 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1511 isa<VectorType>(getType())) &&
1512 "Tried to create an arithmetic operation on a non-arithmetic type!");
1516 assert(getType() == LHS->getType() &&
1517 "Arithmetic operation should return same type as operands!");
1518 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1519 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1520 "Incorrect operand type (not integer) for S/UDIV");
1523 assert(getType() == LHS->getType() &&
1524 "Arithmetic operation should return same type as operands!");
1525 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1526 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1527 && "Incorrect operand type (not floating point) for FDIV");
1531 assert(getType() == LHS->getType() &&
1532 "Arithmetic operation should return same type as operands!");
1533 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1534 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1535 "Incorrect operand type (not integer) for S/UREM");
1538 assert(getType() == LHS->getType() &&
1539 "Arithmetic operation should return same type as operands!");
1540 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1541 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1542 && "Incorrect operand type (not floating point) for FREM");
1547 assert(getType() == LHS->getType() &&
1548 "Shift operation should return same type as operands!");
1549 assert(getType()->isInteger() &&
1550 "Shift operation requires integer operands");
1554 assert(getType() == LHS->getType() &&
1555 "Logical operation should return same type as operands!");
1556 assert((getType()->isInteger() ||
1557 (isa<VectorType>(getType()) &&
1558 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1559 "Tried to create a logical operation on a non-integral type!");
1567 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1568 const std::string &Name,
1569 Instruction *InsertBefore) {
1570 assert(S1->getType() == S2->getType() &&
1571 "Cannot create binary operator with two operands of differing type!");
1572 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1575 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1576 const std::string &Name,
1577 BasicBlock *InsertAtEnd) {
1578 BinaryOperator *Res = Create(Op, S1, S2, Name);
1579 InsertAtEnd->getInstList().push_back(Res);
1583 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1584 Instruction *InsertBefore) {
1585 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1586 return new BinaryOperator(Instruction::Sub,
1588 Op->getType(), Name, InsertBefore);
1591 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1592 BasicBlock *InsertAtEnd) {
1593 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1594 return new BinaryOperator(Instruction::Sub,
1596 Op->getType(), Name, InsertAtEnd);
1599 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1600 Instruction *InsertBefore) {
1602 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1603 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1604 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1606 C = ConstantInt::getAllOnesValue(Op->getType());
1609 return new BinaryOperator(Instruction::Xor, Op, C,
1610 Op->getType(), Name, InsertBefore);
1613 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1614 BasicBlock *InsertAtEnd) {
1616 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1617 // Create a vector of all ones values.
1618 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1620 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1622 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1625 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1626 Op->getType(), Name, InsertAtEnd);
1630 // isConstantAllOnes - Helper function for several functions below
1631 static inline bool isConstantAllOnes(const Value *V) {
1632 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1633 return CI->isAllOnesValue();
1634 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1635 return CV->isAllOnesValue();
1639 bool BinaryOperator::isNeg(const Value *V) {
1640 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1641 if (Bop->getOpcode() == Instruction::Sub)
1642 return Bop->getOperand(0) ==
1643 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1647 bool BinaryOperator::isNot(const Value *V) {
1648 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1649 return (Bop->getOpcode() == Instruction::Xor &&
1650 (isConstantAllOnes(Bop->getOperand(1)) ||
1651 isConstantAllOnes(Bop->getOperand(0))));
1655 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1656 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1657 return cast<BinaryOperator>(BinOp)->getOperand(1);
1660 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1661 return getNegArgument(const_cast<Value*>(BinOp));
1664 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1665 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1666 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1667 Value *Op0 = BO->getOperand(0);
1668 Value *Op1 = BO->getOperand(1);
1669 if (isConstantAllOnes(Op0)) return Op1;
1671 assert(isConstantAllOnes(Op1));
1675 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1676 return getNotArgument(const_cast<Value*>(BinOp));
1680 // swapOperands - Exchange the two operands to this instruction. This
1681 // instruction is safe to use on any binary instruction and does not
1682 // modify the semantics of the instruction. If the instruction is
1683 // order dependent (SetLT f.e.) the opcode is changed.
1685 bool BinaryOperator::swapOperands() {
1686 if (!isCommutative())
1687 return true; // Can't commute operands
1688 Op<0>().swap(Op<1>());
1692 //===----------------------------------------------------------------------===//
1694 //===----------------------------------------------------------------------===//
1696 // Just determine if this cast only deals with integral->integral conversion.
1697 bool CastInst::isIntegerCast() const {
1698 switch (getOpcode()) {
1699 default: return false;
1700 case Instruction::ZExt:
1701 case Instruction::SExt:
1702 case Instruction::Trunc:
1704 case Instruction::BitCast:
1705 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1709 bool CastInst::isLosslessCast() const {
1710 // Only BitCast can be lossless, exit fast if we're not BitCast
1711 if (getOpcode() != Instruction::BitCast)
1714 // Identity cast is always lossless
1715 const Type* SrcTy = getOperand(0)->getType();
1716 const Type* DstTy = getType();
1720 // Pointer to pointer is always lossless.
1721 if (isa<PointerType>(SrcTy))
1722 return isa<PointerType>(DstTy);
1723 return false; // Other types have no identity values
1726 /// This function determines if the CastInst does not require any bits to be
1727 /// changed in order to effect the cast. Essentially, it identifies cases where
1728 /// no code gen is necessary for the cast, hence the name no-op cast. For
1729 /// example, the following are all no-op casts:
1730 /// # bitcast i32* %x to i8*
1731 /// # bitcast <2 x i32> %x to <4 x i16>
1732 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1733 /// @brief Determine if a cast is a no-op.
1734 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1735 switch (getOpcode()) {
1737 assert(!"Invalid CastOp");
1738 case Instruction::Trunc:
1739 case Instruction::ZExt:
1740 case Instruction::SExt:
1741 case Instruction::FPTrunc:
1742 case Instruction::FPExt:
1743 case Instruction::UIToFP:
1744 case Instruction::SIToFP:
1745 case Instruction::FPToUI:
1746 case Instruction::FPToSI:
1747 return false; // These always modify bits
1748 case Instruction::BitCast:
1749 return true; // BitCast never modifies bits.
1750 case Instruction::PtrToInt:
1751 return IntPtrTy->getPrimitiveSizeInBits() ==
1752 getType()->getPrimitiveSizeInBits();
1753 case Instruction::IntToPtr:
1754 return IntPtrTy->getPrimitiveSizeInBits() ==
1755 getOperand(0)->getType()->getPrimitiveSizeInBits();
1759 /// This function determines if a pair of casts can be eliminated and what
1760 /// opcode should be used in the elimination. This assumes that there are two
1761 /// instructions like this:
1762 /// * %F = firstOpcode SrcTy %x to MidTy
1763 /// * %S = secondOpcode MidTy %F to DstTy
1764 /// The function returns a resultOpcode so these two casts can be replaced with:
1765 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1766 /// If no such cast is permited, the function returns 0.
1767 unsigned CastInst::isEliminableCastPair(
1768 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1769 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1771 // Define the 144 possibilities for these two cast instructions. The values
1772 // in this matrix determine what to do in a given situation and select the
1773 // case in the switch below. The rows correspond to firstOp, the columns
1774 // correspond to secondOp. In looking at the table below, keep in mind
1775 // the following cast properties:
1777 // Size Compare Source Destination
1778 // Operator Src ? Size Type Sign Type Sign
1779 // -------- ------------ ------------------- ---------------------
1780 // TRUNC > Integer Any Integral Any
1781 // ZEXT < Integral Unsigned Integer Any
1782 // SEXT < Integral Signed Integer Any
1783 // FPTOUI n/a FloatPt n/a Integral Unsigned
1784 // FPTOSI n/a FloatPt n/a Integral Signed
1785 // UITOFP n/a Integral Unsigned FloatPt n/a
1786 // SITOFP n/a Integral Signed FloatPt n/a
1787 // FPTRUNC > FloatPt n/a FloatPt n/a
1788 // FPEXT < FloatPt n/a FloatPt n/a
1789 // PTRTOINT n/a Pointer n/a Integral Unsigned
1790 // INTTOPTR n/a Integral Unsigned Pointer n/a
1791 // BITCONVERT = FirstClass n/a FirstClass n/a
1793 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1794 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1795 // into "fptoui double to ulong", but this loses information about the range
1796 // of the produced value (we no longer know the top-part is all zeros).
1797 // Further this conversion is often much more expensive for typical hardware,
1798 // and causes issues when building libgcc. We disallow fptosi+sext for the
1800 const unsigned numCastOps =
1801 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1802 static const uint8_t CastResults[numCastOps][numCastOps] = {
1803 // T F F U S F F P I B -+
1804 // R Z S P P I I T P 2 N T |
1805 // U E E 2 2 2 2 R E I T C +- secondOp
1806 // N X X U S F F N X N 2 V |
1807 // C T T I I P P C T T P T -+
1808 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1809 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1810 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1811 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1812 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1813 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1814 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1815 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1816 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1817 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1818 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1819 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1822 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1823 [secondOp-Instruction::CastOpsBegin];
1826 // categorically disallowed
1829 // allowed, use first cast's opcode
1832 // allowed, use second cast's opcode
1835 // no-op cast in second op implies firstOp as long as the DestTy
1837 if (DstTy->isInteger())
1841 // no-op cast in second op implies firstOp as long as the DestTy
1842 // is floating point
1843 if (DstTy->isFloatingPoint())
1847 // no-op cast in first op implies secondOp as long as the SrcTy
1849 if (SrcTy->isInteger())
1853 // no-op cast in first op implies secondOp as long as the SrcTy
1854 // is a floating point
1855 if (SrcTy->isFloatingPoint())
1859 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1860 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1861 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1862 if (MidSize >= PtrSize)
1863 return Instruction::BitCast;
1867 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1868 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1869 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1870 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1871 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1872 if (SrcSize == DstSize)
1873 return Instruction::BitCast;
1874 else if (SrcSize < DstSize)
1878 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1879 return Instruction::ZExt;
1881 // fpext followed by ftrunc is allowed if the bit size returned to is
1882 // the same as the original, in which case its just a bitcast
1884 return Instruction::BitCast;
1885 return 0; // If the types are not the same we can't eliminate it.
1887 // bitcast followed by ptrtoint is allowed as long as the bitcast
1888 // is a pointer to pointer cast.
1889 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1893 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1894 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1898 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1899 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1900 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1901 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1902 if (SrcSize <= PtrSize && SrcSize == DstSize)
1903 return Instruction::BitCast;
1907 // cast combination can't happen (error in input). This is for all cases
1908 // where the MidTy is not the same for the two cast instructions.
1909 assert(!"Invalid Cast Combination");
1912 assert(!"Error in CastResults table!!!");
1918 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1919 const std::string &Name, Instruction *InsertBefore) {
1920 // Construct and return the appropriate CastInst subclass
1922 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1923 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1924 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1925 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1926 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1927 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1928 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1929 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1930 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1931 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1932 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1933 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1935 assert(!"Invalid opcode provided");
1940 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1941 const std::string &Name, BasicBlock *InsertAtEnd) {
1942 // Construct and return the appropriate CastInst subclass
1944 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1945 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1946 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1947 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1948 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1949 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1950 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1951 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1952 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1953 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1954 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1955 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1957 assert(!"Invalid opcode provided");
1962 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1963 const std::string &Name,
1964 Instruction *InsertBefore) {
1965 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1966 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1967 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1970 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1971 const std::string &Name,
1972 BasicBlock *InsertAtEnd) {
1973 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1974 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1975 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1978 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1979 const std::string &Name,
1980 Instruction *InsertBefore) {
1981 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1982 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1983 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
1986 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1987 const std::string &Name,
1988 BasicBlock *InsertAtEnd) {
1989 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1990 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1991 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1994 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
1995 const std::string &Name,
1996 Instruction *InsertBefore) {
1997 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1998 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1999 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2002 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2003 const std::string &Name,
2004 BasicBlock *InsertAtEnd) {
2005 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2006 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2007 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2010 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2011 const std::string &Name,
2012 BasicBlock *InsertAtEnd) {
2013 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2014 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2017 if (Ty->isInteger())
2018 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2019 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2022 /// @brief Create a BitCast or a PtrToInt cast instruction
2023 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2024 const std::string &Name,
2025 Instruction *InsertBefore) {
2026 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2027 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2030 if (Ty->isInteger())
2031 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2032 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2035 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2036 bool isSigned, const std::string &Name,
2037 Instruction *InsertBefore) {
2038 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2039 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2040 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2041 Instruction::CastOps opcode =
2042 (SrcBits == DstBits ? Instruction::BitCast :
2043 (SrcBits > DstBits ? Instruction::Trunc :
2044 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2045 return Create(opcode, C, Ty, Name, InsertBefore);
2048 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2049 bool isSigned, const std::string &Name,
2050 BasicBlock *InsertAtEnd) {
2051 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2052 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2053 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2054 Instruction::CastOps opcode =
2055 (SrcBits == DstBits ? Instruction::BitCast :
2056 (SrcBits > DstBits ? Instruction::Trunc :
2057 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2058 return Create(opcode, C, Ty, Name, InsertAtEnd);
2061 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2062 const std::string &Name,
2063 Instruction *InsertBefore) {
2064 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2066 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2067 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2068 Instruction::CastOps opcode =
2069 (SrcBits == DstBits ? Instruction::BitCast :
2070 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2071 return Create(opcode, C, Ty, Name, InsertBefore);
2074 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2075 const std::string &Name,
2076 BasicBlock *InsertAtEnd) {
2077 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2079 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2080 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2081 Instruction::CastOps opcode =
2082 (SrcBits == DstBits ? Instruction::BitCast :
2083 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2084 return Create(opcode, C, Ty, Name, InsertAtEnd);
2087 // Check whether it is valid to call getCastOpcode for these types.
2088 // This routine must be kept in sync with getCastOpcode.
2089 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2090 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2093 if (SrcTy == DestTy)
2096 // Get the bit sizes, we'll need these
2097 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2098 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2100 // Run through the possibilities ...
2101 if (DestTy->isInteger()) { // Casting to integral
2102 if (SrcTy->isInteger()) { // Casting from integral
2104 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2106 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2107 // Casting from vector
2108 return DestBits == PTy->getBitWidth();
2109 } else { // Casting from something else
2110 return isa<PointerType>(SrcTy);
2112 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2113 if (SrcTy->isInteger()) { // Casting from integral
2115 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2117 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2118 // Casting from vector
2119 return DestBits == PTy->getBitWidth();
2120 } else { // Casting from something else
2123 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2124 // Casting to vector
2125 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2126 // Casting from vector
2127 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2128 } else { // Casting from something else
2129 return DestPTy->getBitWidth() == SrcBits;
2131 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2132 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2134 } else if (SrcTy->isInteger()) { // Casting from integral
2136 } else { // Casting from something else
2139 } else { // Casting to something else
2144 // Provide a way to get a "cast" where the cast opcode is inferred from the
2145 // types and size of the operand. This, basically, is a parallel of the
2146 // logic in the castIsValid function below. This axiom should hold:
2147 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2148 // should not assert in castIsValid. In other words, this produces a "correct"
2149 // casting opcode for the arguments passed to it.
2150 // This routine must be kept in sync with isCastable.
2151 Instruction::CastOps
2152 CastInst::getCastOpcode(
2153 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2154 // Get the bit sizes, we'll need these
2155 const Type *SrcTy = Src->getType();
2156 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2157 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2159 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2160 "Only first class types are castable!");
2162 // Run through the possibilities ...
2163 if (DestTy->isInteger()) { // Casting to integral
2164 if (SrcTy->isInteger()) { // Casting from integral
2165 if (DestBits < SrcBits)
2166 return Trunc; // int -> smaller int
2167 else if (DestBits > SrcBits) { // its an extension
2169 return SExt; // signed -> SEXT
2171 return ZExt; // unsigned -> ZEXT
2173 return BitCast; // Same size, No-op cast
2175 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2177 return FPToSI; // FP -> sint
2179 return FPToUI; // FP -> uint
2180 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2181 assert(DestBits == PTy->getBitWidth() &&
2182 "Casting vector to integer of different width");
2183 return BitCast; // Same size, no-op cast
2185 assert(isa<PointerType>(SrcTy) &&
2186 "Casting from a value that is not first-class type");
2187 return PtrToInt; // ptr -> int
2189 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2190 if (SrcTy->isInteger()) { // Casting from integral
2192 return SIToFP; // sint -> FP
2194 return UIToFP; // uint -> FP
2195 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2196 if (DestBits < SrcBits) {
2197 return FPTrunc; // FP -> smaller FP
2198 } else if (DestBits > SrcBits) {
2199 return FPExt; // FP -> larger FP
2201 return BitCast; // same size, no-op cast
2203 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2204 assert(DestBits == PTy->getBitWidth() &&
2205 "Casting vector to floating point of different width");
2206 return BitCast; // same size, no-op cast
2208 assert(0 && "Casting pointer or non-first class to float");
2210 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2211 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2212 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2213 "Casting vector to vector of different widths");
2214 return BitCast; // vector -> vector
2215 } else if (DestPTy->getBitWidth() == SrcBits) {
2216 return BitCast; // float/int -> vector
2218 assert(!"Illegal cast to vector (wrong type or size)");
2220 } else if (isa<PointerType>(DestTy)) {
2221 if (isa<PointerType>(SrcTy)) {
2222 return BitCast; // ptr -> ptr
2223 } else if (SrcTy->isInteger()) {
2224 return IntToPtr; // int -> ptr
2226 assert(!"Casting pointer to other than pointer or int");
2229 assert(!"Casting to type that is not first-class");
2232 // If we fall through to here we probably hit an assertion cast above
2233 // and assertions are not turned on. Anything we return is an error, so
2234 // BitCast is as good a choice as any.
2238 //===----------------------------------------------------------------------===//
2239 // CastInst SubClass Constructors
2240 //===----------------------------------------------------------------------===//
2242 /// Check that the construction parameters for a CastInst are correct. This
2243 /// could be broken out into the separate constructors but it is useful to have
2244 /// it in one place and to eliminate the redundant code for getting the sizes
2245 /// of the types involved.
2247 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2249 // Check for type sanity on the arguments
2250 const Type *SrcTy = S->getType();
2251 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2254 // Get the size of the types in bits, we'll need this later
2255 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2256 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2258 // Switch on the opcode provided
2260 default: return false; // This is an input error
2261 case Instruction::Trunc:
2262 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2263 case Instruction::ZExt:
2264 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2265 case Instruction::SExt:
2266 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2267 case Instruction::FPTrunc:
2268 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2269 SrcBitSize > DstBitSize;
2270 case Instruction::FPExt:
2271 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2272 SrcBitSize < DstBitSize;
2273 case Instruction::UIToFP:
2274 case Instruction::SIToFP:
2275 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2276 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2277 return SVTy->getElementType()->isInteger() &&
2278 DVTy->getElementType()->isFloatingPoint() &&
2279 SVTy->getNumElements() == DVTy->getNumElements();
2282 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2283 case Instruction::FPToUI:
2284 case Instruction::FPToSI:
2285 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2286 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2287 return SVTy->getElementType()->isFloatingPoint() &&
2288 DVTy->getElementType()->isInteger() &&
2289 SVTy->getNumElements() == DVTy->getNumElements();
2292 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2293 case Instruction::PtrToInt:
2294 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2295 case Instruction::IntToPtr:
2296 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2297 case Instruction::BitCast:
2298 // BitCast implies a no-op cast of type only. No bits change.
2299 // However, you can't cast pointers to anything but pointers.
2300 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2303 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2304 // these cases, the cast is okay if the source and destination bit widths
2306 return SrcBitSize == DstBitSize;
2310 TruncInst::TruncInst(
2311 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2312 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2313 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2316 TruncInst::TruncInst(
2317 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2318 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2319 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2323 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2324 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2325 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2329 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2330 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2331 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2334 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2335 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2336 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2340 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2341 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2342 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2345 FPTruncInst::FPTruncInst(
2346 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2347 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2348 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2351 FPTruncInst::FPTruncInst(
2352 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2353 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2354 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2357 FPExtInst::FPExtInst(
2358 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2359 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2360 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2363 FPExtInst::FPExtInst(
2364 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2365 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2366 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2369 UIToFPInst::UIToFPInst(
2370 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2371 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2372 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2375 UIToFPInst::UIToFPInst(
2376 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2377 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2378 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2381 SIToFPInst::SIToFPInst(
2382 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2383 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2384 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2387 SIToFPInst::SIToFPInst(
2388 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2389 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2390 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2393 FPToUIInst::FPToUIInst(
2394 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2395 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2396 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2399 FPToUIInst::FPToUIInst(
2400 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2401 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2402 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2405 FPToSIInst::FPToSIInst(
2406 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2407 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2408 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2411 FPToSIInst::FPToSIInst(
2412 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2413 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2414 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2417 PtrToIntInst::PtrToIntInst(
2418 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2419 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2420 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2423 PtrToIntInst::PtrToIntInst(
2424 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2425 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2426 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2429 IntToPtrInst::IntToPtrInst(
2430 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2431 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2432 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2435 IntToPtrInst::IntToPtrInst(
2436 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2437 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2438 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2441 BitCastInst::BitCastInst(
2442 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2443 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2444 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2447 BitCastInst::BitCastInst(
2448 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2449 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2450 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2453 //===----------------------------------------------------------------------===//
2455 //===----------------------------------------------------------------------===//
2457 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2458 Value *LHS, Value *RHS, const std::string &Name,
2459 Instruction *InsertBefore)
2460 : Instruction(ty, op,
2461 OperandTraits<CmpInst>::op_begin(this),
2462 OperandTraits<CmpInst>::operands(this),
2466 SubclassData = predicate;
2470 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2471 Value *LHS, Value *RHS, const std::string &Name,
2472 BasicBlock *InsertAtEnd)
2473 : Instruction(ty, op,
2474 OperandTraits<CmpInst>::op_begin(this),
2475 OperandTraits<CmpInst>::operands(this),
2479 SubclassData = predicate;
2484 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2485 const std::string &Name, Instruction *InsertBefore) {
2486 if (Op == Instruction::ICmp) {
2487 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2490 if (Op == Instruction::FCmp) {
2491 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2494 if (Op == Instruction::VICmp) {
2495 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2498 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2503 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2504 const std::string &Name, BasicBlock *InsertAtEnd) {
2505 if (Op == Instruction::ICmp) {
2506 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2509 if (Op == Instruction::FCmp) {
2510 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2513 if (Op == Instruction::VICmp) {
2514 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2517 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2521 void CmpInst::swapOperands() {
2522 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2525 cast<FCmpInst>(this)->swapOperands();
2528 bool CmpInst::isCommutative() {
2529 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2530 return IC->isCommutative();
2531 return cast<FCmpInst>(this)->isCommutative();
2534 bool CmpInst::isEquality() {
2535 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2536 return IC->isEquality();
2537 return cast<FCmpInst>(this)->isEquality();
2541 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2543 default: assert(!"Unknown cmp predicate!");
2544 case ICMP_EQ: return ICMP_NE;
2545 case ICMP_NE: return ICMP_EQ;
2546 case ICMP_UGT: return ICMP_ULE;
2547 case ICMP_ULT: return ICMP_UGE;
2548 case ICMP_UGE: return ICMP_ULT;
2549 case ICMP_ULE: return ICMP_UGT;
2550 case ICMP_SGT: return ICMP_SLE;
2551 case ICMP_SLT: return ICMP_SGE;
2552 case ICMP_SGE: return ICMP_SLT;
2553 case ICMP_SLE: return ICMP_SGT;
2555 case FCMP_OEQ: return FCMP_UNE;
2556 case FCMP_ONE: return FCMP_UEQ;
2557 case FCMP_OGT: return FCMP_ULE;
2558 case FCMP_OLT: return FCMP_UGE;
2559 case FCMP_OGE: return FCMP_ULT;
2560 case FCMP_OLE: return FCMP_UGT;
2561 case FCMP_UEQ: return FCMP_ONE;
2562 case FCMP_UNE: return FCMP_OEQ;
2563 case FCMP_UGT: return FCMP_OLE;
2564 case FCMP_ULT: return FCMP_OGE;
2565 case FCMP_UGE: return FCMP_OLT;
2566 case FCMP_ULE: return FCMP_OGT;
2567 case FCMP_ORD: return FCMP_UNO;
2568 case FCMP_UNO: return FCMP_ORD;
2569 case FCMP_TRUE: return FCMP_FALSE;
2570 case FCMP_FALSE: return FCMP_TRUE;
2574 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2576 default: assert(! "Unknown icmp predicate!");
2577 case ICMP_EQ: case ICMP_NE:
2578 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2580 case ICMP_UGT: return ICMP_SGT;
2581 case ICMP_ULT: return ICMP_SLT;
2582 case ICMP_UGE: return ICMP_SGE;
2583 case ICMP_ULE: return ICMP_SLE;
2587 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2589 default: assert(! "Unknown icmp predicate!");
2590 case ICMP_EQ: case ICMP_NE:
2591 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2593 case ICMP_SGT: return ICMP_UGT;
2594 case ICMP_SLT: return ICMP_ULT;
2595 case ICMP_SGE: return ICMP_UGE;
2596 case ICMP_SLE: return ICMP_ULE;
2600 bool ICmpInst::isSignedPredicate(Predicate pred) {
2602 default: assert(! "Unknown icmp predicate!");
2603 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2605 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2606 case ICMP_UGE: case ICMP_ULE:
2611 /// Initialize a set of values that all satisfy the condition with C.
2614 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2617 uint32_t BitWidth = C.getBitWidth();
2619 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2620 case ICmpInst::ICMP_EQ: Upper++; break;
2621 case ICmpInst::ICMP_NE: Lower++; break;
2622 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2623 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2624 case ICmpInst::ICMP_UGT:
2625 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2627 case ICmpInst::ICMP_SGT:
2628 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2630 case ICmpInst::ICMP_ULE:
2631 Lower = APInt::getMinValue(BitWidth); Upper++;
2633 case ICmpInst::ICMP_SLE:
2634 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2636 case ICmpInst::ICMP_UGE:
2637 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2639 case ICmpInst::ICMP_SGE:
2640 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2643 return ConstantRange(Lower, Upper);
2646 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2648 default: assert(!"Unknown cmp predicate!");
2649 case ICMP_EQ: case ICMP_NE:
2651 case ICMP_SGT: return ICMP_SLT;
2652 case ICMP_SLT: return ICMP_SGT;
2653 case ICMP_SGE: return ICMP_SLE;
2654 case ICMP_SLE: return ICMP_SGE;
2655 case ICMP_UGT: return ICMP_ULT;
2656 case ICMP_ULT: return ICMP_UGT;
2657 case ICMP_UGE: return ICMP_ULE;
2658 case ICMP_ULE: return ICMP_UGE;
2660 case FCMP_FALSE: case FCMP_TRUE:
2661 case FCMP_OEQ: case FCMP_ONE:
2662 case FCMP_UEQ: case FCMP_UNE:
2663 case FCMP_ORD: case FCMP_UNO:
2665 case FCMP_OGT: return FCMP_OLT;
2666 case FCMP_OLT: return FCMP_OGT;
2667 case FCMP_OGE: return FCMP_OLE;
2668 case FCMP_OLE: return FCMP_OGE;
2669 case FCMP_UGT: return FCMP_ULT;
2670 case FCMP_ULT: return FCMP_UGT;
2671 case FCMP_UGE: return FCMP_ULE;
2672 case FCMP_ULE: return FCMP_UGE;
2676 bool CmpInst::isUnsigned(unsigned short predicate) {
2677 switch (predicate) {
2678 default: return false;
2679 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2680 case ICmpInst::ICMP_UGE: return true;
2684 bool CmpInst::isSigned(unsigned short predicate){
2685 switch (predicate) {
2686 default: return false;
2687 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2688 case ICmpInst::ICMP_SGE: return true;
2692 bool CmpInst::isOrdered(unsigned short predicate) {
2693 switch (predicate) {
2694 default: return false;
2695 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2696 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2697 case FCmpInst::FCMP_ORD: return true;
2701 bool CmpInst::isUnordered(unsigned short predicate) {
2702 switch (predicate) {
2703 default: return false;
2704 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2705 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2706 case FCmpInst::FCMP_UNO: return true;
2710 //===----------------------------------------------------------------------===//
2711 // SwitchInst Implementation
2712 //===----------------------------------------------------------------------===//
2714 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2715 assert(Value && Default);
2716 ReservedSpace = 2+NumCases*2;
2718 OperandList = allocHungoffUses(ReservedSpace);
2720 OperandList[0] = Value;
2721 OperandList[1] = Default;
2724 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2725 /// switch on and a default destination. The number of additional cases can
2726 /// be specified here to make memory allocation more efficient. This
2727 /// constructor can also autoinsert before another instruction.
2728 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2729 Instruction *InsertBefore)
2730 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2731 init(Value, Default, NumCases);
2734 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2735 /// switch on and a default destination. The number of additional cases can
2736 /// be specified here to make memory allocation more efficient. This
2737 /// constructor also autoinserts at the end of the specified BasicBlock.
2738 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2739 BasicBlock *InsertAtEnd)
2740 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2741 init(Value, Default, NumCases);
2744 SwitchInst::SwitchInst(const SwitchInst &SI)
2745 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2746 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2747 Use *OL = OperandList, *InOL = SI.OperandList;
2748 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2750 OL[i+1] = InOL[i+1];
2754 SwitchInst::~SwitchInst() {
2755 dropHungoffUses(OperandList);
2759 /// addCase - Add an entry to the switch instruction...
2761 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2762 unsigned OpNo = NumOperands;
2763 if (OpNo+2 > ReservedSpace)
2764 resizeOperands(0); // Get more space!
2765 // Initialize some new operands.
2766 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2767 NumOperands = OpNo+2;
2768 OperandList[OpNo] = OnVal;
2769 OperandList[OpNo+1] = Dest;
2772 /// removeCase - This method removes the specified successor from the switch
2773 /// instruction. Note that this cannot be used to remove the default
2774 /// destination (successor #0).
2776 void SwitchInst::removeCase(unsigned idx) {
2777 assert(idx != 0 && "Cannot remove the default case!");
2778 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2780 unsigned NumOps = getNumOperands();
2781 Use *OL = OperandList;
2783 // Move everything after this operand down.
2785 // FIXME: we could just swap with the end of the list, then erase. However,
2786 // client might not expect this to happen. The code as it is thrashes the
2787 // use/def lists, which is kinda lame.
2788 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2790 OL[i-2+1] = OL[i+1];
2793 // Nuke the last value.
2794 OL[NumOps-2].set(0);
2795 OL[NumOps-2+1].set(0);
2796 NumOperands = NumOps-2;
2799 /// resizeOperands - resize operands - This adjusts the length of the operands
2800 /// list according to the following behavior:
2801 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2802 /// of operation. This grows the number of ops by 3 times.
2803 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2804 /// 3. If NumOps == NumOperands, trim the reserved space.
2806 void SwitchInst::resizeOperands(unsigned NumOps) {
2807 unsigned e = getNumOperands();
2810 } else if (NumOps*2 > NumOperands) {
2811 // No resize needed.
2812 if (ReservedSpace >= NumOps) return;
2813 } else if (NumOps == NumOperands) {
2814 if (ReservedSpace == NumOps) return;
2819 ReservedSpace = NumOps;
2820 Use *NewOps = allocHungoffUses(NumOps);
2821 Use *OldOps = OperandList;
2822 for (unsigned i = 0; i != e; ++i) {
2823 NewOps[i] = OldOps[i];
2825 OperandList = NewOps;
2826 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2830 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2831 return getSuccessor(idx);
2833 unsigned SwitchInst::getNumSuccessorsV() const {
2834 return getNumSuccessors();
2836 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2837 setSuccessor(idx, B);
2840 //===----------------------------------------------------------------------===//
2841 // GetResultInst Implementation
2842 //===----------------------------------------------------------------------===//
2844 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2845 const std::string &Name,
2846 Instruction *InsertBef)
2847 : UnaryInstruction(cast<StructType>(Aggregate->getType())
2848 ->getElementType(Index),
2849 GetResult, Aggregate, InsertBef),
2851 assert(isValidOperands(Aggregate, Index)
2852 && "Invalid GetResultInst operands!");
2856 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2860 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2861 unsigned NumElements = STy->getNumElements();
2862 if (Index >= NumElements || NumElements == 0)
2865 // getresult aggregate value's element types are restricted to
2866 // avoid nested aggregates.
2867 for (unsigned i = 0; i < NumElements; ++i)
2868 if (!STy->getElementType(i)->isFirstClassType())
2871 // Otherwise, Aggregate is valid.
2877 // Define these methods here so vtables don't get emitted into every translation
2878 // unit that uses these classes.
2880 GetElementPtrInst *GetElementPtrInst::clone() const {
2881 return new(getNumOperands()) GetElementPtrInst(*this);
2884 BinaryOperator *BinaryOperator::clone() const {
2885 return Create(getOpcode(), Op<0>(), Op<1>());
2888 FCmpInst* FCmpInst::clone() const {
2889 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2891 ICmpInst* ICmpInst::clone() const {
2892 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2895 VFCmpInst* VFCmpInst::clone() const {
2896 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2898 VICmpInst* VICmpInst::clone() const {
2899 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2902 ExtractValueInst *ExtractValueInst::clone() const {
2903 return new ExtractValueInst(*this);
2905 InsertValueInst *InsertValueInst::clone() const {
2906 return new InsertValueInst(*this);
2910 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2911 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2912 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2913 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2914 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2915 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2916 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2917 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2918 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2919 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2920 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2921 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2922 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2923 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2924 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2925 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2926 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2927 CallInst *CallInst::clone() const {
2928 return new(getNumOperands()) CallInst(*this);
2930 SelectInst *SelectInst::clone() const {
2931 return new(getNumOperands()) SelectInst(*this);
2933 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2935 ExtractElementInst *ExtractElementInst::clone() const {
2936 return new ExtractElementInst(*this);
2938 InsertElementInst *InsertElementInst::clone() const {
2939 return InsertElementInst::Create(*this);
2941 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2942 return new ShuffleVectorInst(*this);
2944 PHINode *PHINode::clone() const { return new PHINode(*this); }
2945 ReturnInst *ReturnInst::clone() const {
2946 return new(getNumOperands()) ReturnInst(*this);
2948 BranchInst *BranchInst::clone() const {
2949 return new(getNumOperands()) BranchInst(*this);
2951 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2952 InvokeInst *InvokeInst::clone() const {
2953 return new(getNumOperands()) InvokeInst(*this);
2955 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2956 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2957 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }