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/Operator.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/Support/ConstantRange.h"
24 #include "llvm/Support/MathExtras.h"
27 //===----------------------------------------------------------------------===//
29 //===----------------------------------------------------------------------===//
31 #define CALLSITE_DELEGATE_GETTER(METHOD) \
32 Instruction *II(getInstruction()); \
34 ? cast<CallInst>(II)->METHOD \
35 : cast<InvokeInst>(II)->METHOD
37 #define CALLSITE_DELEGATE_SETTER(METHOD) \
38 Instruction *II(getInstruction()); \
40 cast<CallInst>(II)->METHOD; \
42 cast<InvokeInst>(II)->METHOD
44 CallSite::CallSite(Instruction *C) {
45 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
47 I.setInt(isa<CallInst>(C));
49 CallingConv::ID CallSite::getCallingConv() const {
50 CALLSITE_DELEGATE_GETTER(getCallingConv());
52 void CallSite::setCallingConv(CallingConv::ID CC) {
53 CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
55 const AttrListPtr &CallSite::getAttributes() const {
56 CALLSITE_DELEGATE_GETTER(getAttributes());
58 void CallSite::setAttributes(const AttrListPtr &PAL) {
59 CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
61 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
62 CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
64 uint16_t CallSite::getParamAlignment(uint16_t i) const {
65 CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
67 bool CallSite::doesNotAccessMemory() const {
68 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
70 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
71 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
73 bool CallSite::onlyReadsMemory() const {
74 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
76 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
77 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
79 bool CallSite::doesNotReturn() const {
80 CALLSITE_DELEGATE_GETTER(doesNotReturn());
82 void CallSite::setDoesNotReturn(bool doesNotReturn) {
83 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
85 bool CallSite::doesNotThrow() const {
86 CALLSITE_DELEGATE_GETTER(doesNotThrow());
88 void CallSite::setDoesNotThrow(bool doesNotThrow) {
89 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
92 bool CallSite::hasArgument(const Value *Arg) const {
93 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
99 #undef CALLSITE_DELEGATE_GETTER
100 #undef CALLSITE_DELEGATE_SETTER
102 //===----------------------------------------------------------------------===//
103 // TerminatorInst Class
104 //===----------------------------------------------------------------------===//
106 // Out of line virtual method, so the vtable, etc has a home.
107 TerminatorInst::~TerminatorInst() {
110 //===----------------------------------------------------------------------===//
111 // UnaryInstruction Class
112 //===----------------------------------------------------------------------===//
114 // Out of line virtual method, so the vtable, etc has a home.
115 UnaryInstruction::~UnaryInstruction() {
118 //===----------------------------------------------------------------------===//
120 //===----------------------------------------------------------------------===//
122 /// areInvalidOperands - Return a string if the specified operands are invalid
123 /// for a select operation, otherwise return null.
124 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
125 if (Op1->getType() != Op2->getType())
126 return "both values to select must have same type";
128 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
130 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
131 return "vector select condition element type must be i1";
132 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
134 return "selected values for vector select must be vectors";
135 if (ET->getNumElements() != VT->getNumElements())
136 return "vector select requires selected vectors to have "
137 "the same vector length as select condition";
138 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
139 return "select condition must be i1 or <n x i1>";
145 //===----------------------------------------------------------------------===//
147 //===----------------------------------------------------------------------===//
149 PHINode::PHINode(const PHINode &PN)
150 : Instruction(PN.getType(), Instruction::PHI,
151 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
152 ReservedSpace(PN.getNumOperands()) {
153 Use *OL = OperandList;
154 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
155 OL[i] = PN.getOperand(i);
156 OL[i+1] = PN.getOperand(i+1);
158 SubclassOptionalData = PN.SubclassOptionalData;
161 PHINode::~PHINode() {
163 dropHungoffUses(OperandList);
166 // removeIncomingValue - Remove an incoming value. This is useful if a
167 // predecessor basic block is deleted.
168 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
169 unsigned NumOps = getNumOperands();
170 Use *OL = OperandList;
171 assert(Idx*2 < NumOps && "BB not in PHI node!");
172 Value *Removed = OL[Idx*2];
174 // Move everything after this operand down.
176 // FIXME: we could just swap with the end of the list, then erase. However,
177 // client might not expect this to happen. The code as it is thrashes the
178 // use/def lists, which is kinda lame.
179 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
184 // Nuke the last value.
186 OL[NumOps-2+1].set(0);
187 NumOperands = NumOps-2;
189 // If the PHI node is dead, because it has zero entries, nuke it now.
190 if (NumOps == 2 && DeletePHIIfEmpty) {
191 // If anyone is using this PHI, make them use a dummy value instead...
192 replaceAllUsesWith(UndefValue::get(getType()));
198 /// resizeOperands - resize operands - This adjusts the length of the operands
199 /// list according to the following behavior:
200 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
201 /// of operation. This grows the number of ops by 1.5 times.
202 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
203 /// 3. If NumOps == NumOperands, trim the reserved space.
205 void PHINode::resizeOperands(unsigned NumOps) {
206 unsigned e = getNumOperands();
209 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
210 } else if (NumOps*2 > NumOperands) {
212 if (ReservedSpace >= NumOps) return;
213 } else if (NumOps == NumOperands) {
214 if (ReservedSpace == NumOps) return;
219 ReservedSpace = NumOps;
220 Use *OldOps = OperandList;
221 Use *NewOps = allocHungoffUses(NumOps);
222 std::copy(OldOps, OldOps + e, NewOps);
223 OperandList = NewOps;
224 if (OldOps) Use::zap(OldOps, OldOps + e, true);
227 /// hasConstantValue - If the specified PHI node always merges together the same
228 /// value, return the value, otherwise return null.
230 /// If the PHI has undef operands, but all the rest of the operands are
231 /// some unique value, return that value if it can be proved that the
232 /// value dominates the PHI. If DT is null, use a conservative check,
233 /// otherwise use DT to test for dominance.
235 Value *PHINode::hasConstantValue(DominatorTree *DT) const {
236 // If the PHI node only has one incoming value, eliminate the PHI node...
237 if (getNumIncomingValues() == 1) {
238 if (getIncomingValue(0) != this) // not X = phi X
239 return getIncomingValue(0);
241 return UndefValue::get(getType()); // Self cycle is dead.
244 // Otherwise if all of the incoming values are the same for the PHI, replace
245 // the PHI node with the incoming value.
248 bool HasUndefInput = false;
249 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
250 if (isa<UndefValue>(getIncomingValue(i))) {
251 HasUndefInput = true;
252 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
253 if (InVal && getIncomingValue(i) != InVal)
254 return 0; // Not the same, bail out.
256 InVal = getIncomingValue(i);
259 // The only case that could cause InVal to be null is if we have a PHI node
260 // that only has entries for itself. In this case, there is no entry into the
261 // loop, so kill the PHI.
263 if (InVal == 0) InVal = UndefValue::get(getType());
265 // If we have a PHI node like phi(X, undef, X), where X is defined by some
266 // instruction, we cannot always return X as the result of the PHI node. Only
267 // do this if X is not an instruction (thus it must dominate the PHI block),
268 // or if the client is prepared to deal with this possibility.
270 if (Instruction *IV = dyn_cast<Instruction>(InVal)) {
272 // We have a DominatorTree. Do a precise test.
273 if (!DT->dominates(IV, this))
276 // If it's in the entry block, it dominates everything.
277 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
279 return 0; // Cannot guarantee that InVal dominates this PHINode.
283 // All of the incoming values are the same, return the value now.
288 //===----------------------------------------------------------------------===//
289 // CallInst Implementation
290 //===----------------------------------------------------------------------===//
292 CallInst::~CallInst() {
295 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
296 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
297 Use *OL = OperandList;
300 const FunctionType *FTy =
301 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
302 FTy = FTy; // silence warning.
304 assert((NumParams == FTy->getNumParams() ||
305 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
306 "Calling a function with bad signature!");
307 for (unsigned i = 0; i != NumParams; ++i) {
308 assert((i >= FTy->getNumParams() ||
309 FTy->getParamType(i) == Params[i]->getType()) &&
310 "Calling a function with a bad signature!");
315 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
316 assert(NumOperands == 3 && "NumOperands not set up?");
317 Use *OL = OperandList;
322 const FunctionType *FTy =
323 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
324 FTy = FTy; // silence warning.
326 assert((FTy->getNumParams() == 2 ||
327 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
328 "Calling a function with bad signature");
329 assert((0 >= FTy->getNumParams() ||
330 FTy->getParamType(0) == Actual1->getType()) &&
331 "Calling a function with a bad signature!");
332 assert((1 >= FTy->getNumParams() ||
333 FTy->getParamType(1) == Actual2->getType()) &&
334 "Calling a function with a bad signature!");
337 void CallInst::init(Value *Func, Value *Actual) {
338 assert(NumOperands == 2 && "NumOperands not set up?");
339 Use *OL = OperandList;
343 const FunctionType *FTy =
344 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
345 FTy = FTy; // silence warning.
347 assert((FTy->getNumParams() == 1 ||
348 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
349 "Calling a function with bad signature");
350 assert((0 == FTy->getNumParams() ||
351 FTy->getParamType(0) == Actual->getType()) &&
352 "Calling a function with a bad signature!");
355 void CallInst::init(Value *Func) {
356 assert(NumOperands == 1 && "NumOperands not set up?");
357 Use *OL = OperandList;
360 const FunctionType *FTy =
361 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
362 FTy = FTy; // silence warning.
364 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
367 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
368 Instruction *InsertBefore)
369 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
370 ->getElementType())->getReturnType(),
372 OperandTraits<CallInst>::op_end(this) - 2,
378 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
379 BasicBlock *InsertAtEnd)
380 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
381 ->getElementType())->getReturnType(),
383 OperandTraits<CallInst>::op_end(this) - 2,
388 CallInst::CallInst(Value *Func, const Twine &Name,
389 Instruction *InsertBefore)
390 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
391 ->getElementType())->getReturnType(),
393 OperandTraits<CallInst>::op_end(this) - 1,
399 CallInst::CallInst(Value *Func, const Twine &Name,
400 BasicBlock *InsertAtEnd)
401 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
402 ->getElementType())->getReturnType(),
404 OperandTraits<CallInst>::op_end(this) - 1,
410 CallInst::CallInst(const CallInst &CI)
411 : Instruction(CI.getType(), Instruction::Call,
412 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
413 CI.getNumOperands()) {
414 setAttributes(CI.getAttributes());
415 SubclassData = CI.SubclassData;
416 Use *OL = OperandList;
417 Use *InOL = CI.OperandList;
418 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
420 SubclassOptionalData = CI.SubclassOptionalData;
423 void CallInst::addAttribute(unsigned i, Attributes attr) {
424 AttrListPtr PAL = getAttributes();
425 PAL = PAL.addAttr(i, attr);
429 void CallInst::removeAttribute(unsigned i, Attributes attr) {
430 AttrListPtr PAL = getAttributes();
431 PAL = PAL.removeAttr(i, attr);
435 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
436 if (AttributeList.paramHasAttr(i, attr))
438 if (const Function *F = getCalledFunction())
439 return F->paramHasAttr(i, attr);
444 //===----------------------------------------------------------------------===//
445 // InvokeInst Implementation
446 //===----------------------------------------------------------------------===//
448 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
449 Value* const *Args, unsigned NumArgs) {
450 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
451 Use *OL = OperandList;
455 const FunctionType *FTy =
456 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
457 FTy = FTy; // silence warning.
459 assert(((NumArgs == FTy->getNumParams()) ||
460 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
461 "Calling a function with bad signature");
463 for (unsigned i = 0, e = NumArgs; i != e; i++) {
464 assert((i >= FTy->getNumParams() ||
465 FTy->getParamType(i) == Args[i]->getType()) &&
466 "Invoking a function with a bad signature!");
472 InvokeInst::InvokeInst(const InvokeInst &II)
473 : TerminatorInst(II.getType(), Instruction::Invoke,
474 OperandTraits<InvokeInst>::op_end(this)
475 - II.getNumOperands(),
476 II.getNumOperands()) {
477 setAttributes(II.getAttributes());
478 SubclassData = II.SubclassData;
479 Use *OL = OperandList, *InOL = II.OperandList;
480 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
482 SubclassOptionalData = II.SubclassOptionalData;
485 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
486 return getSuccessor(idx);
488 unsigned InvokeInst::getNumSuccessorsV() const {
489 return getNumSuccessors();
491 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
492 return setSuccessor(idx, B);
495 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
496 if (AttributeList.paramHasAttr(i, attr))
498 if (const Function *F = getCalledFunction())
499 return F->paramHasAttr(i, attr);
503 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
504 AttrListPtr PAL = getAttributes();
505 PAL = PAL.addAttr(i, attr);
509 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
510 AttrListPtr PAL = getAttributes();
511 PAL = PAL.removeAttr(i, attr);
516 //===----------------------------------------------------------------------===//
517 // ReturnInst Implementation
518 //===----------------------------------------------------------------------===//
520 ReturnInst::ReturnInst(const ReturnInst &RI)
521 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
522 OperandTraits<ReturnInst>::op_end(this) -
524 RI.getNumOperands()) {
525 if (RI.getNumOperands())
526 Op<0>() = RI.Op<0>();
527 SubclassOptionalData = RI.SubclassOptionalData;
530 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
531 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
532 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
537 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
538 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
539 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
544 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
545 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
546 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
549 unsigned ReturnInst::getNumSuccessorsV() const {
550 return getNumSuccessors();
553 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
554 /// emit the vtable for the class in this translation unit.
555 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
556 llvm_unreachable("ReturnInst has no successors!");
559 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
560 llvm_unreachable("ReturnInst has no successors!");
564 ReturnInst::~ReturnInst() {
567 //===----------------------------------------------------------------------===//
568 // UnwindInst Implementation
569 //===----------------------------------------------------------------------===//
571 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
572 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
573 0, 0, InsertBefore) {
575 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
576 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
581 unsigned UnwindInst::getNumSuccessorsV() const {
582 return getNumSuccessors();
585 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
586 llvm_unreachable("UnwindInst has no successors!");
589 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
590 llvm_unreachable("UnwindInst has no successors!");
594 //===----------------------------------------------------------------------===//
595 // UnreachableInst Implementation
596 //===----------------------------------------------------------------------===//
598 UnreachableInst::UnreachableInst(LLVMContext &Context,
599 Instruction *InsertBefore)
600 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
601 0, 0, InsertBefore) {
603 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
604 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
608 unsigned UnreachableInst::getNumSuccessorsV() const {
609 return getNumSuccessors();
612 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
613 llvm_unreachable("UnwindInst has no successors!");
616 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
617 llvm_unreachable("UnwindInst has no successors!");
621 //===----------------------------------------------------------------------===//
622 // BranchInst Implementation
623 //===----------------------------------------------------------------------===//
625 void BranchInst::AssertOK() {
627 assert(getCondition()->getType() == Type::getInt1Ty(getContext()) &&
628 "May only branch on boolean predicates!");
631 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
632 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
633 OperandTraits<BranchInst>::op_end(this) - 1,
635 assert(IfTrue != 0 && "Branch destination may not be null!");
638 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
639 Instruction *InsertBefore)
640 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
641 OperandTraits<BranchInst>::op_end(this) - 3,
651 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
652 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
653 OperandTraits<BranchInst>::op_end(this) - 1,
655 assert(IfTrue != 0 && "Branch destination may not be null!");
659 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
660 BasicBlock *InsertAtEnd)
661 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
662 OperandTraits<BranchInst>::op_end(this) - 3,
673 BranchInst::BranchInst(const BranchInst &BI) :
674 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
675 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
676 BI.getNumOperands()) {
677 Op<-1>() = BI.Op<-1>();
678 if (BI.getNumOperands() != 1) {
679 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
680 Op<-3>() = BI.Op<-3>();
681 Op<-2>() = BI.Op<-2>();
683 SubclassOptionalData = BI.SubclassOptionalData;
687 Use* Use::getPrefix() {
688 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
689 if (PotentialPrefix.getOpaqueValue())
692 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
695 BranchInst::~BranchInst() {
696 if (NumOperands == 1) {
697 if (Use *Prefix = OperandList->getPrefix()) {
700 // mark OperandList to have a special value for scrutiny
701 // by baseclass destructors and operator delete
702 OperandList = Prefix;
705 OperandList = op_begin();
711 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
712 return getSuccessor(idx);
714 unsigned BranchInst::getNumSuccessorsV() const {
715 return getNumSuccessors();
717 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
718 setSuccessor(idx, B);
722 //===----------------------------------------------------------------------===//
723 // AllocationInst Implementation
724 //===----------------------------------------------------------------------===//
726 static Value *getAISize(LLVMContext &Context, Value *Amt) {
728 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
730 assert(!isa<BasicBlock>(Amt) &&
731 "Passed basic block into allocation size parameter! Use other ctor");
732 assert(Amt->getType() == Type::getInt32Ty(Context) &&
733 "Malloc/Allocation array size is not a 32-bit integer!");
738 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
739 unsigned Align, const Twine &Name,
740 Instruction *InsertBefore)
741 : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
742 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
744 assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!");
748 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
749 unsigned Align, const Twine &Name,
750 BasicBlock *InsertAtEnd)
751 : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
752 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
754 assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!");
758 // Out of line virtual method, so the vtable, etc has a home.
759 AllocationInst::~AllocationInst() {
762 void AllocationInst::setAlignment(unsigned Align) {
763 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
764 SubclassData = Log2_32(Align) + 1;
765 assert(getAlignment() == Align && "Alignment representation error!");
768 bool AllocationInst::isArrayAllocation() const {
769 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
770 return CI->getZExtValue() != 1;
774 const Type *AllocationInst::getAllocatedType() const {
775 return getType()->getElementType();
778 /// isStaticAlloca - Return true if this alloca is in the entry block of the
779 /// function and is a constant size. If so, the code generator will fold it
780 /// into the prolog/epilog code, so it is basically free.
781 bool AllocaInst::isStaticAlloca() const {
782 // Must be constant size.
783 if (!isa<ConstantInt>(getArraySize())) return false;
785 // Must be in the entry block.
786 const BasicBlock *Parent = getParent();
787 return Parent == &Parent->getParent()->front();
790 //===----------------------------------------------------------------------===//
791 // FreeInst Implementation
792 //===----------------------------------------------------------------------===//
794 void FreeInst::AssertOK() {
795 assert(isa<PointerType>(getOperand(0)->getType()) &&
796 "Can not free something of nonpointer type!");
799 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
800 : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
801 Free, Ptr, InsertBefore) {
805 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
806 : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
807 Free, Ptr, InsertAtEnd) {
812 //===----------------------------------------------------------------------===//
813 // LoadInst Implementation
814 //===----------------------------------------------------------------------===//
816 void LoadInst::AssertOK() {
817 assert(isa<PointerType>(getOperand(0)->getType()) &&
818 "Ptr must have pointer type.");
821 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
822 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
823 Load, Ptr, InsertBef) {
830 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
831 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
832 Load, Ptr, InsertAE) {
839 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
840 Instruction *InsertBef)
841 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
842 Load, Ptr, InsertBef) {
843 setVolatile(isVolatile);
849 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
850 unsigned Align, Instruction *InsertBef)
851 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
852 Load, Ptr, InsertBef) {
853 setVolatile(isVolatile);
859 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
860 unsigned Align, BasicBlock *InsertAE)
861 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
862 Load, Ptr, InsertAE) {
863 setVolatile(isVolatile);
869 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
870 BasicBlock *InsertAE)
871 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
872 Load, Ptr, InsertAE) {
873 setVolatile(isVolatile);
881 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
882 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
883 Load, Ptr, InsertBef) {
887 if (Name && Name[0]) setName(Name);
890 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
891 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
892 Load, Ptr, InsertAE) {
896 if (Name && Name[0]) setName(Name);
899 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
900 Instruction *InsertBef)
901 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
902 Load, Ptr, InsertBef) {
903 setVolatile(isVolatile);
906 if (Name && Name[0]) setName(Name);
909 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
910 BasicBlock *InsertAE)
911 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
912 Load, Ptr, InsertAE) {
913 setVolatile(isVolatile);
916 if (Name && Name[0]) setName(Name);
919 void LoadInst::setAlignment(unsigned Align) {
920 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
921 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
924 //===----------------------------------------------------------------------===//
925 // StoreInst Implementation
926 //===----------------------------------------------------------------------===//
928 void StoreInst::AssertOK() {
929 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
930 assert(isa<PointerType>(getOperand(1)->getType()) &&
931 "Ptr must have pointer type!");
932 assert(getOperand(0)->getType() ==
933 cast<PointerType>(getOperand(1)->getType())->getElementType()
934 && "Ptr must be a pointer to Val type!");
938 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
939 : Instruction(Type::getVoidTy(val->getContext()), Store,
940 OperandTraits<StoreInst>::op_begin(this),
941 OperandTraits<StoreInst>::operands(this),
950 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
951 : Instruction(Type::getVoidTy(val->getContext()), Store,
952 OperandTraits<StoreInst>::op_begin(this),
953 OperandTraits<StoreInst>::operands(this),
962 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
963 Instruction *InsertBefore)
964 : Instruction(Type::getVoidTy(val->getContext()), 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 unsigned Align, Instruction *InsertBefore)
977 : Instruction(Type::getVoidTy(val->getContext()), Store,
978 OperandTraits<StoreInst>::op_begin(this),
979 OperandTraits<StoreInst>::operands(this),
983 setVolatile(isVolatile);
988 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
989 unsigned Align, BasicBlock *InsertAtEnd)
990 : Instruction(Type::getVoidTy(val->getContext()), Store,
991 OperandTraits<StoreInst>::op_begin(this),
992 OperandTraits<StoreInst>::operands(this),
996 setVolatile(isVolatile);
1001 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1002 BasicBlock *InsertAtEnd)
1003 : Instruction(Type::getVoidTy(val->getContext()), Store,
1004 OperandTraits<StoreInst>::op_begin(this),
1005 OperandTraits<StoreInst>::operands(this),
1009 setVolatile(isVolatile);
1014 void StoreInst::setAlignment(unsigned Align) {
1015 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1016 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1019 //===----------------------------------------------------------------------===//
1020 // GetElementPtrInst Implementation
1021 //===----------------------------------------------------------------------===//
1023 static unsigned retrieveAddrSpace(const Value *Val) {
1024 return cast<PointerType>(Val->getType())->getAddressSpace();
1027 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1028 const Twine &Name) {
1029 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1030 Use *OL = OperandList;
1033 for (unsigned i = 0; i != NumIdx; ++i)
1039 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1040 assert(NumOperands == 2 && "NumOperands not initialized?");
1041 Use *OL = OperandList;
1048 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1049 : Instruction(GEPI.getType(), GetElementPtr,
1050 OperandTraits<GetElementPtrInst>::op_end(this)
1051 - GEPI.getNumOperands(),
1052 GEPI.getNumOperands()) {
1053 Use *OL = OperandList;
1054 Use *GEPIOL = GEPI.OperandList;
1055 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1057 SubclassOptionalData = GEPI.SubclassOptionalData;
1060 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1061 const Twine &Name, Instruction *InBe)
1062 : Instruction(PointerType::get(
1063 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1065 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1067 init(Ptr, Idx, Name);
1070 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1071 const Twine &Name, BasicBlock *IAE)
1072 : Instruction(PointerType::get(
1073 checkType(getIndexedType(Ptr->getType(),Idx)),
1074 retrieveAddrSpace(Ptr)),
1076 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1078 init(Ptr, Idx, Name);
1081 /// getIndexedType - Returns the type of the element that would be accessed with
1082 /// a gep instruction with the specified parameters.
1084 /// The Idxs pointer should point to a continuous piece of memory containing the
1085 /// indices, either as Value* or uint64_t.
1087 /// A null type is returned if the indices are invalid for the specified
1090 template <typename IndexTy>
1091 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1093 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1094 if (!PTy) return 0; // Type isn't a pointer type!
1095 const Type *Agg = PTy->getElementType();
1097 // Handle the special case of the empty set index set, which is always valid.
1101 // If there is at least one index, the top level type must be sized, otherwise
1102 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1103 // that contain opaque types) under the assumption that it will be resolved to
1104 // a sane type later.
1105 if (!Agg->isSized() && !Agg->isAbstract())
1108 unsigned CurIdx = 1;
1109 for (; CurIdx != NumIdx; ++CurIdx) {
1110 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1111 if (!CT || isa<PointerType>(CT)) return 0;
1112 IndexTy Index = Idxs[CurIdx];
1113 if (!CT->indexValid(Index)) return 0;
1114 Agg = CT->getTypeAtIndex(Index);
1116 // If the new type forwards to another type, then it is in the middle
1117 // of being refined to another type (and hence, may have dropped all
1118 // references to what it was using before). So, use the new forwarded
1120 if (const Type *Ty = Agg->getForwardedType())
1123 return CurIdx == NumIdx ? Agg : 0;
1126 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1129 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1132 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1133 uint64_t const *Idxs,
1135 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1138 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1139 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1140 if (!PTy) return 0; // Type isn't a pointer type!
1142 // Check the pointer index.
1143 if (!PTy->indexValid(Idx)) return 0;
1145 return PTy->getElementType();
1149 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1150 /// zeros. If so, the result pointer and the first operand have the same
1151 /// value, just potentially different types.
1152 bool GetElementPtrInst::hasAllZeroIndices() const {
1153 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1154 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1155 if (!CI->isZero()) return false;
1163 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1164 /// constant integers. If so, the result pointer and the first operand have
1165 /// a constant offset between them.
1166 bool GetElementPtrInst::hasAllConstantIndices() const {
1167 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1168 if (!isa<ConstantInt>(getOperand(i)))
1174 void GetElementPtrInst::setIsInBounds(bool B) {
1175 cast<GEPOperator>(this)->setIsInBounds(B);
1178 //===----------------------------------------------------------------------===//
1179 // ExtractElementInst Implementation
1180 //===----------------------------------------------------------------------===//
1182 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1184 Instruction *InsertBef)
1185 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1187 OperandTraits<ExtractElementInst>::op_begin(this),
1189 assert(isValidOperands(Val, Index) &&
1190 "Invalid extractelement instruction operands!");
1196 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1198 BasicBlock *InsertAE)
1199 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1201 OperandTraits<ExtractElementInst>::op_begin(this),
1203 assert(isValidOperands(Val, Index) &&
1204 "Invalid extractelement instruction operands!");
1212 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1213 if (!isa<VectorType>(Val->getType()) ||
1214 Index->getType() != Type::getInt32Ty(Val->getContext()))
1220 //===----------------------------------------------------------------------===//
1221 // InsertElementInst Implementation
1222 //===----------------------------------------------------------------------===//
1224 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1226 Instruction *InsertBef)
1227 : Instruction(Vec->getType(), InsertElement,
1228 OperandTraits<InsertElementInst>::op_begin(this),
1230 assert(isValidOperands(Vec, Elt, Index) &&
1231 "Invalid insertelement instruction operands!");
1238 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1240 BasicBlock *InsertAE)
1241 : Instruction(Vec->getType(), InsertElement,
1242 OperandTraits<InsertElementInst>::op_begin(this),
1244 assert(isValidOperands(Vec, Elt, Index) &&
1245 "Invalid insertelement instruction operands!");
1253 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1254 const Value *Index) {
1255 if (!isa<VectorType>(Vec->getType()))
1256 return false; // First operand of insertelement must be vector type.
1258 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1259 return false;// Second operand of insertelement must be vector element type.
1261 if (Index->getType() != Type::getInt32Ty(Vec->getContext()))
1262 return false; // Third operand of insertelement must be i32.
1267 //===----------------------------------------------------------------------===//
1268 // ShuffleVectorInst Implementation
1269 //===----------------------------------------------------------------------===//
1271 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1273 Instruction *InsertBefore)
1274 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1275 cast<VectorType>(Mask->getType())->getNumElements()),
1277 OperandTraits<ShuffleVectorInst>::op_begin(this),
1278 OperandTraits<ShuffleVectorInst>::operands(this),
1280 assert(isValidOperands(V1, V2, Mask) &&
1281 "Invalid shuffle vector instruction operands!");
1288 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1290 BasicBlock *InsertAtEnd)
1291 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1292 cast<VectorType>(Mask->getType())->getNumElements()),
1294 OperandTraits<ShuffleVectorInst>::op_begin(this),
1295 OperandTraits<ShuffleVectorInst>::operands(this),
1297 assert(isValidOperands(V1, V2, Mask) &&
1298 "Invalid shuffle vector instruction operands!");
1306 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1307 const Value *Mask) {
1308 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1311 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1312 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1313 MaskTy->getElementType() != Type::getInt32Ty(V1->getContext()))
1318 /// getMaskValue - Return the index from the shuffle mask for the specified
1319 /// output result. This is either -1 if the element is undef or a number less
1320 /// than 2*numelements.
1321 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1322 const Constant *Mask = cast<Constant>(getOperand(2));
1323 if (isa<UndefValue>(Mask)) return -1;
1324 if (isa<ConstantAggregateZero>(Mask)) return 0;
1325 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1326 assert(i < MaskCV->getNumOperands() && "Index out of range");
1328 if (isa<UndefValue>(MaskCV->getOperand(i)))
1330 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1333 //===----------------------------------------------------------------------===//
1334 // InsertValueInst Class
1335 //===----------------------------------------------------------------------===//
1337 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1338 unsigned NumIdx, const Twine &Name) {
1339 assert(NumOperands == 2 && "NumOperands not initialized?");
1343 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1347 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1348 const Twine &Name) {
1349 assert(NumOperands == 2 && "NumOperands not initialized?");
1353 Indices.push_back(Idx);
1357 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1358 : Instruction(IVI.getType(), InsertValue,
1359 OperandTraits<InsertValueInst>::op_begin(this), 2),
1360 Indices(IVI.Indices) {
1361 Op<0>() = IVI.getOperand(0);
1362 Op<1>() = IVI.getOperand(1);
1363 SubclassOptionalData = IVI.SubclassOptionalData;
1366 InsertValueInst::InsertValueInst(Value *Agg,
1370 Instruction *InsertBefore)
1371 : Instruction(Agg->getType(), InsertValue,
1372 OperandTraits<InsertValueInst>::op_begin(this),
1374 init(Agg, Val, Idx, Name);
1377 InsertValueInst::InsertValueInst(Value *Agg,
1381 BasicBlock *InsertAtEnd)
1382 : Instruction(Agg->getType(), InsertValue,
1383 OperandTraits<InsertValueInst>::op_begin(this),
1385 init(Agg, Val, Idx, Name);
1388 //===----------------------------------------------------------------------===//
1389 // ExtractValueInst Class
1390 //===----------------------------------------------------------------------===//
1392 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1393 const Twine &Name) {
1394 assert(NumOperands == 1 && "NumOperands not initialized?");
1396 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1400 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1401 assert(NumOperands == 1 && "NumOperands not initialized?");
1403 Indices.push_back(Idx);
1407 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1408 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1409 Indices(EVI.Indices) {
1410 SubclassOptionalData = EVI.SubclassOptionalData;
1413 // getIndexedType - Returns the type of the element that would be extracted
1414 // with an extractvalue instruction with the specified parameters.
1416 // A null type is returned if the indices are invalid for the specified
1419 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1420 const unsigned *Idxs,
1422 unsigned CurIdx = 0;
1423 for (; CurIdx != NumIdx; ++CurIdx) {
1424 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1425 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1426 unsigned Index = Idxs[CurIdx];
1427 if (!CT->indexValid(Index)) return 0;
1428 Agg = CT->getTypeAtIndex(Index);
1430 // If the new type forwards to another type, then it is in the middle
1431 // of being refined to another type (and hence, may have dropped all
1432 // references to what it was using before). So, use the new forwarded
1434 if (const Type *Ty = Agg->getForwardedType())
1437 return CurIdx == NumIdx ? Agg : 0;
1440 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1442 return getIndexedType(Agg, &Idx, 1);
1445 //===----------------------------------------------------------------------===//
1446 // BinaryOperator Class
1447 //===----------------------------------------------------------------------===//
1449 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1450 /// type is floating-point, to help provide compatibility with an older API.
1452 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1454 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1455 if (Ty->isFPOrFPVector()) {
1456 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1457 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1458 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1463 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1464 const Type *Ty, const Twine &Name,
1465 Instruction *InsertBefore)
1466 : Instruction(Ty, AdjustIType(iType, Ty),
1467 OperandTraits<BinaryOperator>::op_begin(this),
1468 OperandTraits<BinaryOperator>::operands(this),
1472 init(AdjustIType(iType, Ty));
1476 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1477 const Type *Ty, const Twine &Name,
1478 BasicBlock *InsertAtEnd)
1479 : Instruction(Ty, AdjustIType(iType, Ty),
1480 OperandTraits<BinaryOperator>::op_begin(this),
1481 OperandTraits<BinaryOperator>::operands(this),
1485 init(AdjustIType(iType, Ty));
1490 void BinaryOperator::init(BinaryOps iType) {
1491 Value *LHS = getOperand(0), *RHS = getOperand(1);
1492 LHS = LHS; RHS = RHS; // Silence warnings.
1493 assert(LHS->getType() == RHS->getType() &&
1494 "Binary operator operand types must match!");
1499 assert(getType() == LHS->getType() &&
1500 "Arithmetic operation should return same type as operands!");
1501 assert(getType()->isIntOrIntVector() &&
1502 "Tried to create an integer operation on a non-integer type!");
1504 case FAdd: case FSub:
1506 assert(getType() == LHS->getType() &&
1507 "Arithmetic operation should return same type as operands!");
1508 assert(getType()->isFPOrFPVector() &&
1509 "Tried to create a floating-point operation on a "
1510 "non-floating-point type!");
1514 assert(getType() == LHS->getType() &&
1515 "Arithmetic operation should return same type as operands!");
1516 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1517 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1518 "Incorrect operand type (not integer) for S/UDIV");
1521 assert(getType() == LHS->getType() &&
1522 "Arithmetic operation should return same type as operands!");
1523 assert(getType()->isFPOrFPVector() &&
1524 "Incorrect operand type (not floating point) for FDIV");
1528 assert(getType() == LHS->getType() &&
1529 "Arithmetic operation should return same type as operands!");
1530 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1531 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1532 "Incorrect operand type (not integer) for S/UREM");
1535 assert(getType() == LHS->getType() &&
1536 "Arithmetic operation should return same type as operands!");
1537 assert(getType()->isFPOrFPVector() &&
1538 "Incorrect operand type (not floating point) for FREM");
1543 assert(getType() == LHS->getType() &&
1544 "Shift operation should return same type as operands!");
1545 assert((getType()->isInteger() ||
1546 (isa<VectorType>(getType()) &&
1547 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1548 "Tried to create a shift operation on a non-integral type!");
1552 assert(getType() == LHS->getType() &&
1553 "Logical operation should return same type as operands!");
1554 assert((getType()->isInteger() ||
1555 (isa<VectorType>(getType()) &&
1556 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1557 "Tried to create a logical operation on a non-integral type!");
1565 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1567 Instruction *InsertBefore) {
1568 assert(S1->getType() == S2->getType() &&
1569 "Cannot create binary operator with two operands of differing type!");
1570 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1573 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1575 BasicBlock *InsertAtEnd) {
1576 BinaryOperator *Res = Create(Op, S1, S2, Name);
1577 InsertAtEnd->getInstList().push_back(Res);
1581 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1582 Instruction *InsertBefore) {
1583 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1584 return new BinaryOperator(Instruction::Sub,
1586 Op->getType(), Name, InsertBefore);
1589 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1590 BasicBlock *InsertAtEnd) {
1591 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1592 return new BinaryOperator(Instruction::Sub,
1594 Op->getType(), Name, InsertAtEnd);
1597 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1598 Instruction *InsertBefore) {
1599 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1600 return new BinaryOperator(Instruction::FSub,
1602 Op->getType(), Name, InsertBefore);
1605 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1606 BasicBlock *InsertAtEnd) {
1607 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1608 return new BinaryOperator(Instruction::FSub,
1610 Op->getType(), Name, InsertAtEnd);
1613 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1614 Instruction *InsertBefore) {
1616 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1617 C = Constant::getAllOnesValue(PTy->getElementType());
1618 C = ConstantVector::get(
1619 std::vector<Constant*>(PTy->getNumElements(), C));
1621 C = Constant::getAllOnesValue(Op->getType());
1624 return new BinaryOperator(Instruction::Xor, Op, C,
1625 Op->getType(), Name, InsertBefore);
1628 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1629 BasicBlock *InsertAtEnd) {
1631 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1632 // Create a vector of all ones values.
1633 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1634 AllOnes = ConstantVector::get(
1635 std::vector<Constant*>(PTy->getNumElements(), Elt));
1637 AllOnes = Constant::getAllOnesValue(Op->getType());
1640 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1641 Op->getType(), Name, InsertAtEnd);
1645 // isConstantAllOnes - Helper function for several functions below
1646 static inline bool isConstantAllOnes(const Value *V) {
1647 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1648 return CI->isAllOnesValue();
1649 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1650 return CV->isAllOnesValue();
1654 bool BinaryOperator::isNeg(const Value *V) {
1655 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1656 if (Bop->getOpcode() == Instruction::Sub)
1657 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1658 return C->isNegativeZeroValue();
1662 bool BinaryOperator::isFNeg(const Value *V) {
1663 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1664 if (Bop->getOpcode() == Instruction::FSub)
1665 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1666 return C->isNegativeZeroValue();
1670 bool BinaryOperator::isNot(const Value *V) {
1671 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1672 return (Bop->getOpcode() == Instruction::Xor &&
1673 (isConstantAllOnes(Bop->getOperand(1)) ||
1674 isConstantAllOnes(Bop->getOperand(0))));
1678 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1679 return cast<BinaryOperator>(BinOp)->getOperand(1);
1682 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1683 return getNegArgument(const_cast<Value*>(BinOp));
1686 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1687 return cast<BinaryOperator>(BinOp)->getOperand(1);
1690 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1691 return getFNegArgument(const_cast<Value*>(BinOp));
1694 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1695 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1696 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1697 Value *Op0 = BO->getOperand(0);
1698 Value *Op1 = BO->getOperand(1);
1699 if (isConstantAllOnes(Op0)) return Op1;
1701 assert(isConstantAllOnes(Op1));
1705 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1706 return getNotArgument(const_cast<Value*>(BinOp));
1710 // swapOperands - Exchange the two operands to this instruction. This
1711 // instruction is safe to use on any binary instruction and does not
1712 // modify the semantics of the instruction. If the instruction is
1713 // order dependent (SetLT f.e.) the opcode is changed.
1715 bool BinaryOperator::swapOperands() {
1716 if (!isCommutative())
1717 return true; // Can't commute operands
1718 Op<0>().swap(Op<1>());
1722 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1723 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1726 void BinaryOperator::setHasNoSignedWrap(bool b) {
1727 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1730 void BinaryOperator::setIsExact(bool b) {
1731 cast<SDivOperator>(this)->setIsExact(b);
1734 //===----------------------------------------------------------------------===//
1736 //===----------------------------------------------------------------------===//
1738 // Just determine if this cast only deals with integral->integral conversion.
1739 bool CastInst::isIntegerCast() const {
1740 switch (getOpcode()) {
1741 default: return false;
1742 case Instruction::ZExt:
1743 case Instruction::SExt:
1744 case Instruction::Trunc:
1746 case Instruction::BitCast:
1747 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1751 bool CastInst::isLosslessCast() const {
1752 // Only BitCast can be lossless, exit fast if we're not BitCast
1753 if (getOpcode() != Instruction::BitCast)
1756 // Identity cast is always lossless
1757 const Type* SrcTy = getOperand(0)->getType();
1758 const Type* DstTy = getType();
1762 // Pointer to pointer is always lossless.
1763 if (isa<PointerType>(SrcTy))
1764 return isa<PointerType>(DstTy);
1765 return false; // Other types have no identity values
1768 /// This function determines if the CastInst does not require any bits to be
1769 /// changed in order to effect the cast. Essentially, it identifies cases where
1770 /// no code gen is necessary for the cast, hence the name no-op cast. For
1771 /// example, the following are all no-op casts:
1772 /// # bitcast i32* %x to i8*
1773 /// # bitcast <2 x i32> %x to <4 x i16>
1774 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1775 /// @brief Determine if a cast is a no-op.
1776 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1777 switch (getOpcode()) {
1779 assert(!"Invalid CastOp");
1780 case Instruction::Trunc:
1781 case Instruction::ZExt:
1782 case Instruction::SExt:
1783 case Instruction::FPTrunc:
1784 case Instruction::FPExt:
1785 case Instruction::UIToFP:
1786 case Instruction::SIToFP:
1787 case Instruction::FPToUI:
1788 case Instruction::FPToSI:
1789 return false; // These always modify bits
1790 case Instruction::BitCast:
1791 return true; // BitCast never modifies bits.
1792 case Instruction::PtrToInt:
1793 return IntPtrTy->getScalarSizeInBits() ==
1794 getType()->getScalarSizeInBits();
1795 case Instruction::IntToPtr:
1796 return IntPtrTy->getScalarSizeInBits() ==
1797 getOperand(0)->getType()->getScalarSizeInBits();
1801 /// This function determines if a pair of casts can be eliminated and what
1802 /// opcode should be used in the elimination. This assumes that there are two
1803 /// instructions like this:
1804 /// * %F = firstOpcode SrcTy %x to MidTy
1805 /// * %S = secondOpcode MidTy %F to DstTy
1806 /// The function returns a resultOpcode so these two casts can be replaced with:
1807 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1808 /// If no such cast is permited, the function returns 0.
1809 unsigned CastInst::isEliminableCastPair(
1810 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1811 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1813 // Define the 144 possibilities for these two cast instructions. The values
1814 // in this matrix determine what to do in a given situation and select the
1815 // case in the switch below. The rows correspond to firstOp, the columns
1816 // correspond to secondOp. In looking at the table below, keep in mind
1817 // the following cast properties:
1819 // Size Compare Source Destination
1820 // Operator Src ? Size Type Sign Type Sign
1821 // -------- ------------ ------------------- ---------------------
1822 // TRUNC > Integer Any Integral Any
1823 // ZEXT < Integral Unsigned Integer Any
1824 // SEXT < Integral Signed Integer Any
1825 // FPTOUI n/a FloatPt n/a Integral Unsigned
1826 // FPTOSI n/a FloatPt n/a Integral Signed
1827 // UITOFP n/a Integral Unsigned FloatPt n/a
1828 // SITOFP n/a Integral Signed FloatPt n/a
1829 // FPTRUNC > FloatPt n/a FloatPt n/a
1830 // FPEXT < FloatPt n/a FloatPt n/a
1831 // PTRTOINT n/a Pointer n/a Integral Unsigned
1832 // INTTOPTR n/a Integral Unsigned Pointer n/a
1833 // BITCONVERT = FirstClass n/a FirstClass n/a
1835 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1836 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
1837 // into "fptoui double to i64", but this loses information about the range
1838 // of the produced value (we no longer know the top-part is all zeros).
1839 // Further this conversion is often much more expensive for typical hardware,
1840 // and causes issues when building libgcc. We disallow fptosi+sext for the
1842 const unsigned numCastOps =
1843 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1844 static const uint8_t CastResults[numCastOps][numCastOps] = {
1845 // T F F U S F F P I B -+
1846 // R Z S P P I I T P 2 N T |
1847 // U E E 2 2 2 2 R E I T C +- secondOp
1848 // N X X U S F F N X N 2 V |
1849 // C T T I I P P C T T P T -+
1850 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1851 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1852 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1853 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1854 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1855 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1856 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1857 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1858 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1859 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1860 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1861 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1864 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1865 [secondOp-Instruction::CastOpsBegin];
1868 // categorically disallowed
1871 // allowed, use first cast's opcode
1874 // allowed, use second cast's opcode
1877 // no-op cast in second op implies firstOp as long as the DestTy
1879 if (DstTy->isInteger())
1883 // no-op cast in second op implies firstOp as long as the DestTy
1884 // is floating point
1885 if (DstTy->isFloatingPoint())
1889 // no-op cast in first op implies secondOp as long as the SrcTy
1891 if (SrcTy->isInteger())
1895 // no-op cast in first op implies secondOp as long as the SrcTy
1896 // is a floating point
1897 if (SrcTy->isFloatingPoint())
1901 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1904 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1905 unsigned MidSize = MidTy->getScalarSizeInBits();
1906 if (MidSize >= PtrSize)
1907 return Instruction::BitCast;
1911 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1912 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1913 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1914 unsigned SrcSize = SrcTy->getScalarSizeInBits();
1915 unsigned DstSize = DstTy->getScalarSizeInBits();
1916 if (SrcSize == DstSize)
1917 return Instruction::BitCast;
1918 else if (SrcSize < DstSize)
1922 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1923 return Instruction::ZExt;
1925 // fpext followed by ftrunc is allowed if the bit size returned to is
1926 // the same as the original, in which case its just a bitcast
1928 return Instruction::BitCast;
1929 return 0; // If the types are not the same we can't eliminate it.
1931 // bitcast followed by ptrtoint is allowed as long as the bitcast
1932 // is a pointer to pointer cast.
1933 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1937 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1938 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1942 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1945 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1946 unsigned SrcSize = SrcTy->getScalarSizeInBits();
1947 unsigned DstSize = DstTy->getScalarSizeInBits();
1948 if (SrcSize <= PtrSize && SrcSize == DstSize)
1949 return Instruction::BitCast;
1953 // cast combination can't happen (error in input). This is for all cases
1954 // where the MidTy is not the same for the two cast instructions.
1955 assert(!"Invalid Cast Combination");
1958 assert(!"Error in CastResults table!!!");
1964 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1965 const Twine &Name, Instruction *InsertBefore) {
1966 // Construct and return the appropriate CastInst subclass
1968 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1969 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1970 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1971 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1972 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1973 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1974 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1975 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1976 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1977 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1978 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1979 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1981 assert(!"Invalid opcode provided");
1986 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1987 const Twine &Name, BasicBlock *InsertAtEnd) {
1988 // Construct and return the appropriate CastInst subclass
1990 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1991 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1992 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1993 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1994 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1995 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1996 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1997 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1998 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1999 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2000 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2001 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2003 assert(!"Invalid opcode provided");
2008 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2010 Instruction *InsertBefore) {
2011 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2012 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2013 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2016 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2018 BasicBlock *InsertAtEnd) {
2019 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2020 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2021 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2024 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2026 Instruction *InsertBefore) {
2027 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2028 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2029 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2032 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2034 BasicBlock *InsertAtEnd) {
2035 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2036 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2037 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2040 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2042 Instruction *InsertBefore) {
2043 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2044 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2045 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2048 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2050 BasicBlock *InsertAtEnd) {
2051 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2052 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2053 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2056 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2058 BasicBlock *InsertAtEnd) {
2059 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2060 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2063 if (Ty->isInteger())
2064 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2065 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2068 /// @brief Create a BitCast or a PtrToInt cast instruction
2069 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2071 Instruction *InsertBefore) {
2072 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2073 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2076 if (Ty->isInteger())
2077 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2078 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2081 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2082 bool isSigned, const Twine &Name,
2083 Instruction *InsertBefore) {
2084 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2085 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2086 unsigned DstBits = Ty->getScalarSizeInBits();
2087 Instruction::CastOps opcode =
2088 (SrcBits == DstBits ? Instruction::BitCast :
2089 (SrcBits > DstBits ? Instruction::Trunc :
2090 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2091 return Create(opcode, C, Ty, Name, InsertBefore);
2094 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2095 bool isSigned, const Twine &Name,
2096 BasicBlock *InsertAtEnd) {
2097 assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() &&
2099 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2100 unsigned DstBits = Ty->getScalarSizeInBits();
2101 Instruction::CastOps opcode =
2102 (SrcBits == DstBits ? Instruction::BitCast :
2103 (SrcBits > DstBits ? Instruction::Trunc :
2104 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2105 return Create(opcode, C, Ty, Name, InsertAtEnd);
2108 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2110 Instruction *InsertBefore) {
2111 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2113 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2114 unsigned DstBits = Ty->getScalarSizeInBits();
2115 Instruction::CastOps opcode =
2116 (SrcBits == DstBits ? Instruction::BitCast :
2117 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2118 return Create(opcode, C, Ty, Name, InsertBefore);
2121 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2123 BasicBlock *InsertAtEnd) {
2124 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2126 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2127 unsigned DstBits = Ty->getScalarSizeInBits();
2128 Instruction::CastOps opcode =
2129 (SrcBits == DstBits ? Instruction::BitCast :
2130 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2131 return Create(opcode, C, Ty, Name, InsertAtEnd);
2134 // Check whether it is valid to call getCastOpcode for these types.
2135 // This routine must be kept in sync with getCastOpcode.
2136 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2137 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2140 if (SrcTy == DestTy)
2143 // Get the bit sizes, we'll need these
2144 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2145 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2147 // Run through the possibilities ...
2148 if (DestTy->isInteger()) { // Casting to integral
2149 if (SrcTy->isInteger()) { // Casting from integral
2151 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2153 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2154 // Casting from vector
2155 return DestBits == PTy->getBitWidth();
2156 } else { // Casting from something else
2157 return isa<PointerType>(SrcTy);
2159 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2160 if (SrcTy->isInteger()) { // Casting from integral
2162 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2164 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2165 // Casting from vector
2166 return DestBits == PTy->getBitWidth();
2167 } else { // Casting from something else
2170 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2171 // Casting to vector
2172 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2173 // Casting from vector
2174 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2175 } else { // Casting from something else
2176 return DestPTy->getBitWidth() == SrcBits;
2178 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2179 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2181 } else if (SrcTy->isInteger()) { // Casting from integral
2183 } else { // Casting from something else
2186 } else { // Casting to something else
2191 // Provide a way to get a "cast" where the cast opcode is inferred from the
2192 // types and size of the operand. This, basically, is a parallel of the
2193 // logic in the castIsValid function below. This axiom should hold:
2194 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2195 // should not assert in castIsValid. In other words, this produces a "correct"
2196 // casting opcode for the arguments passed to it.
2197 // This routine must be kept in sync with isCastable.
2198 Instruction::CastOps
2199 CastInst::getCastOpcode(
2200 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2201 // Get the bit sizes, we'll need these
2202 const Type *SrcTy = Src->getType();
2203 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2204 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2206 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2207 "Only first class types are castable!");
2209 // Run through the possibilities ...
2210 if (DestTy->isInteger()) { // Casting to integral
2211 if (SrcTy->isInteger()) { // Casting from integral
2212 if (DestBits < SrcBits)
2213 return Trunc; // int -> smaller int
2214 else if (DestBits > SrcBits) { // its an extension
2216 return SExt; // signed -> SEXT
2218 return ZExt; // unsigned -> ZEXT
2220 return BitCast; // Same size, No-op cast
2222 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2224 return FPToSI; // FP -> sint
2226 return FPToUI; // FP -> uint
2227 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2228 assert(DestBits == PTy->getBitWidth() &&
2229 "Casting vector to integer of different width");
2231 return BitCast; // Same size, no-op cast
2233 assert(isa<PointerType>(SrcTy) &&
2234 "Casting from a value that is not first-class type");
2235 return PtrToInt; // ptr -> int
2237 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2238 if (SrcTy->isInteger()) { // Casting from integral
2240 return SIToFP; // sint -> FP
2242 return UIToFP; // uint -> FP
2243 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2244 if (DestBits < SrcBits) {
2245 return FPTrunc; // FP -> smaller FP
2246 } else if (DestBits > SrcBits) {
2247 return FPExt; // FP -> larger FP
2249 return BitCast; // same size, no-op cast
2251 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2252 assert(DestBits == PTy->getBitWidth() &&
2253 "Casting vector to floating point of different width");
2255 return BitCast; // same size, no-op cast
2257 llvm_unreachable("Casting pointer or non-first class to float");
2259 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2260 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2261 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2262 "Casting vector to vector of different widths");
2264 return BitCast; // vector -> vector
2265 } else if (DestPTy->getBitWidth() == SrcBits) {
2266 return BitCast; // float/int -> vector
2268 assert(!"Illegal cast to vector (wrong type or size)");
2270 } else if (isa<PointerType>(DestTy)) {
2271 if (isa<PointerType>(SrcTy)) {
2272 return BitCast; // ptr -> ptr
2273 } else if (SrcTy->isInteger()) {
2274 return IntToPtr; // int -> ptr
2276 assert(!"Casting pointer to other than pointer or int");
2279 assert(!"Casting to type that is not first-class");
2282 // If we fall through to here we probably hit an assertion cast above
2283 // and assertions are not turned on. Anything we return is an error, so
2284 // BitCast is as good a choice as any.
2288 //===----------------------------------------------------------------------===//
2289 // CastInst SubClass Constructors
2290 //===----------------------------------------------------------------------===//
2292 /// Check that the construction parameters for a CastInst are correct. This
2293 /// could be broken out into the separate constructors but it is useful to have
2294 /// it in one place and to eliminate the redundant code for getting the sizes
2295 /// of the types involved.
2297 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2299 // Check for type sanity on the arguments
2300 const Type *SrcTy = S->getType();
2301 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2304 // Get the size of the types in bits, we'll need this later
2305 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2306 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2308 // Switch on the opcode provided
2310 default: return false; // This is an input error
2311 case Instruction::Trunc:
2312 return SrcTy->isIntOrIntVector() &&
2313 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2314 case Instruction::ZExt:
2315 return SrcTy->isIntOrIntVector() &&
2316 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2317 case Instruction::SExt:
2318 return SrcTy->isIntOrIntVector() &&
2319 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2320 case Instruction::FPTrunc:
2321 return SrcTy->isFPOrFPVector() &&
2322 DstTy->isFPOrFPVector() &&
2323 SrcBitSize > DstBitSize;
2324 case Instruction::FPExt:
2325 return SrcTy->isFPOrFPVector() &&
2326 DstTy->isFPOrFPVector() &&
2327 SrcBitSize < DstBitSize;
2328 case Instruction::UIToFP:
2329 case Instruction::SIToFP:
2330 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2331 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2332 return SVTy->getElementType()->isIntOrIntVector() &&
2333 DVTy->getElementType()->isFPOrFPVector() &&
2334 SVTy->getNumElements() == DVTy->getNumElements();
2337 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2338 case Instruction::FPToUI:
2339 case Instruction::FPToSI:
2340 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2341 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2342 return SVTy->getElementType()->isFPOrFPVector() &&
2343 DVTy->getElementType()->isIntOrIntVector() &&
2344 SVTy->getNumElements() == DVTy->getNumElements();
2347 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2348 case Instruction::PtrToInt:
2349 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2350 case Instruction::IntToPtr:
2351 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2352 case Instruction::BitCast:
2353 // BitCast implies a no-op cast of type only. No bits change.
2354 // However, you can't cast pointers to anything but pointers.
2355 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2358 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2359 // these cases, the cast is okay if the source and destination bit widths
2361 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2365 TruncInst::TruncInst(
2366 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2367 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2368 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2371 TruncInst::TruncInst(
2372 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2373 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2374 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2378 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2379 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2380 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2384 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2385 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2386 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2389 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2390 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2391 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2395 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2396 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2397 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2400 FPTruncInst::FPTruncInst(
2401 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2402 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2403 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2406 FPTruncInst::FPTruncInst(
2407 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2408 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2409 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2412 FPExtInst::FPExtInst(
2413 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2414 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2415 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2418 FPExtInst::FPExtInst(
2419 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2420 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2421 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2424 UIToFPInst::UIToFPInst(
2425 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2426 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2427 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2430 UIToFPInst::UIToFPInst(
2431 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2432 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2433 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2436 SIToFPInst::SIToFPInst(
2437 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2438 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2439 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2442 SIToFPInst::SIToFPInst(
2443 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2444 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2445 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2448 FPToUIInst::FPToUIInst(
2449 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2450 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2451 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2454 FPToUIInst::FPToUIInst(
2455 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2456 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2457 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2460 FPToSIInst::FPToSIInst(
2461 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2462 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2463 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2466 FPToSIInst::FPToSIInst(
2467 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2468 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2469 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2472 PtrToIntInst::PtrToIntInst(
2473 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2474 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2475 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2478 PtrToIntInst::PtrToIntInst(
2479 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2480 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2481 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2484 IntToPtrInst::IntToPtrInst(
2485 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2486 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2487 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2490 IntToPtrInst::IntToPtrInst(
2491 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2492 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2493 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2496 BitCastInst::BitCastInst(
2497 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2498 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2499 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2502 BitCastInst::BitCastInst(
2503 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2504 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2505 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2508 //===----------------------------------------------------------------------===//
2510 //===----------------------------------------------------------------------===//
2512 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2513 Value *LHS, Value *RHS, const Twine &Name,
2514 Instruction *InsertBefore)
2515 : Instruction(ty, op,
2516 OperandTraits<CmpInst>::op_begin(this),
2517 OperandTraits<CmpInst>::operands(this),
2521 SubclassData = predicate;
2525 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2526 Value *LHS, Value *RHS, const Twine &Name,
2527 BasicBlock *InsertAtEnd)
2528 : Instruction(ty, op,
2529 OperandTraits<CmpInst>::op_begin(this),
2530 OperandTraits<CmpInst>::operands(this),
2534 SubclassData = predicate;
2539 CmpInst::Create(OtherOps Op, unsigned short predicate,
2540 Value *S1, Value *S2,
2541 const Twine &Name, Instruction *InsertBefore) {
2542 if (Op == Instruction::ICmp) {
2544 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2547 return new ICmpInst(CmpInst::Predicate(predicate),
2552 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2555 return new FCmpInst(CmpInst::Predicate(predicate),
2560 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2561 const Twine &Name, BasicBlock *InsertAtEnd) {
2562 if (Op == Instruction::ICmp) {
2563 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2566 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2570 void CmpInst::swapOperands() {
2571 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2574 cast<FCmpInst>(this)->swapOperands();
2577 bool CmpInst::isCommutative() {
2578 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2579 return IC->isCommutative();
2580 return cast<FCmpInst>(this)->isCommutative();
2583 bool CmpInst::isEquality() {
2584 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2585 return IC->isEquality();
2586 return cast<FCmpInst>(this)->isEquality();
2590 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2592 default: assert(!"Unknown cmp predicate!");
2593 case ICMP_EQ: return ICMP_NE;
2594 case ICMP_NE: return ICMP_EQ;
2595 case ICMP_UGT: return ICMP_ULE;
2596 case ICMP_ULT: return ICMP_UGE;
2597 case ICMP_UGE: return ICMP_ULT;
2598 case ICMP_ULE: return ICMP_UGT;
2599 case ICMP_SGT: return ICMP_SLE;
2600 case ICMP_SLT: return ICMP_SGE;
2601 case ICMP_SGE: return ICMP_SLT;
2602 case ICMP_SLE: return ICMP_SGT;
2604 case FCMP_OEQ: return FCMP_UNE;
2605 case FCMP_ONE: return FCMP_UEQ;
2606 case FCMP_OGT: return FCMP_ULE;
2607 case FCMP_OLT: return FCMP_UGE;
2608 case FCMP_OGE: return FCMP_ULT;
2609 case FCMP_OLE: return FCMP_UGT;
2610 case FCMP_UEQ: return FCMP_ONE;
2611 case FCMP_UNE: return FCMP_OEQ;
2612 case FCMP_UGT: return FCMP_OLE;
2613 case FCMP_ULT: return FCMP_OGE;
2614 case FCMP_UGE: return FCMP_OLT;
2615 case FCMP_ULE: return FCMP_OGT;
2616 case FCMP_ORD: return FCMP_UNO;
2617 case FCMP_UNO: return FCMP_ORD;
2618 case FCMP_TRUE: return FCMP_FALSE;
2619 case FCMP_FALSE: return FCMP_TRUE;
2623 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2625 default: assert(! "Unknown icmp predicate!");
2626 case ICMP_EQ: case ICMP_NE:
2627 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2629 case ICMP_UGT: return ICMP_SGT;
2630 case ICMP_ULT: return ICMP_SLT;
2631 case ICMP_UGE: return ICMP_SGE;
2632 case ICMP_ULE: return ICMP_SLE;
2636 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2638 default: assert(! "Unknown icmp predicate!");
2639 case ICMP_EQ: case ICMP_NE:
2640 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2642 case ICMP_SGT: return ICMP_UGT;
2643 case ICMP_SLT: return ICMP_ULT;
2644 case ICMP_SGE: return ICMP_UGE;
2645 case ICMP_SLE: return ICMP_ULE;
2649 bool ICmpInst::isSignedPredicate(Predicate pred) {
2651 default: assert(! "Unknown icmp predicate!");
2652 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2654 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2655 case ICMP_UGE: case ICMP_ULE:
2660 /// Initialize a set of values that all satisfy the condition with C.
2663 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2666 uint32_t BitWidth = C.getBitWidth();
2668 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2669 case ICmpInst::ICMP_EQ: Upper++; break;
2670 case ICmpInst::ICMP_NE: Lower++; break;
2671 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2672 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2673 case ICmpInst::ICMP_UGT:
2674 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2676 case ICmpInst::ICMP_SGT:
2677 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2679 case ICmpInst::ICMP_ULE:
2680 Lower = APInt::getMinValue(BitWidth); Upper++;
2682 case ICmpInst::ICMP_SLE:
2683 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2685 case ICmpInst::ICMP_UGE:
2686 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2688 case ICmpInst::ICMP_SGE:
2689 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2692 return ConstantRange(Lower, Upper);
2695 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2697 default: assert(!"Unknown cmp predicate!");
2698 case ICMP_EQ: case ICMP_NE:
2700 case ICMP_SGT: return ICMP_SLT;
2701 case ICMP_SLT: return ICMP_SGT;
2702 case ICMP_SGE: return ICMP_SLE;
2703 case ICMP_SLE: return ICMP_SGE;
2704 case ICMP_UGT: return ICMP_ULT;
2705 case ICMP_ULT: return ICMP_UGT;
2706 case ICMP_UGE: return ICMP_ULE;
2707 case ICMP_ULE: return ICMP_UGE;
2709 case FCMP_FALSE: case FCMP_TRUE:
2710 case FCMP_OEQ: case FCMP_ONE:
2711 case FCMP_UEQ: case FCMP_UNE:
2712 case FCMP_ORD: case FCMP_UNO:
2714 case FCMP_OGT: return FCMP_OLT;
2715 case FCMP_OLT: return FCMP_OGT;
2716 case FCMP_OGE: return FCMP_OLE;
2717 case FCMP_OLE: return FCMP_OGE;
2718 case FCMP_UGT: return FCMP_ULT;
2719 case FCMP_ULT: return FCMP_UGT;
2720 case FCMP_UGE: return FCMP_ULE;
2721 case FCMP_ULE: return FCMP_UGE;
2725 bool CmpInst::isUnsigned(unsigned short predicate) {
2726 switch (predicate) {
2727 default: return false;
2728 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2729 case ICmpInst::ICMP_UGE: return true;
2733 bool CmpInst::isSigned(unsigned short predicate){
2734 switch (predicate) {
2735 default: return false;
2736 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2737 case ICmpInst::ICMP_SGE: return true;
2741 bool CmpInst::isOrdered(unsigned short predicate) {
2742 switch (predicate) {
2743 default: return false;
2744 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2745 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2746 case FCmpInst::FCMP_ORD: return true;
2750 bool CmpInst::isUnordered(unsigned short predicate) {
2751 switch (predicate) {
2752 default: return false;
2753 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2754 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2755 case FCmpInst::FCMP_UNO: return true;
2759 //===----------------------------------------------------------------------===//
2760 // SwitchInst Implementation
2761 //===----------------------------------------------------------------------===//
2763 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2764 assert(Value && Default);
2765 ReservedSpace = 2+NumCases*2;
2767 OperandList = allocHungoffUses(ReservedSpace);
2769 OperandList[0] = Value;
2770 OperandList[1] = Default;
2773 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2774 /// switch on and a default destination. The number of additional cases can
2775 /// be specified here to make memory allocation more efficient. This
2776 /// constructor can also autoinsert before another instruction.
2777 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2778 Instruction *InsertBefore)
2779 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2780 0, 0, InsertBefore) {
2781 init(Value, Default, NumCases);
2784 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2785 /// switch on and a default destination. The number of additional cases can
2786 /// be specified here to make memory allocation more efficient. This
2787 /// constructor also autoinserts at the end of the specified BasicBlock.
2788 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2789 BasicBlock *InsertAtEnd)
2790 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2791 0, 0, InsertAtEnd) {
2792 init(Value, Default, NumCases);
2795 SwitchInst::SwitchInst(const SwitchInst &SI)
2796 : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch,
2797 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2798 Use *OL = OperandList, *InOL = SI.OperandList;
2799 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2801 OL[i+1] = InOL[i+1];
2803 SubclassOptionalData = SI.SubclassOptionalData;
2806 SwitchInst::~SwitchInst() {
2807 dropHungoffUses(OperandList);
2811 /// addCase - Add an entry to the switch instruction...
2813 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2814 unsigned OpNo = NumOperands;
2815 if (OpNo+2 > ReservedSpace)
2816 resizeOperands(0); // Get more space!
2817 // Initialize some new operands.
2818 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2819 NumOperands = OpNo+2;
2820 OperandList[OpNo] = OnVal;
2821 OperandList[OpNo+1] = Dest;
2824 /// removeCase - This method removes the specified successor from the switch
2825 /// instruction. Note that this cannot be used to remove the default
2826 /// destination (successor #0).
2828 void SwitchInst::removeCase(unsigned idx) {
2829 assert(idx != 0 && "Cannot remove the default case!");
2830 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2832 unsigned NumOps = getNumOperands();
2833 Use *OL = OperandList;
2835 // Move everything after this operand down.
2837 // FIXME: we could just swap with the end of the list, then erase. However,
2838 // client might not expect this to happen. The code as it is thrashes the
2839 // use/def lists, which is kinda lame.
2840 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2842 OL[i-2+1] = OL[i+1];
2845 // Nuke the last value.
2846 OL[NumOps-2].set(0);
2847 OL[NumOps-2+1].set(0);
2848 NumOperands = NumOps-2;
2851 /// resizeOperands - resize operands - This adjusts the length of the operands
2852 /// list according to the following behavior:
2853 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2854 /// of operation. This grows the number of ops by 3 times.
2855 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2856 /// 3. If NumOps == NumOperands, trim the reserved space.
2858 void SwitchInst::resizeOperands(unsigned NumOps) {
2859 unsigned e = getNumOperands();
2862 } else if (NumOps*2 > NumOperands) {
2863 // No resize needed.
2864 if (ReservedSpace >= NumOps) return;
2865 } else if (NumOps == NumOperands) {
2866 if (ReservedSpace == NumOps) return;
2871 ReservedSpace = NumOps;
2872 Use *NewOps = allocHungoffUses(NumOps);
2873 Use *OldOps = OperandList;
2874 for (unsigned i = 0; i != e; ++i) {
2875 NewOps[i] = OldOps[i];
2877 OperandList = NewOps;
2878 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2882 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2883 return getSuccessor(idx);
2885 unsigned SwitchInst::getNumSuccessorsV() const {
2886 return getNumSuccessors();
2888 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2889 setSuccessor(idx, B);
2892 // Define these methods here so vtables don't get emitted into every translation
2893 // unit that uses these classes.
2895 GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const {
2896 GetElementPtrInst *New = new(getNumOperands()) GetElementPtrInst(*this);
2897 New->SubclassOptionalData = SubclassOptionalData;
2901 BinaryOperator *BinaryOperator::clone(LLVMContext&) const {
2902 BinaryOperator *New = Create(getOpcode(), Op<0>(), Op<1>());
2903 New->SubclassOptionalData = SubclassOptionalData;
2907 FCmpInst* FCmpInst::clone(LLVMContext &Context) const {
2908 FCmpInst *New = new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2909 New->SubclassOptionalData = SubclassOptionalData;
2912 ICmpInst* ICmpInst::clone(LLVMContext &Context) const {
2913 ICmpInst *New = new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2914 New->SubclassOptionalData = SubclassOptionalData;
2918 ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const {
2919 ExtractValueInst *New = new ExtractValueInst(*this);
2920 New->SubclassOptionalData = SubclassOptionalData;
2923 InsertValueInst *InsertValueInst::clone(LLVMContext&) const {
2924 InsertValueInst *New = new InsertValueInst(*this);
2925 New->SubclassOptionalData = SubclassOptionalData;
2929 MallocInst *MallocInst::clone(LLVMContext&) const {
2930 MallocInst *New = new MallocInst(getAllocatedType(),
2931 (Value*)getOperand(0),
2933 New->SubclassOptionalData = SubclassOptionalData;
2937 AllocaInst *AllocaInst::clone(LLVMContext&) const {
2938 AllocaInst *New = new AllocaInst(getAllocatedType(),
2939 (Value*)getOperand(0),
2941 New->SubclassOptionalData = SubclassOptionalData;
2945 FreeInst *FreeInst::clone(LLVMContext&) const {
2946 FreeInst *New = new FreeInst(getOperand(0));
2947 New->SubclassOptionalData = SubclassOptionalData;
2951 LoadInst *LoadInst::clone(LLVMContext&) const {
2952 LoadInst *New = new LoadInst(getOperand(0),
2953 Twine(), isVolatile(),
2955 New->SubclassOptionalData = SubclassOptionalData;
2959 StoreInst *StoreInst::clone(LLVMContext&) const {
2960 StoreInst *New = new StoreInst(getOperand(0), getOperand(1),
2961 isVolatile(), getAlignment());
2962 New->SubclassOptionalData = SubclassOptionalData;
2966 TruncInst *TruncInst::clone(LLVMContext&) const {
2967 TruncInst *New = new TruncInst(getOperand(0), getType());
2968 New->SubclassOptionalData = SubclassOptionalData;
2972 ZExtInst *ZExtInst::clone(LLVMContext&) const {
2973 ZExtInst *New = new ZExtInst(getOperand(0), getType());
2974 New->SubclassOptionalData = SubclassOptionalData;
2978 SExtInst *SExtInst::clone(LLVMContext&) const {
2979 SExtInst *New = new SExtInst(getOperand(0), getType());
2980 New->SubclassOptionalData = SubclassOptionalData;
2984 FPTruncInst *FPTruncInst::clone(LLVMContext&) const {
2985 FPTruncInst *New = new FPTruncInst(getOperand(0), getType());
2986 New->SubclassOptionalData = SubclassOptionalData;
2990 FPExtInst *FPExtInst::clone(LLVMContext&) const {
2991 FPExtInst *New = new FPExtInst(getOperand(0), getType());
2992 New->SubclassOptionalData = SubclassOptionalData;
2996 UIToFPInst *UIToFPInst::clone(LLVMContext&) const {
2997 UIToFPInst *New = new UIToFPInst(getOperand(0), getType());
2998 New->SubclassOptionalData = SubclassOptionalData;
3002 SIToFPInst *SIToFPInst::clone(LLVMContext&) const {
3003 SIToFPInst *New = new SIToFPInst(getOperand(0), getType());
3004 New->SubclassOptionalData = SubclassOptionalData;
3008 FPToUIInst *FPToUIInst::clone(LLVMContext&) const {
3009 FPToUIInst *New = new FPToUIInst(getOperand(0), getType());
3010 New->SubclassOptionalData = SubclassOptionalData;
3014 FPToSIInst *FPToSIInst::clone(LLVMContext&) const {
3015 FPToSIInst *New = new FPToSIInst(getOperand(0), getType());
3016 New->SubclassOptionalData = SubclassOptionalData;
3020 PtrToIntInst *PtrToIntInst::clone(LLVMContext&) const {
3021 PtrToIntInst *New = new PtrToIntInst(getOperand(0), getType());
3022 New->SubclassOptionalData = SubclassOptionalData;
3026 IntToPtrInst *IntToPtrInst::clone(LLVMContext&) const {
3027 IntToPtrInst *New = new IntToPtrInst(getOperand(0), getType());
3028 New->SubclassOptionalData = SubclassOptionalData;
3032 BitCastInst *BitCastInst::clone(LLVMContext&) const {
3033 BitCastInst *New = new BitCastInst(getOperand(0), getType());
3034 New->SubclassOptionalData = SubclassOptionalData;
3038 CallInst *CallInst::clone(LLVMContext&) const {
3039 CallInst *New = new(getNumOperands()) CallInst(*this);
3040 New->SubclassOptionalData = SubclassOptionalData;
3044 SelectInst *SelectInst::clone(LLVMContext&) const {
3045 SelectInst *New = SelectInst::Create(getOperand(0),
3048 New->SubclassOptionalData = SubclassOptionalData;
3052 VAArgInst *VAArgInst::clone(LLVMContext&) const {
3053 VAArgInst *New = new VAArgInst(getOperand(0), getType());
3054 New->SubclassOptionalData = SubclassOptionalData;
3058 ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const {
3059 ExtractElementInst *New = ExtractElementInst::Create(getOperand(0),
3061 New->SubclassOptionalData = SubclassOptionalData;
3065 InsertElementInst *InsertElementInst::clone(LLVMContext&) const {
3066 InsertElementInst *New = InsertElementInst::Create(getOperand(0),
3069 New->SubclassOptionalData = SubclassOptionalData;
3073 ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const {
3074 ShuffleVectorInst *New = new ShuffleVectorInst(getOperand(0),
3077 New->SubclassOptionalData = SubclassOptionalData;
3081 PHINode *PHINode::clone(LLVMContext&) const {
3082 PHINode *New = new PHINode(*this);
3083 New->SubclassOptionalData = SubclassOptionalData;
3087 ReturnInst *ReturnInst::clone(LLVMContext&) const {
3088 ReturnInst *New = new(getNumOperands()) ReturnInst(*this);
3089 New->SubclassOptionalData = SubclassOptionalData;
3093 BranchInst *BranchInst::clone(LLVMContext&) const {
3094 unsigned Ops(getNumOperands());
3095 BranchInst *New = new(Ops, Ops == 1) BranchInst(*this);
3096 New->SubclassOptionalData = SubclassOptionalData;
3100 SwitchInst *SwitchInst::clone(LLVMContext&) const {
3101 SwitchInst *New = new SwitchInst(*this);
3102 New->SubclassOptionalData = SubclassOptionalData;
3106 InvokeInst *InvokeInst::clone(LLVMContext&) const {
3107 InvokeInst *New = new(getNumOperands()) InvokeInst(*this);
3108 New->SubclassOptionalData = SubclassOptionalData;
3112 UnwindInst *UnwindInst::clone(LLVMContext &C) const {
3113 UnwindInst *New = new UnwindInst(C);
3114 New->SubclassOptionalData = SubclassOptionalData;
3118 UnreachableInst *UnreachableInst::clone(LLVMContext &C) const {
3119 UnreachableInst *New = new UnreachableInst(C);
3120 New->SubclassOptionalData = SubclassOptionalData;