1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/ParameterAttributes.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
26 unsigned CallSite::getCallingConv() const {
27 if (CallInst *CI = dyn_cast<CallInst>(I))
28 return CI->getCallingConv();
30 return cast<InvokeInst>(I)->getCallingConv();
32 void CallSite::setCallingConv(unsigned CC) {
33 if (CallInst *CI = dyn_cast<CallInst>(I))
34 CI->setCallingConv(CC);
36 cast<InvokeInst>(I)->setCallingConv(CC);
38 const ParamAttrsList* CallSite::getParamAttrs() const {
39 if (CallInst *CI = dyn_cast<CallInst>(I))
40 return CI->getParamAttrs();
42 return cast<InvokeInst>(I)->getParamAttrs();
44 void CallSite::setParamAttrs(const ParamAttrsList *PAL) {
45 if (CallInst *CI = dyn_cast<CallInst>(I))
46 CI->setParamAttrs(PAL);
48 cast<InvokeInst>(I)->setParamAttrs(PAL);
50 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
51 if (CallInst *CI = dyn_cast<CallInst>(I))
52 return CI->paramHasAttr(i, attr);
54 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
56 bool CallSite::doesNotAccessMemory() const {
57 if (CallInst *CI = dyn_cast<CallInst>(I))
58 return CI->doesNotAccessMemory();
60 return cast<InvokeInst>(I)->doesNotAccessMemory();
62 bool CallSite::onlyReadsMemory() const {
63 if (CallInst *CI = dyn_cast<CallInst>(I))
64 return CI->onlyReadsMemory();
66 return cast<InvokeInst>(I)->onlyReadsMemory();
68 bool CallSite::isNoUnwind() const {
69 if (CallInst *CI = dyn_cast<CallInst>(I))
70 return CI->isNoUnwind();
72 return cast<InvokeInst>(I)->isNoUnwind();
77 //===----------------------------------------------------------------------===//
78 // TerminatorInst Class
79 //===----------------------------------------------------------------------===//
81 // Out of line virtual method, so the vtable, etc has a home.
82 TerminatorInst::~TerminatorInst() {
85 // Out of line virtual method, so the vtable, etc has a home.
86 UnaryInstruction::~UnaryInstruction() {
90 //===----------------------------------------------------------------------===//
92 //===----------------------------------------------------------------------===//
94 PHINode::PHINode(const PHINode &PN)
95 : Instruction(PN.getType(), Instruction::PHI,
96 new Use[PN.getNumOperands()], PN.getNumOperands()),
97 ReservedSpace(PN.getNumOperands()) {
98 Use *OL = OperandList;
99 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
100 OL[i].init(PN.getOperand(i), this);
101 OL[i+1].init(PN.getOperand(i+1), this);
105 PHINode::~PHINode() {
106 delete [] OperandList;
109 // removeIncomingValue - Remove an incoming value. This is useful if a
110 // predecessor basic block is deleted.
111 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
112 unsigned NumOps = getNumOperands();
113 Use *OL = OperandList;
114 assert(Idx*2 < NumOps && "BB not in PHI node!");
115 Value *Removed = OL[Idx*2];
117 // Move everything after this operand down.
119 // FIXME: we could just swap with the end of the list, then erase. However,
120 // client might not expect this to happen. The code as it is thrashes the
121 // use/def lists, which is kinda lame.
122 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
127 // Nuke the last value.
129 OL[NumOps-2+1].set(0);
130 NumOperands = NumOps-2;
132 // If the PHI node is dead, because it has zero entries, nuke it now.
133 if (NumOps == 2 && DeletePHIIfEmpty) {
134 // If anyone is using this PHI, make them use a dummy value instead...
135 replaceAllUsesWith(UndefValue::get(getType()));
141 /// resizeOperands - resize operands - This adjusts the length of the operands
142 /// list according to the following behavior:
143 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
144 /// of operation. This grows the number of ops by 1.5 times.
145 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
146 /// 3. If NumOps == NumOperands, trim the reserved space.
148 void PHINode::resizeOperands(unsigned NumOps) {
150 NumOps = (getNumOperands())*3/2;
151 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
152 } else if (NumOps*2 > NumOperands) {
154 if (ReservedSpace >= NumOps) return;
155 } else if (NumOps == NumOperands) {
156 if (ReservedSpace == NumOps) return;
161 ReservedSpace = NumOps;
162 Use *NewOps = new Use[NumOps];
163 Use *OldOps = OperandList;
164 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
165 NewOps[i].init(OldOps[i], this);
169 OperandList = NewOps;
172 /// hasConstantValue - If the specified PHI node always merges together the same
173 /// value, return the value, otherwise return null.
175 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
176 // If the PHI node only has one incoming value, eliminate the PHI node...
177 if (getNumIncomingValues() == 1)
178 if (getIncomingValue(0) != this) // not X = phi X
179 return getIncomingValue(0);
181 return UndefValue::get(getType()); // Self cycle is dead.
183 // Otherwise if all of the incoming values are the same for the PHI, replace
184 // the PHI node with the incoming value.
187 bool HasUndefInput = false;
188 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
189 if (isa<UndefValue>(getIncomingValue(i)))
190 HasUndefInput = true;
191 else if (getIncomingValue(i) != this) // Not the PHI node itself...
192 if (InVal && getIncomingValue(i) != InVal)
193 return 0; // Not the same, bail out.
195 InVal = getIncomingValue(i);
197 // The only case that could cause InVal to be null is if we have a PHI node
198 // that only has entries for itself. In this case, there is no entry into the
199 // loop, so kill the PHI.
201 if (InVal == 0) InVal = UndefValue::get(getType());
203 // If we have a PHI node like phi(X, undef, X), where X is defined by some
204 // instruction, we cannot always return X as the result of the PHI node. Only
205 // do this if X is not an instruction (thus it must dominate the PHI block),
206 // or if the client is prepared to deal with this possibility.
207 if (HasUndefInput && !AllowNonDominatingInstruction)
208 if (Instruction *IV = dyn_cast<Instruction>(InVal))
209 // If it's in the entry block, it dominates everything.
210 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
212 return 0; // Cannot guarantee that InVal dominates this PHINode.
214 // All of the incoming values are the same, return the value now.
219 //===----------------------------------------------------------------------===//
220 // CallInst Implementation
221 //===----------------------------------------------------------------------===//
223 CallInst::~CallInst() {
224 delete [] OperandList;
226 ParamAttrs->dropRef();
229 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
231 NumOperands = NumParams+1;
232 Use *OL = OperandList = new Use[NumParams+1];
233 OL[0].init(Func, this);
235 const FunctionType *FTy =
236 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
237 FTy = FTy; // silence warning.
239 assert((NumParams == FTy->getNumParams() ||
240 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
241 "Calling a function with bad signature!");
242 for (unsigned i = 0; i != NumParams; ++i) {
243 assert((i >= FTy->getNumParams() ||
244 FTy->getParamType(i) == Params[i]->getType()) &&
245 "Calling a function with a bad signature!");
246 OL[i+1].init(Params[i], this);
250 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
253 Use *OL = OperandList = new Use[3];
254 OL[0].init(Func, this);
255 OL[1].init(Actual1, this);
256 OL[2].init(Actual2, this);
258 const FunctionType *FTy =
259 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
260 FTy = FTy; // silence warning.
262 assert((FTy->getNumParams() == 2 ||
263 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
264 "Calling a function with bad signature");
265 assert((0 >= FTy->getNumParams() ||
266 FTy->getParamType(0) == Actual1->getType()) &&
267 "Calling a function with a bad signature!");
268 assert((1 >= FTy->getNumParams() ||
269 FTy->getParamType(1) == Actual2->getType()) &&
270 "Calling a function with a bad signature!");
273 void CallInst::init(Value *Func, Value *Actual) {
276 Use *OL = OperandList = new Use[2];
277 OL[0].init(Func, this);
278 OL[1].init(Actual, this);
280 const FunctionType *FTy =
281 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
282 FTy = FTy; // silence warning.
284 assert((FTy->getNumParams() == 1 ||
285 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
286 "Calling a function with bad signature");
287 assert((0 == FTy->getNumParams() ||
288 FTy->getParamType(0) == Actual->getType()) &&
289 "Calling a function with a bad signature!");
292 void CallInst::init(Value *Func) {
295 Use *OL = OperandList = new Use[1];
296 OL[0].init(Func, this);
298 const FunctionType *FTy =
299 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
300 FTy = FTy; // silence warning.
302 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
306 // Leave for llvm-gcc
307 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
308 const std::string &Name, BasicBlock *InsertAtEnd)
309 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
310 ->getElementType())->getReturnType(),
311 Instruction::Call, 0, 0, InsertAtEnd) {
312 init(Func, Args, NumArgs);
315 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
316 const std::string &Name, Instruction *InsertBefore)
317 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
318 ->getElementType())->getReturnType(),
319 Instruction::Call, 0, 0, InsertBefore) {
320 init(Func, Args, NumArgs);
324 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
325 const std::string &Name, Instruction *InsertBefore)
326 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
327 ->getElementType())->getReturnType(),
328 Instruction::Call, 0, 0, InsertBefore) {
329 init(Func, Actual1, Actual2);
333 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
334 const std::string &Name, BasicBlock *InsertAtEnd)
335 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
336 ->getElementType())->getReturnType(),
337 Instruction::Call, 0, 0, InsertAtEnd) {
338 init(Func, Actual1, Actual2);
342 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
343 Instruction *InsertBefore)
344 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
345 ->getElementType())->getReturnType(),
346 Instruction::Call, 0, 0, InsertBefore) {
351 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
352 BasicBlock *InsertAtEnd)
353 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
354 ->getElementType())->getReturnType(),
355 Instruction::Call, 0, 0, InsertAtEnd) {
359 CallInst::CallInst(Value *Func, const std::string &Name,
360 Instruction *InsertBefore)
361 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
362 ->getElementType())->getReturnType(),
363 Instruction::Call, 0, 0, InsertBefore) {
368 CallInst::CallInst(Value *Func, const std::string &Name,
369 BasicBlock *InsertAtEnd)
370 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
371 ->getElementType())->getReturnType(),
372 Instruction::Call, 0, 0, InsertAtEnd) {
377 CallInst::CallInst(const CallInst &CI)
378 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
379 CI.getNumOperands()),
381 setParamAttrs(CI.getParamAttrs());
382 SubclassData = CI.SubclassData;
383 Use *OL = OperandList;
384 Use *InOL = CI.OperandList;
385 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
386 OL[i].init(InOL[i], this);
389 void CallInst::setParamAttrs(const ParamAttrsList *newAttrs) {
390 if (ParamAttrs == newAttrs)
394 ParamAttrs->dropRef();
399 ParamAttrs = newAttrs;
402 bool CallInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
403 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
405 if (const Function *F = getCalledFunction())
406 return F->paramHasAttr(i, attr);
411 //===----------------------------------------------------------------------===//
412 // InvokeInst Implementation
413 //===----------------------------------------------------------------------===//
415 InvokeInst::~InvokeInst() {
416 delete [] OperandList;
418 ParamAttrs->dropRef();
421 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
422 Value* const *Args, unsigned NumArgs) {
424 NumOperands = 3+NumArgs;
425 Use *OL = OperandList = new Use[3+NumArgs];
426 OL[0].init(Fn, this);
427 OL[1].init(IfNormal, this);
428 OL[2].init(IfException, this);
429 const FunctionType *FTy =
430 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
431 FTy = FTy; // silence warning.
433 assert((NumArgs == FTy->getNumParams()) ||
434 (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
435 "Calling a function with bad signature");
437 for (unsigned i = 0, e = NumArgs; i != e; i++) {
438 assert((i >= FTy->getNumParams() ||
439 FTy->getParamType(i) == Args[i]->getType()) &&
440 "Invoking a function with a bad signature!");
442 OL[i+3].init(Args[i], this);
446 InvokeInst::InvokeInst(const InvokeInst &II)
447 : TerminatorInst(II.getType(), Instruction::Invoke,
448 new Use[II.getNumOperands()], II.getNumOperands()),
450 setParamAttrs(II.getParamAttrs());
451 SubclassData = II.SubclassData;
452 Use *OL = OperandList, *InOL = II.OperandList;
453 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
454 OL[i].init(InOL[i], this);
457 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
458 return getSuccessor(idx);
460 unsigned InvokeInst::getNumSuccessorsV() const {
461 return getNumSuccessors();
463 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
464 return setSuccessor(idx, B);
467 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
468 if (ParamAttrs == newAttrs)
472 ParamAttrs->dropRef();
477 ParamAttrs = newAttrs;
480 bool InvokeInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
481 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
483 if (const Function *F = getCalledFunction())
484 return F->paramHasAttr(i, attr);
489 //===----------------------------------------------------------------------===//
490 // ReturnInst Implementation
491 //===----------------------------------------------------------------------===//
493 ReturnInst::ReturnInst(const ReturnInst &RI)
494 : TerminatorInst(Type::VoidTy, Instruction::Ret,
495 &RetVal, RI.getNumOperands()) {
496 if (RI.getNumOperands())
497 RetVal.init(RI.RetVal, this);
500 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
501 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
504 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
505 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
508 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
509 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
514 void ReturnInst::init(Value *retVal) {
515 if (retVal && retVal->getType() != Type::VoidTy) {
516 assert(!isa<BasicBlock>(retVal) &&
517 "Cannot return basic block. Probably using the incorrect ctor");
519 RetVal.init(retVal, this);
523 unsigned ReturnInst::getNumSuccessorsV() const {
524 return getNumSuccessors();
527 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
528 // emit the vtable for the class in this translation unit.
529 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
530 assert(0 && "ReturnInst has no successors!");
533 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
534 assert(0 && "ReturnInst has no successors!");
540 //===----------------------------------------------------------------------===//
541 // UnwindInst Implementation
542 //===----------------------------------------------------------------------===//
544 UnwindInst::UnwindInst(Instruction *InsertBefore)
545 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
547 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
548 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
552 unsigned UnwindInst::getNumSuccessorsV() const {
553 return getNumSuccessors();
556 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
557 assert(0 && "UnwindInst has no successors!");
560 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
561 assert(0 && "UnwindInst has no successors!");
566 //===----------------------------------------------------------------------===//
567 // UnreachableInst Implementation
568 //===----------------------------------------------------------------------===//
570 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
571 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
573 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
574 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
577 unsigned UnreachableInst::getNumSuccessorsV() const {
578 return getNumSuccessors();
581 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
582 assert(0 && "UnwindInst has no successors!");
585 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
586 assert(0 && "UnwindInst has no successors!");
591 //===----------------------------------------------------------------------===//
592 // BranchInst Implementation
593 //===----------------------------------------------------------------------===//
595 void BranchInst::AssertOK() {
597 assert(getCondition()->getType() == Type::Int1Ty &&
598 "May only branch on boolean predicates!");
601 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
602 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
603 assert(IfTrue != 0 && "Branch destination may not be null!");
604 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
606 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
607 Instruction *InsertBefore)
608 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
609 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
610 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
611 Ops[2].init(Cond, this);
617 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
618 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
619 assert(IfTrue != 0 && "Branch destination may not be null!");
620 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
623 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
624 BasicBlock *InsertAtEnd)
625 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
626 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
627 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
628 Ops[2].init(Cond, this);
635 BranchInst::BranchInst(const BranchInst &BI) :
636 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
637 OperandList[0].init(BI.getOperand(0), this);
638 if (BI.getNumOperands() != 1) {
639 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
640 OperandList[1].init(BI.getOperand(1), this);
641 OperandList[2].init(BI.getOperand(2), this);
645 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
646 return getSuccessor(idx);
648 unsigned BranchInst::getNumSuccessorsV() const {
649 return getNumSuccessors();
651 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
652 setSuccessor(idx, B);
656 //===----------------------------------------------------------------------===//
657 // AllocationInst Implementation
658 //===----------------------------------------------------------------------===//
660 static Value *getAISize(Value *Amt) {
662 Amt = ConstantInt::get(Type::Int32Ty, 1);
664 assert(!isa<BasicBlock>(Amt) &&
665 "Passed basic block into allocation size parameter! Use other ctor");
666 assert(Amt->getType() == Type::Int32Ty &&
667 "Malloc/Allocation array size is not a 32-bit integer!");
672 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
673 unsigned Align, const std::string &Name,
674 Instruction *InsertBefore)
675 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
676 InsertBefore), Alignment(Align) {
677 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
678 assert(Ty != Type::VoidTy && "Cannot allocate void!");
682 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
683 unsigned Align, const std::string &Name,
684 BasicBlock *InsertAtEnd)
685 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
686 InsertAtEnd), Alignment(Align) {
687 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
688 assert(Ty != Type::VoidTy && "Cannot allocate void!");
692 // Out of line virtual method, so the vtable, etc has a home.
693 AllocationInst::~AllocationInst() {
696 bool AllocationInst::isArrayAllocation() const {
697 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
698 return CI->getZExtValue() != 1;
702 const Type *AllocationInst::getAllocatedType() const {
703 return getType()->getElementType();
706 AllocaInst::AllocaInst(const AllocaInst &AI)
707 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
708 Instruction::Alloca, AI.getAlignment()) {
711 MallocInst::MallocInst(const MallocInst &MI)
712 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
713 Instruction::Malloc, MI.getAlignment()) {
716 //===----------------------------------------------------------------------===//
717 // FreeInst Implementation
718 //===----------------------------------------------------------------------===//
720 void FreeInst::AssertOK() {
721 assert(isa<PointerType>(getOperand(0)->getType()) &&
722 "Can not free something of nonpointer type!");
725 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
726 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
730 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
731 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
736 //===----------------------------------------------------------------------===//
737 // LoadInst Implementation
738 //===----------------------------------------------------------------------===//
740 void LoadInst::AssertOK() {
741 assert(isa<PointerType>(getOperand(0)->getType()) &&
742 "Ptr must have pointer type.");
745 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
746 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
747 Load, Ptr, InsertBef) {
754 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
755 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
756 Load, Ptr, InsertAE) {
763 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
764 Instruction *InsertBef)
765 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
766 Load, Ptr, InsertBef) {
767 setVolatile(isVolatile);
773 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
774 unsigned Align, Instruction *InsertBef)
775 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
776 Load, Ptr, InsertBef) {
777 setVolatile(isVolatile);
783 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
784 unsigned Align, BasicBlock *InsertAE)
785 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
786 Load, Ptr, InsertAE) {
787 setVolatile(isVolatile);
793 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
794 BasicBlock *InsertAE)
795 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
796 Load, Ptr, InsertAE) {
797 setVolatile(isVolatile);
805 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
806 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
807 Load, Ptr, InsertBef) {
811 if (Name && Name[0]) setName(Name);
814 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
815 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
816 Load, Ptr, InsertAE) {
820 if (Name && Name[0]) setName(Name);
823 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
824 Instruction *InsertBef)
825 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
826 Load, Ptr, InsertBef) {
827 setVolatile(isVolatile);
830 if (Name && Name[0]) setName(Name);
833 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
834 BasicBlock *InsertAE)
835 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
836 Load, Ptr, InsertAE) {
837 setVolatile(isVolatile);
840 if (Name && Name[0]) setName(Name);
843 void LoadInst::setAlignment(unsigned Align) {
844 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
845 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
848 //===----------------------------------------------------------------------===//
849 // StoreInst Implementation
850 //===----------------------------------------------------------------------===//
852 void StoreInst::AssertOK() {
853 assert(isa<PointerType>(getOperand(1)->getType()) &&
854 "Ptr must have pointer type!");
855 assert(getOperand(0)->getType() ==
856 cast<PointerType>(getOperand(1)->getType())->getElementType()
857 && "Ptr must be a pointer to Val type!");
861 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
862 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
863 Ops[0].init(val, this);
864 Ops[1].init(addr, this);
870 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
871 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
872 Ops[0].init(val, this);
873 Ops[1].init(addr, this);
879 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
880 Instruction *InsertBefore)
881 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
882 Ops[0].init(val, this);
883 Ops[1].init(addr, this);
884 setVolatile(isVolatile);
889 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
890 unsigned Align, Instruction *InsertBefore)
891 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
892 Ops[0].init(val, this);
893 Ops[1].init(addr, this);
894 setVolatile(isVolatile);
899 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
900 unsigned Align, BasicBlock *InsertAtEnd)
901 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
902 Ops[0].init(val, this);
903 Ops[1].init(addr, this);
904 setVolatile(isVolatile);
909 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
910 BasicBlock *InsertAtEnd)
911 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
912 Ops[0].init(val, this);
913 Ops[1].init(addr, this);
914 setVolatile(isVolatile);
919 void StoreInst::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 // GetElementPtrInst Implementation
926 //===----------------------------------------------------------------------===//
928 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
929 NumOperands = 1+NumIdx;
930 Use *OL = OperandList = new Use[NumOperands];
931 OL[0].init(Ptr, this);
933 for (unsigned i = 0; i != NumIdx; ++i)
934 OL[i+1].init(Idx[i], this);
937 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
939 Use *OL = OperandList = new Use[2];
940 OL[0].init(Ptr, this);
941 OL[1].init(Idx, this);
944 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
945 const std::string &Name, Instruction *InBe)
946 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
947 cast<PointerType>(Ptr->getType())->getAddressSpace()),
948 GetElementPtr, 0, 0, InBe) {
953 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
954 const std::string &Name, BasicBlock *IAE)
955 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
956 cast<PointerType>(Ptr->getType())->getAddressSpace()),
957 GetElementPtr, 0, 0, IAE) {
962 GetElementPtrInst::~GetElementPtrInst() {
963 delete[] OperandList;
966 // getIndexedType - Returns the type of the element that would be loaded with
967 // a load instruction with the specified parameters.
969 // A null type is returned if the indices are invalid for the specified
972 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
975 bool AllowCompositeLeaf) {
976 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
978 // Handle the special case of the empty set index set...
980 if (AllowCompositeLeaf ||
981 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
982 return cast<PointerType>(Ptr)->getElementType();
987 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
988 if (NumIdx == CurIdx) {
989 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
990 return 0; // Can't load a whole structure or array!?!?
993 Value *Index = Idxs[CurIdx++];
994 if (isa<PointerType>(CT) && CurIdx != 1)
995 return 0; // Can only index into pointer types at the first index!
996 if (!CT->indexValid(Index)) return 0;
997 Ptr = CT->getTypeAtIndex(Index);
999 // If the new type forwards to another type, then it is in the middle
1000 // of being refined to another type (and hence, may have dropped all
1001 // references to what it was using before). So, use the new forwarded
1003 if (const Type * Ty = Ptr->getForwardedType()) {
1007 return CurIdx == NumIdx ? Ptr : 0;
1010 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1011 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1012 if (!PTy) return 0; // Type isn't a pointer type!
1014 // Check the pointer index.
1015 if (!PTy->indexValid(Idx)) return 0;
1017 return PTy->getElementType();
1021 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1022 /// zeros. If so, the result pointer and the first operand have the same
1023 /// value, just potentially different types.
1024 bool GetElementPtrInst::hasAllZeroIndices() const {
1025 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1026 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1027 if (!CI->isZero()) return false;
1035 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1036 /// constant integers. If so, the result pointer and the first operand have
1037 /// a constant offset between them.
1038 bool GetElementPtrInst::hasAllConstantIndices() const {
1039 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1040 if (!isa<ConstantInt>(getOperand(i)))
1047 //===----------------------------------------------------------------------===//
1048 // ExtractElementInst Implementation
1049 //===----------------------------------------------------------------------===//
1051 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1052 const std::string &Name,
1053 Instruction *InsertBef)
1054 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1055 ExtractElement, Ops, 2, InsertBef) {
1056 assert(isValidOperands(Val, Index) &&
1057 "Invalid extractelement instruction operands!");
1058 Ops[0].init(Val, this);
1059 Ops[1].init(Index, this);
1063 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1064 const std::string &Name,
1065 Instruction *InsertBef)
1066 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1067 ExtractElement, Ops, 2, InsertBef) {
1068 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1069 assert(isValidOperands(Val, Index) &&
1070 "Invalid extractelement instruction operands!");
1071 Ops[0].init(Val, this);
1072 Ops[1].init(Index, this);
1077 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1078 const std::string &Name,
1079 BasicBlock *InsertAE)
1080 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1081 ExtractElement, Ops, 2, InsertAE) {
1082 assert(isValidOperands(Val, Index) &&
1083 "Invalid extractelement instruction operands!");
1085 Ops[0].init(Val, this);
1086 Ops[1].init(Index, this);
1090 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1091 const std::string &Name,
1092 BasicBlock *InsertAE)
1093 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1094 ExtractElement, Ops, 2, InsertAE) {
1095 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1096 assert(isValidOperands(Val, Index) &&
1097 "Invalid extractelement instruction operands!");
1099 Ops[0].init(Val, this);
1100 Ops[1].init(Index, this);
1105 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1106 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1112 //===----------------------------------------------------------------------===//
1113 // InsertElementInst Implementation
1114 //===----------------------------------------------------------------------===//
1116 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1117 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1118 Ops[0].init(IE.Ops[0], this);
1119 Ops[1].init(IE.Ops[1], this);
1120 Ops[2].init(IE.Ops[2], this);
1122 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1123 const std::string &Name,
1124 Instruction *InsertBef)
1125 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1126 assert(isValidOperands(Vec, Elt, Index) &&
1127 "Invalid insertelement instruction operands!");
1128 Ops[0].init(Vec, this);
1129 Ops[1].init(Elt, this);
1130 Ops[2].init(Index, this);
1134 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1135 const std::string &Name,
1136 Instruction *InsertBef)
1137 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1138 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1139 assert(isValidOperands(Vec, Elt, Index) &&
1140 "Invalid insertelement instruction operands!");
1141 Ops[0].init(Vec, this);
1142 Ops[1].init(Elt, this);
1143 Ops[2].init(Index, this);
1148 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1149 const std::string &Name,
1150 BasicBlock *InsertAE)
1151 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1152 assert(isValidOperands(Vec, Elt, Index) &&
1153 "Invalid insertelement instruction operands!");
1155 Ops[0].init(Vec, this);
1156 Ops[1].init(Elt, this);
1157 Ops[2].init(Index, this);
1161 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1162 const std::string &Name,
1163 BasicBlock *InsertAE)
1164 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1165 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1166 assert(isValidOperands(Vec, Elt, Index) &&
1167 "Invalid insertelement instruction operands!");
1169 Ops[0].init(Vec, this);
1170 Ops[1].init(Elt, this);
1171 Ops[2].init(Index, this);
1175 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1176 const Value *Index) {
1177 if (!isa<VectorType>(Vec->getType()))
1178 return false; // First operand of insertelement must be vector type.
1180 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1181 return false;// Second operand of insertelement must be vector element type.
1183 if (Index->getType() != Type::Int32Ty)
1184 return false; // Third operand of insertelement must be uint.
1189 //===----------------------------------------------------------------------===//
1190 // ShuffleVectorInst Implementation
1191 //===----------------------------------------------------------------------===//
1193 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1194 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1195 Ops[0].init(SV.Ops[0], this);
1196 Ops[1].init(SV.Ops[1], this);
1197 Ops[2].init(SV.Ops[2], this);
1200 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1201 const std::string &Name,
1202 Instruction *InsertBefore)
1203 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1204 assert(isValidOperands(V1, V2, Mask) &&
1205 "Invalid shuffle vector instruction operands!");
1206 Ops[0].init(V1, this);
1207 Ops[1].init(V2, this);
1208 Ops[2].init(Mask, this);
1212 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1213 const std::string &Name,
1214 BasicBlock *InsertAtEnd)
1215 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1216 assert(isValidOperands(V1, V2, Mask) &&
1217 "Invalid shuffle vector instruction operands!");
1219 Ops[0].init(V1, this);
1220 Ops[1].init(V2, this);
1221 Ops[2].init(Mask, this);
1225 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1226 const Value *Mask) {
1227 if (!isa<VectorType>(V1->getType())) return false;
1228 if (V1->getType() != V2->getType()) return false;
1229 if (!isa<VectorType>(Mask->getType()) ||
1230 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1231 cast<VectorType>(Mask->getType())->getNumElements() !=
1232 cast<VectorType>(V1->getType())->getNumElements())
1238 //===----------------------------------------------------------------------===//
1239 // BinaryOperator Class
1240 //===----------------------------------------------------------------------===//
1242 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1243 const Type *Ty, const std::string &Name,
1244 Instruction *InsertBefore)
1245 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1246 Ops[0].init(S1, this);
1247 Ops[1].init(S2, this);
1252 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1253 const Type *Ty, const std::string &Name,
1254 BasicBlock *InsertAtEnd)
1255 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1256 Ops[0].init(S1, this);
1257 Ops[1].init(S2, this);
1263 void BinaryOperator::init(BinaryOps iType) {
1264 Value *LHS = getOperand(0), *RHS = getOperand(1);
1265 LHS = LHS; RHS = RHS; // Silence warnings.
1266 assert(LHS->getType() == RHS->getType() &&
1267 "Binary operator operand types must match!");
1272 assert(getType() == LHS->getType() &&
1273 "Arithmetic operation should return same type as operands!");
1274 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1275 isa<VectorType>(getType())) &&
1276 "Tried to create an arithmetic operation on a non-arithmetic type!");
1280 assert(getType() == LHS->getType() &&
1281 "Arithmetic operation should return same type as operands!");
1282 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1283 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1284 "Incorrect operand type (not integer) for S/UDIV");
1287 assert(getType() == LHS->getType() &&
1288 "Arithmetic operation should return same type as operands!");
1289 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1290 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1291 && "Incorrect operand type (not floating point) for FDIV");
1295 assert(getType() == LHS->getType() &&
1296 "Arithmetic operation should return same type as operands!");
1297 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1298 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1299 "Incorrect operand type (not integer) for S/UREM");
1302 assert(getType() == LHS->getType() &&
1303 "Arithmetic operation should return same type as operands!");
1304 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1305 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1306 && "Incorrect operand type (not floating point) for FREM");
1311 assert(getType() == LHS->getType() &&
1312 "Shift operation should return same type as operands!");
1313 assert(getType()->isInteger() &&
1314 "Shift operation requires integer operands");
1318 assert(getType() == LHS->getType() &&
1319 "Logical operation should return same type as operands!");
1320 assert((getType()->isInteger() ||
1321 (isa<VectorType>(getType()) &&
1322 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1323 "Tried to create a logical operation on a non-integral type!");
1331 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1332 const std::string &Name,
1333 Instruction *InsertBefore) {
1334 assert(S1->getType() == S2->getType() &&
1335 "Cannot create binary operator with two operands of differing type!");
1336 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1339 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1340 const std::string &Name,
1341 BasicBlock *InsertAtEnd) {
1342 BinaryOperator *Res = create(Op, S1, S2, Name);
1343 InsertAtEnd->getInstList().push_back(Res);
1347 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1348 Instruction *InsertBefore) {
1349 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1350 return new BinaryOperator(Instruction::Sub,
1352 Op->getType(), Name, InsertBefore);
1355 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1356 BasicBlock *InsertAtEnd) {
1357 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1358 return new BinaryOperator(Instruction::Sub,
1360 Op->getType(), Name, InsertAtEnd);
1363 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1364 Instruction *InsertBefore) {
1366 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1367 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1368 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1370 C = ConstantInt::getAllOnesValue(Op->getType());
1373 return new BinaryOperator(Instruction::Xor, Op, C,
1374 Op->getType(), Name, InsertBefore);
1377 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1378 BasicBlock *InsertAtEnd) {
1380 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1381 // Create a vector of all ones values.
1382 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1384 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1386 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1389 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1390 Op->getType(), Name, InsertAtEnd);
1394 // isConstantAllOnes - Helper function for several functions below
1395 static inline bool isConstantAllOnes(const Value *V) {
1396 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1397 return CI->isAllOnesValue();
1398 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1399 return CV->isAllOnesValue();
1403 bool BinaryOperator::isNeg(const Value *V) {
1404 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1405 if (Bop->getOpcode() == Instruction::Sub)
1406 return Bop->getOperand(0) ==
1407 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1411 bool BinaryOperator::isNot(const Value *V) {
1412 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1413 return (Bop->getOpcode() == Instruction::Xor &&
1414 (isConstantAllOnes(Bop->getOperand(1)) ||
1415 isConstantAllOnes(Bop->getOperand(0))));
1419 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1420 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1421 return cast<BinaryOperator>(BinOp)->getOperand(1);
1424 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1425 return getNegArgument(const_cast<Value*>(BinOp));
1428 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1429 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1430 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1431 Value *Op0 = BO->getOperand(0);
1432 Value *Op1 = BO->getOperand(1);
1433 if (isConstantAllOnes(Op0)) return Op1;
1435 assert(isConstantAllOnes(Op1));
1439 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1440 return getNotArgument(const_cast<Value*>(BinOp));
1444 // swapOperands - Exchange the two operands to this instruction. This
1445 // instruction is safe to use on any binary instruction and does not
1446 // modify the semantics of the instruction. If the instruction is
1447 // order dependent (SetLT f.e.) the opcode is changed.
1449 bool BinaryOperator::swapOperands() {
1450 if (!isCommutative())
1451 return true; // Can't commute operands
1452 std::swap(Ops[0], Ops[1]);
1456 //===----------------------------------------------------------------------===//
1458 //===----------------------------------------------------------------------===//
1460 // Just determine if this cast only deals with integral->integral conversion.
1461 bool CastInst::isIntegerCast() const {
1462 switch (getOpcode()) {
1463 default: return false;
1464 case Instruction::ZExt:
1465 case Instruction::SExt:
1466 case Instruction::Trunc:
1468 case Instruction::BitCast:
1469 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1473 bool CastInst::isLosslessCast() const {
1474 // Only BitCast can be lossless, exit fast if we're not BitCast
1475 if (getOpcode() != Instruction::BitCast)
1478 // Identity cast is always lossless
1479 const Type* SrcTy = getOperand(0)->getType();
1480 const Type* DstTy = getType();
1484 // Pointer to pointer is always lossless.
1485 if (isa<PointerType>(SrcTy))
1486 return isa<PointerType>(DstTy);
1487 return false; // Other types have no identity values
1490 /// This function determines if the CastInst does not require any bits to be
1491 /// changed in order to effect the cast. Essentially, it identifies cases where
1492 /// no code gen is necessary for the cast, hence the name no-op cast. For
1493 /// example, the following are all no-op casts:
1494 /// # bitcast uint %X, int
1495 /// # bitcast uint* %x, sbyte*
1496 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1497 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1498 /// @brief Determine if a cast is a no-op.
1499 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1500 switch (getOpcode()) {
1502 assert(!"Invalid CastOp");
1503 case Instruction::Trunc:
1504 case Instruction::ZExt:
1505 case Instruction::SExt:
1506 case Instruction::FPTrunc:
1507 case Instruction::FPExt:
1508 case Instruction::UIToFP:
1509 case Instruction::SIToFP:
1510 case Instruction::FPToUI:
1511 case Instruction::FPToSI:
1512 return false; // These always modify bits
1513 case Instruction::BitCast:
1514 return true; // BitCast never modifies bits.
1515 case Instruction::PtrToInt:
1516 return IntPtrTy->getPrimitiveSizeInBits() ==
1517 getType()->getPrimitiveSizeInBits();
1518 case Instruction::IntToPtr:
1519 return IntPtrTy->getPrimitiveSizeInBits() ==
1520 getOperand(0)->getType()->getPrimitiveSizeInBits();
1524 /// This function determines if a pair of casts can be eliminated and what
1525 /// opcode should be used in the elimination. This assumes that there are two
1526 /// instructions like this:
1527 /// * %F = firstOpcode SrcTy %x to MidTy
1528 /// * %S = secondOpcode MidTy %F to DstTy
1529 /// The function returns a resultOpcode so these two casts can be replaced with:
1530 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1531 /// If no such cast is permited, the function returns 0.
1532 unsigned CastInst::isEliminableCastPair(
1533 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1534 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1536 // Define the 144 possibilities for these two cast instructions. The values
1537 // in this matrix determine what to do in a given situation and select the
1538 // case in the switch below. The rows correspond to firstOp, the columns
1539 // correspond to secondOp. In looking at the table below, keep in mind
1540 // the following cast properties:
1542 // Size Compare Source Destination
1543 // Operator Src ? Size Type Sign Type Sign
1544 // -------- ------------ ------------------- ---------------------
1545 // TRUNC > Integer Any Integral Any
1546 // ZEXT < Integral Unsigned Integer Any
1547 // SEXT < Integral Signed Integer Any
1548 // FPTOUI n/a FloatPt n/a Integral Unsigned
1549 // FPTOSI n/a FloatPt n/a Integral Signed
1550 // UITOFP n/a Integral Unsigned FloatPt n/a
1551 // SITOFP n/a Integral Signed FloatPt n/a
1552 // FPTRUNC > FloatPt n/a FloatPt n/a
1553 // FPEXT < FloatPt n/a FloatPt n/a
1554 // PTRTOINT n/a Pointer n/a Integral Unsigned
1555 // INTTOPTR n/a Integral Unsigned Pointer n/a
1556 // BITCONVERT = FirstClass n/a FirstClass n/a
1558 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1559 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1560 // into "fptoui double to ulong", but this loses information about the range
1561 // of the produced value (we no longer know the top-part is all zeros).
1562 // Further this conversion is often much more expensive for typical hardware,
1563 // and causes issues when building libgcc. We disallow fptosi+sext for the
1565 const unsigned numCastOps =
1566 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1567 static const uint8_t CastResults[numCastOps][numCastOps] = {
1568 // T F F U S F F P I B -+
1569 // R Z S P P I I T P 2 N T |
1570 // U E E 2 2 2 2 R E I T C +- secondOp
1571 // N X X U S F F N X N 2 V |
1572 // C T T I I P P C T T P T -+
1573 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1574 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1575 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1576 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1577 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1578 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1579 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1580 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1581 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1582 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1583 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1584 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1587 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1588 [secondOp-Instruction::CastOpsBegin];
1591 // categorically disallowed
1594 // allowed, use first cast's opcode
1597 // allowed, use second cast's opcode
1600 // no-op cast in second op implies firstOp as long as the DestTy
1602 if (DstTy->isInteger())
1606 // no-op cast in second op implies firstOp as long as the DestTy
1607 // is floating point
1608 if (DstTy->isFloatingPoint())
1612 // no-op cast in first op implies secondOp as long as the SrcTy
1614 if (SrcTy->isInteger())
1618 // no-op cast in first op implies secondOp as long as the SrcTy
1619 // is a floating point
1620 if (SrcTy->isFloatingPoint())
1624 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1625 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1626 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1627 if (MidSize >= PtrSize)
1628 return Instruction::BitCast;
1632 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1633 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1634 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1635 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1636 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1637 if (SrcSize == DstSize)
1638 return Instruction::BitCast;
1639 else if (SrcSize < DstSize)
1643 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1644 return Instruction::ZExt;
1646 // fpext followed by ftrunc is allowed if the bit size returned to is
1647 // the same as the original, in which case its just a bitcast
1649 return Instruction::BitCast;
1650 return 0; // If the types are not the same we can't eliminate it.
1652 // bitcast followed by ptrtoint is allowed as long as the bitcast
1653 // is a pointer to pointer cast.
1654 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1658 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1659 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1663 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1664 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1665 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1666 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1667 if (SrcSize <= PtrSize && SrcSize == DstSize)
1668 return Instruction::BitCast;
1672 // cast combination can't happen (error in input). This is for all cases
1673 // where the MidTy is not the same for the two cast instructions.
1674 assert(!"Invalid Cast Combination");
1677 assert(!"Error in CastResults table!!!");
1683 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1684 const std::string &Name, Instruction *InsertBefore) {
1685 // Construct and return the appropriate CastInst subclass
1687 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1688 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1689 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1690 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1691 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1692 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1693 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1694 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1695 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1696 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1697 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1698 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1700 assert(!"Invalid opcode provided");
1705 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1706 const std::string &Name, BasicBlock *InsertAtEnd) {
1707 // Construct and return the appropriate CastInst subclass
1709 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1710 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1711 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1712 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1713 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1714 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1715 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1716 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1717 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1718 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1719 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1720 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1722 assert(!"Invalid opcode provided");
1727 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1728 const std::string &Name,
1729 Instruction *InsertBefore) {
1730 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1731 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1732 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1735 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1736 const std::string &Name,
1737 BasicBlock *InsertAtEnd) {
1738 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1739 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1740 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1743 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1744 const std::string &Name,
1745 Instruction *InsertBefore) {
1746 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1747 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1748 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1751 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1752 const std::string &Name,
1753 BasicBlock *InsertAtEnd) {
1754 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1755 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1756 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1759 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1760 const std::string &Name,
1761 Instruction *InsertBefore) {
1762 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1763 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1764 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1767 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1768 const std::string &Name,
1769 BasicBlock *InsertAtEnd) {
1770 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1771 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1772 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1775 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1776 const std::string &Name,
1777 BasicBlock *InsertAtEnd) {
1778 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1779 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1782 if (Ty->isInteger())
1783 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1784 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1787 /// @brief Create a BitCast or a PtrToInt cast instruction
1788 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1789 const std::string &Name,
1790 Instruction *InsertBefore) {
1791 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1792 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1795 if (Ty->isInteger())
1796 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1797 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1800 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1801 bool isSigned, const std::string &Name,
1802 Instruction *InsertBefore) {
1803 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1804 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1805 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1806 Instruction::CastOps opcode =
1807 (SrcBits == DstBits ? Instruction::BitCast :
1808 (SrcBits > DstBits ? Instruction::Trunc :
1809 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1810 return create(opcode, C, Ty, Name, InsertBefore);
1813 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1814 bool isSigned, const std::string &Name,
1815 BasicBlock *InsertAtEnd) {
1816 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1817 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1818 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1819 Instruction::CastOps opcode =
1820 (SrcBits == DstBits ? Instruction::BitCast :
1821 (SrcBits > DstBits ? Instruction::Trunc :
1822 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1823 return create(opcode, C, Ty, Name, InsertAtEnd);
1826 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1827 const std::string &Name,
1828 Instruction *InsertBefore) {
1829 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1831 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1832 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1833 Instruction::CastOps opcode =
1834 (SrcBits == DstBits ? Instruction::BitCast :
1835 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1836 return create(opcode, C, Ty, Name, InsertBefore);
1839 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1840 const std::string &Name,
1841 BasicBlock *InsertAtEnd) {
1842 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1844 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1845 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1846 Instruction::CastOps opcode =
1847 (SrcBits == DstBits ? Instruction::BitCast :
1848 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1849 return create(opcode, C, Ty, Name, InsertAtEnd);
1852 // Provide a way to get a "cast" where the cast opcode is inferred from the
1853 // types and size of the operand. This, basically, is a parallel of the
1854 // logic in the castIsValid function below. This axiom should hold:
1855 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1856 // should not assert in castIsValid. In other words, this produces a "correct"
1857 // casting opcode for the arguments passed to it.
1858 Instruction::CastOps
1859 CastInst::getCastOpcode(
1860 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1861 // Get the bit sizes, we'll need these
1862 const Type *SrcTy = Src->getType();
1863 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1864 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1866 // Run through the possibilities ...
1867 if (DestTy->isInteger()) { // Casting to integral
1868 if (SrcTy->isInteger()) { // Casting from integral
1869 if (DestBits < SrcBits)
1870 return Trunc; // int -> smaller int
1871 else if (DestBits > SrcBits) { // its an extension
1873 return SExt; // signed -> SEXT
1875 return ZExt; // unsigned -> ZEXT
1877 return BitCast; // Same size, No-op cast
1879 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1881 return FPToSI; // FP -> sint
1883 return FPToUI; // FP -> uint
1884 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1885 assert(DestBits == PTy->getBitWidth() &&
1886 "Casting vector to integer of different width");
1887 return BitCast; // Same size, no-op cast
1889 assert(isa<PointerType>(SrcTy) &&
1890 "Casting from a value that is not first-class type");
1891 return PtrToInt; // ptr -> int
1893 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1894 if (SrcTy->isInteger()) { // Casting from integral
1896 return SIToFP; // sint -> FP
1898 return UIToFP; // uint -> FP
1899 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1900 if (DestBits < SrcBits) {
1901 return FPTrunc; // FP -> smaller FP
1902 } else if (DestBits > SrcBits) {
1903 return FPExt; // FP -> larger FP
1905 return BitCast; // same size, no-op cast
1907 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1908 assert(DestBits == PTy->getBitWidth() &&
1909 "Casting vector to floating point of different width");
1910 return BitCast; // same size, no-op cast
1912 assert(0 && "Casting pointer or non-first class to float");
1914 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1915 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1916 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1917 "Casting vector to vector of different widths");
1918 return BitCast; // vector -> vector
1919 } else if (DestPTy->getBitWidth() == SrcBits) {
1920 return BitCast; // float/int -> vector
1922 assert(!"Illegal cast to vector (wrong type or size)");
1924 } else if (isa<PointerType>(DestTy)) {
1925 if (isa<PointerType>(SrcTy)) {
1926 return BitCast; // ptr -> ptr
1927 } else if (SrcTy->isInteger()) {
1928 return IntToPtr; // int -> ptr
1930 assert(!"Casting pointer to other than pointer or int");
1933 assert(!"Casting to type that is not first-class");
1936 // If we fall through to here we probably hit an assertion cast above
1937 // and assertions are not turned on. Anything we return is an error, so
1938 // BitCast is as good a choice as any.
1942 //===----------------------------------------------------------------------===//
1943 // CastInst SubClass Constructors
1944 //===----------------------------------------------------------------------===//
1946 /// Check that the construction parameters for a CastInst are correct. This
1947 /// could be broken out into the separate constructors but it is useful to have
1948 /// it in one place and to eliminate the redundant code for getting the sizes
1949 /// of the types involved.
1951 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1953 // Check for type sanity on the arguments
1954 const Type *SrcTy = S->getType();
1955 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1958 // Get the size of the types in bits, we'll need this later
1959 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1960 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1962 // Switch on the opcode provided
1964 default: return false; // This is an input error
1965 case Instruction::Trunc:
1966 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1967 case Instruction::ZExt:
1968 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1969 case Instruction::SExt:
1970 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1971 case Instruction::FPTrunc:
1972 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1973 SrcBitSize > DstBitSize;
1974 case Instruction::FPExt:
1975 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1976 SrcBitSize < DstBitSize;
1977 case Instruction::UIToFP:
1978 case Instruction::SIToFP:
1979 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
1980 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1981 return SVTy->getElementType()->isInteger() &&
1982 DVTy->getElementType()->isFloatingPoint() &&
1983 SVTy->getNumElements() == DVTy->getNumElements();
1986 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1987 case Instruction::FPToUI:
1988 case Instruction::FPToSI:
1989 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
1990 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1991 return SVTy->getElementType()->isFloatingPoint() &&
1992 DVTy->getElementType()->isInteger() &&
1993 SVTy->getNumElements() == DVTy->getNumElements();
1996 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1997 case Instruction::PtrToInt:
1998 return isa<PointerType>(SrcTy) && DstTy->isInteger();
1999 case Instruction::IntToPtr:
2000 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2001 case Instruction::BitCast:
2002 // BitCast implies a no-op cast of type only. No bits change.
2003 // However, you can't cast pointers to anything but pointers.
2004 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2007 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
2008 // these cases, the cast is okay if the source and destination bit widths
2010 return SrcBitSize == DstBitSize;
2014 TruncInst::TruncInst(
2015 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2016 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2017 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2020 TruncInst::TruncInst(
2021 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2022 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2023 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2027 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2028 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2029 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2033 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2034 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2035 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2038 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2039 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2040 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2044 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2045 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2046 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2049 FPTruncInst::FPTruncInst(
2050 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2051 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2052 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2055 FPTruncInst::FPTruncInst(
2056 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2057 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2058 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2061 FPExtInst::FPExtInst(
2062 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2063 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2064 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2067 FPExtInst::FPExtInst(
2068 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2069 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2070 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2073 UIToFPInst::UIToFPInst(
2074 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2075 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2076 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2079 UIToFPInst::UIToFPInst(
2080 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2081 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2082 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2085 SIToFPInst::SIToFPInst(
2086 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2087 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2088 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2091 SIToFPInst::SIToFPInst(
2092 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2093 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2094 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2097 FPToUIInst::FPToUIInst(
2098 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2099 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2100 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2103 FPToUIInst::FPToUIInst(
2104 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2105 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2106 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2109 FPToSIInst::FPToSIInst(
2110 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2111 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2112 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2115 FPToSIInst::FPToSIInst(
2116 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2117 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2118 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2121 PtrToIntInst::PtrToIntInst(
2122 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2123 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2124 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2127 PtrToIntInst::PtrToIntInst(
2128 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2129 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2130 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2133 IntToPtrInst::IntToPtrInst(
2134 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2135 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2136 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2139 IntToPtrInst::IntToPtrInst(
2140 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2141 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2142 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2145 BitCastInst::BitCastInst(
2146 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2147 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2148 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2151 BitCastInst::BitCastInst(
2152 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2153 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2154 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2157 //===----------------------------------------------------------------------===//
2159 //===----------------------------------------------------------------------===//
2161 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2162 const std::string &Name, Instruction *InsertBefore)
2163 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2164 Ops[0].init(LHS, this);
2165 Ops[1].init(RHS, this);
2166 SubclassData = predicate;
2168 if (op == Instruction::ICmp) {
2169 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2170 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2171 "Invalid ICmp predicate value");
2172 const Type* Op0Ty = getOperand(0)->getType();
2173 const Type* Op1Ty = getOperand(1)->getType();
2174 assert(Op0Ty == Op1Ty &&
2175 "Both operands to ICmp instruction are not of the same type!");
2176 // Check that the operands are the right type
2177 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2178 "Invalid operand types for ICmp instruction");
2181 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2182 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2183 "Invalid FCmp predicate value");
2184 const Type* Op0Ty = getOperand(0)->getType();
2185 const Type* Op1Ty = getOperand(1)->getType();
2186 assert(Op0Ty == Op1Ty &&
2187 "Both operands to FCmp instruction are not of the same type!");
2188 // Check that the operands are the right type
2189 assert(Op0Ty->isFloatingPoint() &&
2190 "Invalid operand types for FCmp instruction");
2193 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2194 const std::string &Name, BasicBlock *InsertAtEnd)
2195 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2196 Ops[0].init(LHS, this);
2197 Ops[1].init(RHS, this);
2198 SubclassData = predicate;
2200 if (op == Instruction::ICmp) {
2201 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2202 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2203 "Invalid ICmp predicate value");
2205 const Type* Op0Ty = getOperand(0)->getType();
2206 const Type* Op1Ty = getOperand(1)->getType();
2207 assert(Op0Ty == Op1Ty &&
2208 "Both operands to ICmp instruction are not of the same type!");
2209 // Check that the operands are the right type
2210 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2211 "Invalid operand types for ICmp instruction");
2214 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2215 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2216 "Invalid FCmp predicate value");
2217 const Type* Op0Ty = getOperand(0)->getType();
2218 const Type* Op1Ty = getOperand(1)->getType();
2219 assert(Op0Ty == Op1Ty &&
2220 "Both operands to FCmp instruction are not of the same type!");
2221 // Check that the operands are the right type
2222 assert(Op0Ty->isFloatingPoint() &&
2223 "Invalid operand types for FCmp instruction");
2227 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2228 const std::string &Name, Instruction *InsertBefore) {
2229 if (Op == Instruction::ICmp) {
2230 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2233 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2238 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2239 const std::string &Name, BasicBlock *InsertAtEnd) {
2240 if (Op == Instruction::ICmp) {
2241 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2244 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2248 void CmpInst::swapOperands() {
2249 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2252 cast<FCmpInst>(this)->swapOperands();
2255 bool CmpInst::isCommutative() {
2256 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2257 return IC->isCommutative();
2258 return cast<FCmpInst>(this)->isCommutative();
2261 bool CmpInst::isEquality() {
2262 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2263 return IC->isEquality();
2264 return cast<FCmpInst>(this)->isEquality();
2268 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2271 assert(!"Unknown icmp predicate!");
2272 case ICMP_EQ: return ICMP_NE;
2273 case ICMP_NE: return ICMP_EQ;
2274 case ICMP_UGT: return ICMP_ULE;
2275 case ICMP_ULT: return ICMP_UGE;
2276 case ICMP_UGE: return ICMP_ULT;
2277 case ICMP_ULE: return ICMP_UGT;
2278 case ICMP_SGT: return ICMP_SLE;
2279 case ICMP_SLT: return ICMP_SGE;
2280 case ICMP_SGE: return ICMP_SLT;
2281 case ICMP_SLE: return ICMP_SGT;
2285 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2287 default: assert(! "Unknown icmp predicate!");
2288 case ICMP_EQ: case ICMP_NE:
2290 case ICMP_SGT: return ICMP_SLT;
2291 case ICMP_SLT: return ICMP_SGT;
2292 case ICMP_SGE: return ICMP_SLE;
2293 case ICMP_SLE: return ICMP_SGE;
2294 case ICMP_UGT: return ICMP_ULT;
2295 case ICMP_ULT: return ICMP_UGT;
2296 case ICMP_UGE: return ICMP_ULE;
2297 case ICMP_ULE: return ICMP_UGE;
2301 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2303 default: assert(! "Unknown icmp predicate!");
2304 case ICMP_EQ: case ICMP_NE:
2305 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2307 case ICMP_UGT: return ICMP_SGT;
2308 case ICMP_ULT: return ICMP_SLT;
2309 case ICMP_UGE: return ICMP_SGE;
2310 case ICMP_ULE: return ICMP_SLE;
2314 bool ICmpInst::isSignedPredicate(Predicate pred) {
2316 default: assert(! "Unknown icmp predicate!");
2317 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2319 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2320 case ICMP_UGE: case ICMP_ULE:
2325 /// Initialize a set of values that all satisfy the condition with C.
2328 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2331 uint32_t BitWidth = C.getBitWidth();
2333 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2334 case ICmpInst::ICMP_EQ: Upper++; break;
2335 case ICmpInst::ICMP_NE: Lower++; break;
2336 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2337 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2338 case ICmpInst::ICMP_UGT:
2339 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2341 case ICmpInst::ICMP_SGT:
2342 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2344 case ICmpInst::ICMP_ULE:
2345 Lower = APInt::getMinValue(BitWidth); Upper++;
2347 case ICmpInst::ICMP_SLE:
2348 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2350 case ICmpInst::ICMP_UGE:
2351 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2353 case ICmpInst::ICMP_SGE:
2354 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2357 return ConstantRange(Lower, Upper);
2360 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2363 assert(!"Unknown icmp predicate!");
2364 case FCMP_OEQ: return FCMP_UNE;
2365 case FCMP_ONE: return FCMP_UEQ;
2366 case FCMP_OGT: return FCMP_ULE;
2367 case FCMP_OLT: return FCMP_UGE;
2368 case FCMP_OGE: return FCMP_ULT;
2369 case FCMP_OLE: return FCMP_UGT;
2370 case FCMP_UEQ: return FCMP_ONE;
2371 case FCMP_UNE: return FCMP_OEQ;
2372 case FCMP_UGT: return FCMP_OLE;
2373 case FCMP_ULT: return FCMP_OGE;
2374 case FCMP_UGE: return FCMP_OLT;
2375 case FCMP_ULE: return FCMP_OGT;
2376 case FCMP_ORD: return FCMP_UNO;
2377 case FCMP_UNO: return FCMP_ORD;
2378 case FCMP_TRUE: return FCMP_FALSE;
2379 case FCMP_FALSE: return FCMP_TRUE;
2383 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2385 default: assert(!"Unknown fcmp predicate!");
2386 case FCMP_FALSE: case FCMP_TRUE:
2387 case FCMP_OEQ: case FCMP_ONE:
2388 case FCMP_UEQ: case FCMP_UNE:
2389 case FCMP_ORD: case FCMP_UNO:
2391 case FCMP_OGT: return FCMP_OLT;
2392 case FCMP_OLT: return FCMP_OGT;
2393 case FCMP_OGE: return FCMP_OLE;
2394 case FCMP_OLE: return FCMP_OGE;
2395 case FCMP_UGT: return FCMP_ULT;
2396 case FCMP_ULT: return FCMP_UGT;
2397 case FCMP_UGE: return FCMP_ULE;
2398 case FCMP_ULE: return FCMP_UGE;
2402 bool CmpInst::isUnsigned(unsigned short predicate) {
2403 switch (predicate) {
2404 default: return false;
2405 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2406 case ICmpInst::ICMP_UGE: return true;
2410 bool CmpInst::isSigned(unsigned short predicate){
2411 switch (predicate) {
2412 default: return false;
2413 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2414 case ICmpInst::ICMP_SGE: return true;
2418 bool CmpInst::isOrdered(unsigned short predicate) {
2419 switch (predicate) {
2420 default: return false;
2421 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2422 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2423 case FCmpInst::FCMP_ORD: return true;
2427 bool CmpInst::isUnordered(unsigned short predicate) {
2428 switch (predicate) {
2429 default: return false;
2430 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2431 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2432 case FCmpInst::FCMP_UNO: return true;
2436 //===----------------------------------------------------------------------===//
2437 // SwitchInst Implementation
2438 //===----------------------------------------------------------------------===//
2440 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2441 assert(Value && Default);
2442 ReservedSpace = 2+NumCases*2;
2444 OperandList = new Use[ReservedSpace];
2446 OperandList[0].init(Value, this);
2447 OperandList[1].init(Default, this);
2450 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2451 /// switch on and a default destination. The number of additional cases can
2452 /// be specified here to make memory allocation more efficient. This
2453 /// constructor can also autoinsert before another instruction.
2454 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2455 Instruction *InsertBefore)
2456 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2457 init(Value, Default, NumCases);
2460 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2461 /// switch on and a default destination. The number of additional cases can
2462 /// be specified here to make memory allocation more efficient. This
2463 /// constructor also autoinserts at the end of the specified BasicBlock.
2464 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2465 BasicBlock *InsertAtEnd)
2466 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2467 init(Value, Default, NumCases);
2470 SwitchInst::SwitchInst(const SwitchInst &SI)
2471 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2472 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2473 Use *OL = OperandList, *InOL = SI.OperandList;
2474 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2475 OL[i].init(InOL[i], this);
2476 OL[i+1].init(InOL[i+1], this);
2480 SwitchInst::~SwitchInst() {
2481 delete [] OperandList;
2485 /// addCase - Add an entry to the switch instruction...
2487 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2488 unsigned OpNo = NumOperands;
2489 if (OpNo+2 > ReservedSpace)
2490 resizeOperands(0); // Get more space!
2491 // Initialize some new operands.
2492 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2493 NumOperands = OpNo+2;
2494 OperandList[OpNo].init(OnVal, this);
2495 OperandList[OpNo+1].init(Dest, this);
2498 /// removeCase - This method removes the specified successor from the switch
2499 /// instruction. Note that this cannot be used to remove the default
2500 /// destination (successor #0).
2502 void SwitchInst::removeCase(unsigned idx) {
2503 assert(idx != 0 && "Cannot remove the default case!");
2504 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2506 unsigned NumOps = getNumOperands();
2507 Use *OL = OperandList;
2509 // Move everything after this operand down.
2511 // FIXME: we could just swap with the end of the list, then erase. However,
2512 // client might not expect this to happen. The code as it is thrashes the
2513 // use/def lists, which is kinda lame.
2514 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2516 OL[i-2+1] = OL[i+1];
2519 // Nuke the last value.
2520 OL[NumOps-2].set(0);
2521 OL[NumOps-2+1].set(0);
2522 NumOperands = NumOps-2;
2525 /// resizeOperands - resize operands - This adjusts the length of the operands
2526 /// list according to the following behavior:
2527 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2528 /// of operation. This grows the number of ops by 1.5 times.
2529 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2530 /// 3. If NumOps == NumOperands, trim the reserved space.
2532 void SwitchInst::resizeOperands(unsigned NumOps) {
2534 NumOps = getNumOperands()/2*6;
2535 } else if (NumOps*2 > NumOperands) {
2536 // No resize needed.
2537 if (ReservedSpace >= NumOps) return;
2538 } else if (NumOps == NumOperands) {
2539 if (ReservedSpace == NumOps) return;
2544 ReservedSpace = NumOps;
2545 Use *NewOps = new Use[NumOps];
2546 Use *OldOps = OperandList;
2547 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2548 NewOps[i].init(OldOps[i], this);
2552 OperandList = NewOps;
2556 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2557 return getSuccessor(idx);
2559 unsigned SwitchInst::getNumSuccessorsV() const {
2560 return getNumSuccessors();
2562 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2563 setSuccessor(idx, B);
2567 // Define these methods here so vtables don't get emitted into every translation
2568 // unit that uses these classes.
2570 GetElementPtrInst *GetElementPtrInst::clone() const {
2571 return new GetElementPtrInst(*this);
2574 BinaryOperator *BinaryOperator::clone() const {
2575 return create(getOpcode(), Ops[0], Ops[1]);
2578 FCmpInst* FCmpInst::clone() const {
2579 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2581 ICmpInst* ICmpInst::clone() const {
2582 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2585 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2586 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2587 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2588 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2589 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2590 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2591 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2592 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2593 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2594 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2595 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2596 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2597 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2598 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2599 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2600 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2601 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2602 CallInst *CallInst::clone() const { return new CallInst(*this); }
2603 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2604 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2606 ExtractElementInst *ExtractElementInst::clone() const {
2607 return new ExtractElementInst(*this);
2609 InsertElementInst *InsertElementInst::clone() const {
2610 return new InsertElementInst(*this);
2612 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2613 return new ShuffleVectorInst(*this);
2615 PHINode *PHINode::clone() const { return new PHINode(*this); }
2616 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2617 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2618 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2619 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2620 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2621 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}