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);
42 //===----------------------------------------------------------------------===//
43 // TerminatorInst Class
44 //===----------------------------------------------------------------------===//
46 // Out of line virtual method, so the vtable, etc has a home.
47 TerminatorInst::~TerminatorInst() {
50 // Out of line virtual method, so the vtable, etc has a home.
51 UnaryInstruction::~UnaryInstruction() {
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 PHINode::PHINode(const PHINode &PN)
60 : Instruction(PN.getType(), Instruction::PHI,
61 new Use[PN.getNumOperands()], PN.getNumOperands()),
62 ReservedSpace(PN.getNumOperands()) {
63 Use *OL = OperandList;
64 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
65 OL[i].init(PN.getOperand(i), this);
66 OL[i+1].init(PN.getOperand(i+1), this);
71 delete [] OperandList;
74 // removeIncomingValue - Remove an incoming value. This is useful if a
75 // predecessor basic block is deleted.
76 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
77 unsigned NumOps = getNumOperands();
78 Use *OL = OperandList;
79 assert(Idx*2 < NumOps && "BB not in PHI node!");
80 Value *Removed = OL[Idx*2];
82 // Move everything after this operand down.
84 // FIXME: we could just swap with the end of the list, then erase. However,
85 // client might not expect this to happen. The code as it is thrashes the
86 // use/def lists, which is kinda lame.
87 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
92 // Nuke the last value.
94 OL[NumOps-2+1].set(0);
95 NumOperands = NumOps-2;
97 // If the PHI node is dead, because it has zero entries, nuke it now.
98 if (NumOps == 2 && DeletePHIIfEmpty) {
99 // If anyone is using this PHI, make them use a dummy value instead...
100 replaceAllUsesWith(UndefValue::get(getType()));
106 /// resizeOperands - resize operands - This adjusts the length of the operands
107 /// list according to the following behavior:
108 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
109 /// of operation. This grows the number of ops by 1.5 times.
110 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
111 /// 3. If NumOps == NumOperands, trim the reserved space.
113 void PHINode::resizeOperands(unsigned NumOps) {
115 NumOps = (getNumOperands())*3/2;
116 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
117 } else if (NumOps*2 > NumOperands) {
119 if (ReservedSpace >= NumOps) return;
120 } else if (NumOps == NumOperands) {
121 if (ReservedSpace == NumOps) return;
126 ReservedSpace = NumOps;
127 Use *NewOps = new Use[NumOps];
128 Use *OldOps = OperandList;
129 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
130 NewOps[i].init(OldOps[i], this);
134 OperandList = NewOps;
137 /// hasConstantValue - If the specified PHI node always merges together the same
138 /// value, return the value, otherwise return null.
140 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
141 // If the PHI node only has one incoming value, eliminate the PHI node...
142 if (getNumIncomingValues() == 1)
143 if (getIncomingValue(0) != this) // not X = phi X
144 return getIncomingValue(0);
146 return UndefValue::get(getType()); // Self cycle is dead.
148 // Otherwise if all of the incoming values are the same for the PHI, replace
149 // the PHI node with the incoming value.
152 bool HasUndefInput = false;
153 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
154 if (isa<UndefValue>(getIncomingValue(i)))
155 HasUndefInput = true;
156 else if (getIncomingValue(i) != this) // Not the PHI node itself...
157 if (InVal && getIncomingValue(i) != InVal)
158 return 0; // Not the same, bail out.
160 InVal = getIncomingValue(i);
162 // The only case that could cause InVal to be null is if we have a PHI node
163 // that only has entries for itself. In this case, there is no entry into the
164 // loop, so kill the PHI.
166 if (InVal == 0) InVal = UndefValue::get(getType());
168 // If we have a PHI node like phi(X, undef, X), where X is defined by some
169 // instruction, we cannot always return X as the result of the PHI node. Only
170 // do this if X is not an instruction (thus it must dominate the PHI block),
171 // or if the client is prepared to deal with this possibility.
172 if (HasUndefInput && !AllowNonDominatingInstruction)
173 if (Instruction *IV = dyn_cast<Instruction>(InVal))
174 // If it's in the entry block, it dominates everything.
175 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
177 return 0; // Cannot guarantee that InVal dominates this PHINode.
179 // All of the incoming values are the same, return the value now.
184 //===----------------------------------------------------------------------===//
185 // CallInst Implementation
186 //===----------------------------------------------------------------------===//
188 CallInst::~CallInst() {
189 delete [] OperandList;
191 ParamAttrs->dropRef();
194 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
196 NumOperands = NumParams+1;
197 Use *OL = OperandList = new Use[NumParams+1];
198 OL[0].init(Func, this);
200 const FunctionType *FTy =
201 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
202 FTy = FTy; // silence warning.
204 assert((NumParams == FTy->getNumParams() ||
205 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
206 "Calling a function with bad signature!");
207 for (unsigned i = 0; i != NumParams; ++i) {
208 assert((i >= FTy->getNumParams() ||
209 FTy->getParamType(i) == Params[i]->getType()) &&
210 "Calling a function with a bad signature!");
211 OL[i+1].init(Params[i], this);
215 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
218 Use *OL = OperandList = new Use[3];
219 OL[0].init(Func, this);
220 OL[1].init(Actual1, this);
221 OL[2].init(Actual2, this);
223 const FunctionType *FTy =
224 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
225 FTy = FTy; // silence warning.
227 assert((FTy->getNumParams() == 2 ||
228 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
229 "Calling a function with bad signature");
230 assert((0 >= FTy->getNumParams() ||
231 FTy->getParamType(0) == Actual1->getType()) &&
232 "Calling a function with a bad signature!");
233 assert((1 >= FTy->getNumParams() ||
234 FTy->getParamType(1) == Actual2->getType()) &&
235 "Calling a function with a bad signature!");
238 void CallInst::init(Value *Func, Value *Actual) {
241 Use *OL = OperandList = new Use[2];
242 OL[0].init(Func, this);
243 OL[1].init(Actual, this);
245 const FunctionType *FTy =
246 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
247 FTy = FTy; // silence warning.
249 assert((FTy->getNumParams() == 1 ||
250 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
251 "Calling a function with bad signature");
252 assert((0 == FTy->getNumParams() ||
253 FTy->getParamType(0) == Actual->getType()) &&
254 "Calling a function with a bad signature!");
257 void CallInst::init(Value *Func) {
260 Use *OL = OperandList = new Use[1];
261 OL[0].init(Func, this);
263 const FunctionType *FTy =
264 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
265 FTy = FTy; // silence warning.
267 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
271 // Leave for llvm-gcc
272 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
273 const std::string &Name, BasicBlock *InsertAtEnd)
274 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
275 ->getElementType())->getReturnType(),
276 Instruction::Call, 0, 0, InsertAtEnd) {
277 init(Func, Args, NumArgs);
280 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
281 const std::string &Name, Instruction *InsertBefore)
282 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
283 ->getElementType())->getReturnType(),
284 Instruction::Call, 0, 0, InsertBefore) {
285 init(Func, Args, NumArgs);
289 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
290 const std::string &Name, Instruction *InsertBefore)
291 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
292 ->getElementType())->getReturnType(),
293 Instruction::Call, 0, 0, InsertBefore) {
294 init(Func, Actual1, Actual2);
298 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
299 const std::string &Name, BasicBlock *InsertAtEnd)
300 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
301 ->getElementType())->getReturnType(),
302 Instruction::Call, 0, 0, InsertAtEnd) {
303 init(Func, Actual1, Actual2);
307 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
308 Instruction *InsertBefore)
309 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
310 ->getElementType())->getReturnType(),
311 Instruction::Call, 0, 0, InsertBefore) {
316 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
317 BasicBlock *InsertAtEnd)
318 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
319 ->getElementType())->getReturnType(),
320 Instruction::Call, 0, 0, InsertAtEnd) {
324 CallInst::CallInst(Value *Func, const std::string &Name,
325 Instruction *InsertBefore)
326 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
327 ->getElementType())->getReturnType(),
328 Instruction::Call, 0, 0, InsertBefore) {
333 CallInst::CallInst(Value *Func, const std::string &Name,
334 BasicBlock *InsertAtEnd)
335 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
336 ->getElementType())->getReturnType(),
337 Instruction::Call, 0, 0, InsertAtEnd) {
342 CallInst::CallInst(const CallInst &CI)
343 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
344 CI.getNumOperands()) {
346 SubclassData = CI.SubclassData;
347 Use *OL = OperandList;
348 Use *InOL = CI.OperandList;
349 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
350 OL[i].init(InOL[i], this);
353 void CallInst::setParamAttrs(ParamAttrsList *newAttrs) {
355 ParamAttrs->dropRef();
360 ParamAttrs = newAttrs;
363 //===----------------------------------------------------------------------===//
364 // InvokeInst Implementation
365 //===----------------------------------------------------------------------===//
367 InvokeInst::~InvokeInst() {
368 delete [] OperandList;
370 ParamAttrs->dropRef();
373 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
374 Value* const *Args, unsigned NumArgs) {
376 NumOperands = 3+NumArgs;
377 Use *OL = OperandList = new Use[3+NumArgs];
378 OL[0].init(Fn, this);
379 OL[1].init(IfNormal, this);
380 OL[2].init(IfException, this);
381 const FunctionType *FTy =
382 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
383 FTy = FTy; // silence warning.
385 assert((NumArgs == FTy->getNumParams()) ||
386 (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
387 "Calling a function with bad signature");
389 for (unsigned i = 0, e = NumArgs; i != e; i++) {
390 assert((i >= FTy->getNumParams() ||
391 FTy->getParamType(i) == Args[i]->getType()) &&
392 "Invoking a function with a bad signature!");
394 OL[i+3].init(Args[i], this);
398 InvokeInst::InvokeInst(const InvokeInst &II)
399 : TerminatorInst(II.getType(), Instruction::Invoke,
400 new Use[II.getNumOperands()], II.getNumOperands()) {
402 SubclassData = II.SubclassData;
403 Use *OL = OperandList, *InOL = II.OperandList;
404 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
405 OL[i].init(InOL[i], this);
408 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
409 return getSuccessor(idx);
411 unsigned InvokeInst::getNumSuccessorsV() const {
412 return getNumSuccessors();
414 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
415 return setSuccessor(idx, B);
418 void InvokeInst::setParamAttrs(ParamAttrsList *newAttrs) {
420 ParamAttrs->dropRef();
425 ParamAttrs = newAttrs;
428 //===----------------------------------------------------------------------===//
429 // ReturnInst Implementation
430 //===----------------------------------------------------------------------===//
432 ReturnInst::ReturnInst(const ReturnInst &RI)
433 : TerminatorInst(Type::VoidTy, Instruction::Ret,
434 &RetVal, RI.getNumOperands()) {
435 if (RI.getNumOperands())
436 RetVal.init(RI.RetVal, this);
439 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
440 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
443 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
444 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
447 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
448 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
453 void ReturnInst::init(Value *retVal) {
454 if (retVal && retVal->getType() != Type::VoidTy) {
455 assert(!isa<BasicBlock>(retVal) &&
456 "Cannot return basic block. Probably using the incorrect ctor");
458 RetVal.init(retVal, this);
462 unsigned ReturnInst::getNumSuccessorsV() const {
463 return getNumSuccessors();
466 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
467 // emit the vtable for the class in this translation unit.
468 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
469 assert(0 && "ReturnInst has no successors!");
472 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
473 assert(0 && "ReturnInst has no successors!");
479 //===----------------------------------------------------------------------===//
480 // UnwindInst Implementation
481 //===----------------------------------------------------------------------===//
483 UnwindInst::UnwindInst(Instruction *InsertBefore)
484 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
486 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
487 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
491 unsigned UnwindInst::getNumSuccessorsV() const {
492 return getNumSuccessors();
495 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
496 assert(0 && "UnwindInst has no successors!");
499 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
500 assert(0 && "UnwindInst has no successors!");
505 //===----------------------------------------------------------------------===//
506 // UnreachableInst Implementation
507 //===----------------------------------------------------------------------===//
509 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
510 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
512 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
513 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
516 unsigned UnreachableInst::getNumSuccessorsV() const {
517 return getNumSuccessors();
520 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
521 assert(0 && "UnwindInst has no successors!");
524 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
525 assert(0 && "UnwindInst has no successors!");
530 //===----------------------------------------------------------------------===//
531 // BranchInst Implementation
532 //===----------------------------------------------------------------------===//
534 void BranchInst::AssertOK() {
536 assert(getCondition()->getType() == Type::Int1Ty &&
537 "May only branch on boolean predicates!");
540 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
541 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
542 assert(IfTrue != 0 && "Branch destination may not be null!");
543 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
545 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
546 Instruction *InsertBefore)
547 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
548 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
549 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
550 Ops[2].init(Cond, this);
556 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
557 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
558 assert(IfTrue != 0 && "Branch destination may not be null!");
559 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
562 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
563 BasicBlock *InsertAtEnd)
564 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
565 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
566 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
567 Ops[2].init(Cond, this);
574 BranchInst::BranchInst(const BranchInst &BI) :
575 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
576 OperandList[0].init(BI.getOperand(0), this);
577 if (BI.getNumOperands() != 1) {
578 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
579 OperandList[1].init(BI.getOperand(1), this);
580 OperandList[2].init(BI.getOperand(2), this);
584 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
585 return getSuccessor(idx);
587 unsigned BranchInst::getNumSuccessorsV() const {
588 return getNumSuccessors();
590 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
591 setSuccessor(idx, B);
595 //===----------------------------------------------------------------------===//
596 // AllocationInst Implementation
597 //===----------------------------------------------------------------------===//
599 static Value *getAISize(Value *Amt) {
601 Amt = ConstantInt::get(Type::Int32Ty, 1);
603 assert(!isa<BasicBlock>(Amt) &&
604 "Passed basic block into allocation size parameter! Ue other ctor");
605 assert(Amt->getType() == Type::Int32Ty &&
606 "Malloc/Allocation array size is not a 32-bit integer!");
611 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
612 unsigned Align, const std::string &Name,
613 Instruction *InsertBefore)
614 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
615 InsertBefore), Alignment(Align) {
616 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
617 assert(Ty != Type::VoidTy && "Cannot allocate void!");
621 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
622 unsigned Align, const std::string &Name,
623 BasicBlock *InsertAtEnd)
624 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
625 InsertAtEnd), Alignment(Align) {
626 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
627 assert(Ty != Type::VoidTy && "Cannot allocate void!");
631 // Out of line virtual method, so the vtable, etc has a home.
632 AllocationInst::~AllocationInst() {
635 bool AllocationInst::isArrayAllocation() const {
636 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
637 return CI->getZExtValue() != 1;
641 const Type *AllocationInst::getAllocatedType() const {
642 return getType()->getElementType();
645 AllocaInst::AllocaInst(const AllocaInst &AI)
646 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
647 Instruction::Alloca, AI.getAlignment()) {
650 MallocInst::MallocInst(const MallocInst &MI)
651 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
652 Instruction::Malloc, MI.getAlignment()) {
655 //===----------------------------------------------------------------------===//
656 // FreeInst Implementation
657 //===----------------------------------------------------------------------===//
659 void FreeInst::AssertOK() {
660 assert(isa<PointerType>(getOperand(0)->getType()) &&
661 "Can not free something of nonpointer type!");
664 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
665 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
669 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
670 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
675 //===----------------------------------------------------------------------===//
676 // LoadInst Implementation
677 //===----------------------------------------------------------------------===//
679 void LoadInst::AssertOK() {
680 assert(isa<PointerType>(getOperand(0)->getType()) &&
681 "Ptr must have pointer type.");
684 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
685 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
686 Load, Ptr, InsertBef) {
693 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
694 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
695 Load, Ptr, InsertAE) {
702 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
703 Instruction *InsertBef)
704 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
705 Load, Ptr, InsertBef) {
706 setVolatile(isVolatile);
712 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
713 unsigned Align, Instruction *InsertBef)
714 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
715 Load, Ptr, InsertBef) {
716 setVolatile(isVolatile);
722 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
723 unsigned Align, BasicBlock *InsertAE)
724 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
725 Load, Ptr, InsertAE) {
726 setVolatile(isVolatile);
732 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
733 BasicBlock *InsertAE)
734 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
735 Load, Ptr, InsertAE) {
736 setVolatile(isVolatile);
744 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
745 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
746 Load, Ptr, InsertBef) {
750 if (Name && Name[0]) setName(Name);
753 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
754 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
755 Load, Ptr, InsertAE) {
759 if (Name && Name[0]) setName(Name);
762 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
763 Instruction *InsertBef)
764 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
765 Load, Ptr, InsertBef) {
766 setVolatile(isVolatile);
769 if (Name && Name[0]) setName(Name);
772 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
773 BasicBlock *InsertAE)
774 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
775 Load, Ptr, InsertAE) {
776 setVolatile(isVolatile);
779 if (Name && Name[0]) setName(Name);
782 void LoadInst::setAlignment(unsigned Align) {
783 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
784 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
787 //===----------------------------------------------------------------------===//
788 // StoreInst Implementation
789 //===----------------------------------------------------------------------===//
791 void StoreInst::AssertOK() {
792 assert(isa<PointerType>(getOperand(1)->getType()) &&
793 "Ptr must have pointer type!");
794 assert(getOperand(0)->getType() ==
795 cast<PointerType>(getOperand(1)->getType())->getElementType()
796 && "Ptr must be a pointer to Val type!");
800 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
801 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
802 Ops[0].init(val, this);
803 Ops[1].init(addr, this);
809 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
810 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
811 Ops[0].init(val, this);
812 Ops[1].init(addr, this);
818 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
819 Instruction *InsertBefore)
820 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
821 Ops[0].init(val, this);
822 Ops[1].init(addr, this);
823 setVolatile(isVolatile);
828 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
829 unsigned Align, Instruction *InsertBefore)
830 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
831 Ops[0].init(val, this);
832 Ops[1].init(addr, this);
833 setVolatile(isVolatile);
838 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
839 unsigned Align, BasicBlock *InsertAtEnd)
840 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
841 Ops[0].init(val, this);
842 Ops[1].init(addr, this);
843 setVolatile(isVolatile);
848 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
849 BasicBlock *InsertAtEnd)
850 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
851 Ops[0].init(val, this);
852 Ops[1].init(addr, this);
853 setVolatile(isVolatile);
858 void StoreInst::setAlignment(unsigned Align) {
859 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
860 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
863 //===----------------------------------------------------------------------===//
864 // GetElementPtrInst Implementation
865 //===----------------------------------------------------------------------===//
867 // checkType - Simple wrapper function to give a better assertion failure
868 // message on bad indexes for a gep instruction.
870 static inline const Type *checkType(const Type *Ty) {
871 assert(Ty && "Invalid GetElementPtrInst indices for type!");
875 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
876 NumOperands = 1+NumIdx;
877 Use *OL = OperandList = new Use[NumOperands];
878 OL[0].init(Ptr, this);
880 for (unsigned i = 0; i != NumIdx; ++i)
881 OL[i+1].init(Idx[i], this);
884 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
886 Use *OL = OperandList = new Use[3];
887 OL[0].init(Ptr, this);
888 OL[1].init(Idx0, this);
889 OL[2].init(Idx1, this);
892 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
894 Use *OL = OperandList = new Use[2];
895 OL[0].init(Ptr, this);
896 OL[1].init(Idx, this);
900 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
902 const std::string &Name, Instruction *InBe)
903 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
904 Idx, NumIdx, true))),
905 GetElementPtr, 0, 0, InBe) {
906 init(Ptr, Idx, NumIdx);
910 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
912 const std::string &Name, BasicBlock *IAE)
913 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
914 Idx, NumIdx, true))),
915 GetElementPtr, 0, 0, IAE) {
916 init(Ptr, Idx, NumIdx);
920 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
921 const std::string &Name, Instruction *InBe)
922 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
923 GetElementPtr, 0, 0, InBe) {
928 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
929 const std::string &Name, BasicBlock *IAE)
930 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
931 GetElementPtr, 0, 0, IAE) {
936 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
937 const std::string &Name, Instruction *InBe)
938 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
940 GetElementPtr, 0, 0, InBe) {
941 init(Ptr, Idx0, Idx1);
945 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
946 const std::string &Name, BasicBlock *IAE)
947 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
949 GetElementPtr, 0, 0, IAE) {
950 init(Ptr, Idx0, Idx1);
954 GetElementPtrInst::~GetElementPtrInst() {
955 delete[] OperandList;
958 // getIndexedType - Returns the type of the element that would be loaded with
959 // a load instruction with the specified parameters.
961 // A null type is returned if the indices are invalid for the specified
964 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
967 bool AllowCompositeLeaf) {
968 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
970 // Handle the special case of the empty set index set...
972 if (AllowCompositeLeaf ||
973 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
974 return cast<PointerType>(Ptr)->getElementType();
979 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
980 if (NumIdx == CurIdx) {
981 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
982 return 0; // Can't load a whole structure or array!?!?
985 Value *Index = Idxs[CurIdx++];
986 if (isa<PointerType>(CT) && CurIdx != 1)
987 return 0; // Can only index into pointer types at the first index!
988 if (!CT->indexValid(Index)) return 0;
989 Ptr = CT->getTypeAtIndex(Index);
991 // If the new type forwards to another type, then it is in the middle
992 // of being refined to another type (and hence, may have dropped all
993 // references to what it was using before). So, use the new forwarded
995 if (const Type * Ty = Ptr->getForwardedType()) {
999 return CurIdx == NumIdx ? Ptr : 0;
1002 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1003 Value *Idx0, Value *Idx1,
1004 bool AllowCompositeLeaf) {
1005 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1006 if (!PTy) return 0; // Type isn't a pointer type!
1008 // Check the pointer index.
1009 if (!PTy->indexValid(Idx0)) return 0;
1011 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
1012 if (!CT || !CT->indexValid(Idx1)) return 0;
1014 const Type *ElTy = CT->getTypeAtIndex(Idx1);
1015 if (AllowCompositeLeaf || ElTy->isFirstClassType())
1020 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1021 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1022 if (!PTy) return 0; // Type isn't a pointer type!
1024 // Check the pointer index.
1025 if (!PTy->indexValid(Idx)) return 0;
1027 return PTy->getElementType();
1031 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1032 /// zeros. If so, the result pointer and the first operand have the same
1033 /// value, just potentially different types.
1034 bool GetElementPtrInst::hasAllZeroIndices() const {
1035 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1036 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1037 if (!CI->isZero()) return false;
1045 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1046 /// constant integers. If so, the result pointer and the first operand have
1047 /// a constant offset between them.
1048 bool GetElementPtrInst::hasAllConstantIndices() const {
1049 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1050 if (!isa<ConstantInt>(getOperand(i)))
1057 //===----------------------------------------------------------------------===//
1058 // ExtractElementInst Implementation
1059 //===----------------------------------------------------------------------===//
1061 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1062 const std::string &Name,
1063 Instruction *InsertBef)
1064 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1065 ExtractElement, Ops, 2, InsertBef) {
1066 assert(isValidOperands(Val, Index) &&
1067 "Invalid extractelement instruction operands!");
1068 Ops[0].init(Val, this);
1069 Ops[1].init(Index, this);
1073 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1074 const std::string &Name,
1075 Instruction *InsertBef)
1076 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1077 ExtractElement, Ops, 2, InsertBef) {
1078 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1079 assert(isValidOperands(Val, Index) &&
1080 "Invalid extractelement instruction operands!");
1081 Ops[0].init(Val, this);
1082 Ops[1].init(Index, this);
1087 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1088 const std::string &Name,
1089 BasicBlock *InsertAE)
1090 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1091 ExtractElement, Ops, 2, InsertAE) {
1092 assert(isValidOperands(Val, Index) &&
1093 "Invalid extractelement instruction operands!");
1095 Ops[0].init(Val, this);
1096 Ops[1].init(Index, this);
1100 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1101 const std::string &Name,
1102 BasicBlock *InsertAE)
1103 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1104 ExtractElement, Ops, 2, InsertAE) {
1105 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1106 assert(isValidOperands(Val, Index) &&
1107 "Invalid extractelement instruction operands!");
1109 Ops[0].init(Val, this);
1110 Ops[1].init(Index, this);
1115 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1116 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1122 //===----------------------------------------------------------------------===//
1123 // InsertElementInst Implementation
1124 //===----------------------------------------------------------------------===//
1126 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1127 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1128 Ops[0].init(IE.Ops[0], this);
1129 Ops[1].init(IE.Ops[1], this);
1130 Ops[2].init(IE.Ops[2], this);
1132 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1133 const std::string &Name,
1134 Instruction *InsertBef)
1135 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1136 assert(isValidOperands(Vec, Elt, Index) &&
1137 "Invalid insertelement instruction operands!");
1138 Ops[0].init(Vec, this);
1139 Ops[1].init(Elt, this);
1140 Ops[2].init(Index, this);
1144 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1145 const std::string &Name,
1146 Instruction *InsertBef)
1147 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1148 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1149 assert(isValidOperands(Vec, Elt, Index) &&
1150 "Invalid insertelement instruction operands!");
1151 Ops[0].init(Vec, this);
1152 Ops[1].init(Elt, this);
1153 Ops[2].init(Index, this);
1158 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1159 const std::string &Name,
1160 BasicBlock *InsertAE)
1161 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1162 assert(isValidOperands(Vec, Elt, Index) &&
1163 "Invalid insertelement instruction operands!");
1165 Ops[0].init(Vec, this);
1166 Ops[1].init(Elt, this);
1167 Ops[2].init(Index, this);
1171 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1172 const std::string &Name,
1173 BasicBlock *InsertAE)
1174 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1175 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1176 assert(isValidOperands(Vec, Elt, Index) &&
1177 "Invalid insertelement instruction operands!");
1179 Ops[0].init(Vec, this);
1180 Ops[1].init(Elt, this);
1181 Ops[2].init(Index, this);
1185 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1186 const Value *Index) {
1187 if (!isa<VectorType>(Vec->getType()))
1188 return false; // First operand of insertelement must be vector type.
1190 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1191 return false;// Second operand of insertelement must be vector element type.
1193 if (Index->getType() != Type::Int32Ty)
1194 return false; // Third operand of insertelement must be uint.
1199 //===----------------------------------------------------------------------===//
1200 // ShuffleVectorInst Implementation
1201 //===----------------------------------------------------------------------===//
1203 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1204 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1205 Ops[0].init(SV.Ops[0], this);
1206 Ops[1].init(SV.Ops[1], this);
1207 Ops[2].init(SV.Ops[2], this);
1210 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1211 const std::string &Name,
1212 Instruction *InsertBefore)
1213 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1214 assert(isValidOperands(V1, V2, Mask) &&
1215 "Invalid shuffle vector instruction operands!");
1216 Ops[0].init(V1, this);
1217 Ops[1].init(V2, this);
1218 Ops[2].init(Mask, this);
1222 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1223 const std::string &Name,
1224 BasicBlock *InsertAtEnd)
1225 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1226 assert(isValidOperands(V1, V2, Mask) &&
1227 "Invalid shuffle vector instruction operands!");
1229 Ops[0].init(V1, this);
1230 Ops[1].init(V2, this);
1231 Ops[2].init(Mask, this);
1235 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1236 const Value *Mask) {
1237 if (!isa<VectorType>(V1->getType())) return false;
1238 if (V1->getType() != V2->getType()) return false;
1239 if (!isa<VectorType>(Mask->getType()) ||
1240 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1241 cast<VectorType>(Mask->getType())->getNumElements() !=
1242 cast<VectorType>(V1->getType())->getNumElements())
1248 //===----------------------------------------------------------------------===//
1249 // BinaryOperator Class
1250 //===----------------------------------------------------------------------===//
1252 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1253 const Type *Ty, const std::string &Name,
1254 Instruction *InsertBefore)
1255 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1256 Ops[0].init(S1, this);
1257 Ops[1].init(S2, this);
1262 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1263 const Type *Ty, const std::string &Name,
1264 BasicBlock *InsertAtEnd)
1265 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1266 Ops[0].init(S1, this);
1267 Ops[1].init(S2, this);
1273 void BinaryOperator::init(BinaryOps iType) {
1274 Value *LHS = getOperand(0), *RHS = getOperand(1);
1275 LHS = LHS; RHS = RHS; // Silence warnings.
1276 assert(LHS->getType() == RHS->getType() &&
1277 "Binary operator operand types must match!");
1282 assert(getType() == LHS->getType() &&
1283 "Arithmetic operation should return same type as operands!");
1284 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1285 isa<VectorType>(getType())) &&
1286 "Tried to create an arithmetic operation on a non-arithmetic type!");
1290 assert(getType() == LHS->getType() &&
1291 "Arithmetic operation should return same type as operands!");
1292 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1293 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1294 "Incorrect operand type (not integer) for S/UDIV");
1297 assert(getType() == LHS->getType() &&
1298 "Arithmetic operation should return same type as operands!");
1299 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1300 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1301 && "Incorrect operand type (not floating point) for FDIV");
1305 assert(getType() == LHS->getType() &&
1306 "Arithmetic operation should return same type as operands!");
1307 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1308 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1309 "Incorrect operand type (not integer) for S/UREM");
1312 assert(getType() == LHS->getType() &&
1313 "Arithmetic operation should return same type as operands!");
1314 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1315 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1316 && "Incorrect operand type (not floating point) for FREM");
1321 assert(getType() == LHS->getType() &&
1322 "Shift operation should return same type as operands!");
1323 assert(getType()->isInteger() &&
1324 "Shift operation requires integer operands");
1328 assert(getType() == LHS->getType() &&
1329 "Logical operation should return same type as operands!");
1330 assert((getType()->isInteger() ||
1331 (isa<VectorType>(getType()) &&
1332 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1333 "Tried to create a logical operation on a non-integral type!");
1341 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1342 const std::string &Name,
1343 Instruction *InsertBefore) {
1344 assert(S1->getType() == S2->getType() &&
1345 "Cannot create binary operator with two operands of differing type!");
1346 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1349 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1350 const std::string &Name,
1351 BasicBlock *InsertAtEnd) {
1352 BinaryOperator *Res = create(Op, S1, S2, Name);
1353 InsertAtEnd->getInstList().push_back(Res);
1357 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1358 Instruction *InsertBefore) {
1359 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1360 return new BinaryOperator(Instruction::Sub,
1362 Op->getType(), Name, InsertBefore);
1365 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1366 BasicBlock *InsertAtEnd) {
1367 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1368 return new BinaryOperator(Instruction::Sub,
1370 Op->getType(), Name, InsertAtEnd);
1373 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1374 Instruction *InsertBefore) {
1376 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1377 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1378 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1380 C = ConstantInt::getAllOnesValue(Op->getType());
1383 return new BinaryOperator(Instruction::Xor, Op, C,
1384 Op->getType(), Name, InsertBefore);
1387 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1388 BasicBlock *InsertAtEnd) {
1390 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1391 // Create a vector of all ones values.
1392 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1394 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1396 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1399 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1400 Op->getType(), Name, InsertAtEnd);
1404 // isConstantAllOnes - Helper function for several functions below
1405 static inline bool isConstantAllOnes(const Value *V) {
1406 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1407 return CI->isAllOnesValue();
1408 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1409 return CV->isAllOnesValue();
1413 bool BinaryOperator::isNeg(const Value *V) {
1414 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1415 if (Bop->getOpcode() == Instruction::Sub)
1416 return Bop->getOperand(0) ==
1417 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1421 bool BinaryOperator::isNot(const Value *V) {
1422 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1423 return (Bop->getOpcode() == Instruction::Xor &&
1424 (isConstantAllOnes(Bop->getOperand(1)) ||
1425 isConstantAllOnes(Bop->getOperand(0))));
1429 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1430 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1431 return cast<BinaryOperator>(BinOp)->getOperand(1);
1434 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1435 return getNegArgument(const_cast<Value*>(BinOp));
1438 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1439 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1440 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1441 Value *Op0 = BO->getOperand(0);
1442 Value *Op1 = BO->getOperand(1);
1443 if (isConstantAllOnes(Op0)) return Op1;
1445 assert(isConstantAllOnes(Op1));
1449 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1450 return getNotArgument(const_cast<Value*>(BinOp));
1454 // swapOperands - Exchange the two operands to this instruction. This
1455 // instruction is safe to use on any binary instruction and does not
1456 // modify the semantics of the instruction. If the instruction is
1457 // order dependent (SetLT f.e.) the opcode is changed.
1459 bool BinaryOperator::swapOperands() {
1460 if (!isCommutative())
1461 return true; // Can't commute operands
1462 std::swap(Ops[0], Ops[1]);
1466 //===----------------------------------------------------------------------===//
1468 //===----------------------------------------------------------------------===//
1470 // Just determine if this cast only deals with integral->integral conversion.
1471 bool CastInst::isIntegerCast() const {
1472 switch (getOpcode()) {
1473 default: return false;
1474 case Instruction::ZExt:
1475 case Instruction::SExt:
1476 case Instruction::Trunc:
1478 case Instruction::BitCast:
1479 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1483 bool CastInst::isLosslessCast() const {
1484 // Only BitCast can be lossless, exit fast if we're not BitCast
1485 if (getOpcode() != Instruction::BitCast)
1488 // Identity cast is always lossless
1489 const Type* SrcTy = getOperand(0)->getType();
1490 const Type* DstTy = getType();
1494 // Pointer to pointer is always lossless.
1495 if (isa<PointerType>(SrcTy))
1496 return isa<PointerType>(DstTy);
1497 return false; // Other types have no identity values
1500 /// This function determines if the CastInst does not require any bits to be
1501 /// changed in order to effect the cast. Essentially, it identifies cases where
1502 /// no code gen is necessary for the cast, hence the name no-op cast. For
1503 /// example, the following are all no-op casts:
1504 /// # bitcast uint %X, int
1505 /// # bitcast uint* %x, sbyte*
1506 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1507 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1508 /// @brief Determine if a cast is a no-op.
1509 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1510 switch (getOpcode()) {
1512 assert(!"Invalid CastOp");
1513 case Instruction::Trunc:
1514 case Instruction::ZExt:
1515 case Instruction::SExt:
1516 case Instruction::FPTrunc:
1517 case Instruction::FPExt:
1518 case Instruction::UIToFP:
1519 case Instruction::SIToFP:
1520 case Instruction::FPToUI:
1521 case Instruction::FPToSI:
1522 return false; // These always modify bits
1523 case Instruction::BitCast:
1524 return true; // BitCast never modifies bits.
1525 case Instruction::PtrToInt:
1526 return IntPtrTy->getPrimitiveSizeInBits() ==
1527 getType()->getPrimitiveSizeInBits();
1528 case Instruction::IntToPtr:
1529 return IntPtrTy->getPrimitiveSizeInBits() ==
1530 getOperand(0)->getType()->getPrimitiveSizeInBits();
1534 /// This function determines if a pair of casts can be eliminated and what
1535 /// opcode should be used in the elimination. This assumes that there are two
1536 /// instructions like this:
1537 /// * %F = firstOpcode SrcTy %x to MidTy
1538 /// * %S = secondOpcode MidTy %F to DstTy
1539 /// The function returns a resultOpcode so these two casts can be replaced with:
1540 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1541 /// If no such cast is permited, the function returns 0.
1542 unsigned CastInst::isEliminableCastPair(
1543 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1544 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1546 // Define the 144 possibilities for these two cast instructions. The values
1547 // in this matrix determine what to do in a given situation and select the
1548 // case in the switch below. The rows correspond to firstOp, the columns
1549 // correspond to secondOp. In looking at the table below, keep in mind
1550 // the following cast properties:
1552 // Size Compare Source Destination
1553 // Operator Src ? Size Type Sign Type Sign
1554 // -------- ------------ ------------------- ---------------------
1555 // TRUNC > Integer Any Integral Any
1556 // ZEXT < Integral Unsigned Integer Any
1557 // SEXT < Integral Signed Integer Any
1558 // FPTOUI n/a FloatPt n/a Integral Unsigned
1559 // FPTOSI n/a FloatPt n/a Integral Signed
1560 // UITOFP n/a Integral Unsigned FloatPt n/a
1561 // SITOFP n/a Integral Signed FloatPt n/a
1562 // FPTRUNC > FloatPt n/a FloatPt n/a
1563 // FPEXT < FloatPt n/a FloatPt n/a
1564 // PTRTOINT n/a Pointer n/a Integral Unsigned
1565 // INTTOPTR n/a Integral Unsigned Pointer n/a
1566 // BITCONVERT = FirstClass n/a FirstClass n/a
1568 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1569 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1570 // into "fptoui double to ulong", but this loses information about the range
1571 // of the produced value (we no longer know the top-part is all zeros).
1572 // Further this conversion is often much more expensive for typical hardware,
1573 // and causes issues when building libgcc. We disallow fptosi+sext for the
1575 const unsigned numCastOps =
1576 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1577 static const uint8_t CastResults[numCastOps][numCastOps] = {
1578 // T F F U S F F P I B -+
1579 // R Z S P P I I T P 2 N T |
1580 // U E E 2 2 2 2 R E I T C +- secondOp
1581 // N X X U S F F N X N 2 V |
1582 // C T T I I P P C T T P T -+
1583 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1584 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1585 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1586 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1587 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1588 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1589 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1590 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1591 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1592 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1593 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1594 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1597 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1598 [secondOp-Instruction::CastOpsBegin];
1601 // categorically disallowed
1604 // allowed, use first cast's opcode
1607 // allowed, use second cast's opcode
1610 // no-op cast in second op implies firstOp as long as the DestTy
1612 if (DstTy->isInteger())
1616 // no-op cast in second op implies firstOp as long as the DestTy
1617 // is floating point
1618 if (DstTy->isFloatingPoint())
1622 // no-op cast in first op implies secondOp as long as the SrcTy
1624 if (SrcTy->isInteger())
1628 // no-op cast in first op implies secondOp as long as the SrcTy
1629 // is a floating point
1630 if (SrcTy->isFloatingPoint())
1634 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1635 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1636 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1637 if (MidSize >= PtrSize)
1638 return Instruction::BitCast;
1642 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1643 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1644 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1645 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1646 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1647 if (SrcSize == DstSize)
1648 return Instruction::BitCast;
1649 else if (SrcSize < DstSize)
1653 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1654 return Instruction::ZExt;
1656 // fpext followed by ftrunc is allowed if the bit size returned to is
1657 // the same as the original, in which case its just a bitcast
1659 return Instruction::BitCast;
1660 return 0; // If the types are not the same we can't eliminate it.
1662 // bitcast followed by ptrtoint is allowed as long as the bitcast
1663 // is a pointer to pointer cast.
1664 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1668 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1669 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1673 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1674 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1675 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1676 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1677 if (SrcSize <= PtrSize && SrcSize == DstSize)
1678 return Instruction::BitCast;
1682 // cast combination can't happen (error in input). This is for all cases
1683 // where the MidTy is not the same for the two cast instructions.
1684 assert(!"Invalid Cast Combination");
1687 assert(!"Error in CastResults table!!!");
1693 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1694 const std::string &Name, Instruction *InsertBefore) {
1695 // Construct and return the appropriate CastInst subclass
1697 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1698 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1699 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1700 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1701 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1702 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1703 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1704 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1705 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1706 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1707 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1708 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1710 assert(!"Invalid opcode provided");
1715 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1716 const std::string &Name, BasicBlock *InsertAtEnd) {
1717 // Construct and return the appropriate CastInst subclass
1719 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1720 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1721 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1722 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1723 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1724 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1725 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1726 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1727 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1728 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1729 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1730 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1732 assert(!"Invalid opcode provided");
1737 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1738 const std::string &Name,
1739 Instruction *InsertBefore) {
1740 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1741 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1742 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1745 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1746 const std::string &Name,
1747 BasicBlock *InsertAtEnd) {
1748 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1749 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1750 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1753 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1754 const std::string &Name,
1755 Instruction *InsertBefore) {
1756 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1757 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1758 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1761 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1762 const std::string &Name,
1763 BasicBlock *InsertAtEnd) {
1764 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1765 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1766 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1769 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1770 const std::string &Name,
1771 Instruction *InsertBefore) {
1772 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1773 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1774 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1777 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1778 const std::string &Name,
1779 BasicBlock *InsertAtEnd) {
1780 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1781 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1782 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1785 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1786 const std::string &Name,
1787 BasicBlock *InsertAtEnd) {
1788 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1789 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1792 if (Ty->isInteger())
1793 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1794 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1797 /// @brief Create a BitCast or a PtrToInt cast instruction
1798 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1799 const std::string &Name,
1800 Instruction *InsertBefore) {
1801 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1802 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1805 if (Ty->isInteger())
1806 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1807 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1810 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1811 bool isSigned, const std::string &Name,
1812 Instruction *InsertBefore) {
1813 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1814 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1815 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1816 Instruction::CastOps opcode =
1817 (SrcBits == DstBits ? Instruction::BitCast :
1818 (SrcBits > DstBits ? Instruction::Trunc :
1819 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1820 return create(opcode, C, Ty, Name, InsertBefore);
1823 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1824 bool isSigned, const std::string &Name,
1825 BasicBlock *InsertAtEnd) {
1826 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1827 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1828 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1829 Instruction::CastOps opcode =
1830 (SrcBits == DstBits ? Instruction::BitCast :
1831 (SrcBits > DstBits ? Instruction::Trunc :
1832 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1833 return create(opcode, C, Ty, Name, InsertAtEnd);
1836 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1837 const std::string &Name,
1838 Instruction *InsertBefore) {
1839 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1841 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1842 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1843 Instruction::CastOps opcode =
1844 (SrcBits == DstBits ? Instruction::BitCast :
1845 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1846 return create(opcode, C, Ty, Name, InsertBefore);
1849 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1850 const std::string &Name,
1851 BasicBlock *InsertAtEnd) {
1852 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1854 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1855 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1856 Instruction::CastOps opcode =
1857 (SrcBits == DstBits ? Instruction::BitCast :
1858 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1859 return create(opcode, C, Ty, Name, InsertAtEnd);
1862 // Provide a way to get a "cast" where the cast opcode is inferred from the
1863 // types and size of the operand. This, basically, is a parallel of the
1864 // logic in the castIsValid function below. This axiom should hold:
1865 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1866 // should not assert in castIsValid. In other words, this produces a "correct"
1867 // casting opcode for the arguments passed to it.
1868 Instruction::CastOps
1869 CastInst::getCastOpcode(
1870 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1871 // Get the bit sizes, we'll need these
1872 const Type *SrcTy = Src->getType();
1873 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1874 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1876 // Run through the possibilities ...
1877 if (DestTy->isInteger()) { // Casting to integral
1878 if (SrcTy->isInteger()) { // Casting from integral
1879 if (DestBits < SrcBits)
1880 return Trunc; // int -> smaller int
1881 else if (DestBits > SrcBits) { // its an extension
1883 return SExt; // signed -> SEXT
1885 return ZExt; // unsigned -> ZEXT
1887 return BitCast; // Same size, No-op cast
1889 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1891 return FPToSI; // FP -> sint
1893 return FPToUI; // FP -> uint
1894 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1895 assert(DestBits == PTy->getBitWidth() &&
1896 "Casting vector to integer of different width");
1897 return BitCast; // Same size, no-op cast
1899 assert(isa<PointerType>(SrcTy) &&
1900 "Casting from a value that is not first-class type");
1901 return PtrToInt; // ptr -> int
1903 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1904 if (SrcTy->isInteger()) { // Casting from integral
1906 return SIToFP; // sint -> FP
1908 return UIToFP; // uint -> FP
1909 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1910 if (DestBits < SrcBits) {
1911 return FPTrunc; // FP -> smaller FP
1912 } else if (DestBits > SrcBits) {
1913 return FPExt; // FP -> larger FP
1915 return BitCast; // same size, no-op cast
1917 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1918 assert(DestBits == PTy->getBitWidth() &&
1919 "Casting vector to floating point of different width");
1920 return BitCast; // same size, no-op cast
1922 assert(0 && "Casting pointer or non-first class to float");
1924 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1925 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1926 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1927 "Casting vector to vector of different widths");
1928 return BitCast; // vector -> vector
1929 } else if (DestPTy->getBitWidth() == SrcBits) {
1930 return BitCast; // float/int -> vector
1932 assert(!"Illegal cast to vector (wrong type or size)");
1934 } else if (isa<PointerType>(DestTy)) {
1935 if (isa<PointerType>(SrcTy)) {
1936 return BitCast; // ptr -> ptr
1937 } else if (SrcTy->isInteger()) {
1938 return IntToPtr; // int -> ptr
1940 assert(!"Casting pointer to other than pointer or int");
1943 assert(!"Casting to type that is not first-class");
1946 // If we fall through to here we probably hit an assertion cast above
1947 // and assertions are not turned on. Anything we return is an error, so
1948 // BitCast is as good a choice as any.
1952 //===----------------------------------------------------------------------===//
1953 // CastInst SubClass Constructors
1954 //===----------------------------------------------------------------------===//
1956 /// Check that the construction parameters for a CastInst are correct. This
1957 /// could be broken out into the separate constructors but it is useful to have
1958 /// it in one place and to eliminate the redundant code for getting the sizes
1959 /// of the types involved.
1961 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1963 // Check for type sanity on the arguments
1964 const Type *SrcTy = S->getType();
1965 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1968 // Get the size of the types in bits, we'll need this later
1969 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1970 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1972 // Switch on the opcode provided
1974 default: return false; // This is an input error
1975 case Instruction::Trunc:
1976 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1977 case Instruction::ZExt:
1978 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1979 case Instruction::SExt:
1980 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1981 case Instruction::FPTrunc:
1982 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1983 SrcBitSize > DstBitSize;
1984 case Instruction::FPExt:
1985 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1986 SrcBitSize < DstBitSize;
1987 case Instruction::UIToFP:
1988 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1989 case Instruction::SIToFP:
1990 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1991 case Instruction::FPToUI:
1992 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1993 case Instruction::FPToSI:
1994 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1995 case Instruction::PtrToInt:
1996 return isa<PointerType>(SrcTy) && DstTy->isInteger();
1997 case Instruction::IntToPtr:
1998 return SrcTy->isInteger() && isa<PointerType>(DstTy);
1999 case Instruction::BitCast:
2000 // BitCast implies a no-op cast of type only. No bits change.
2001 // However, you can't cast pointers to anything but pointers.
2002 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2005 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
2006 // these cases, the cast is okay if the source and destination bit widths
2008 return SrcBitSize == DstBitSize;
2012 TruncInst::TruncInst(
2013 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2014 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2015 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2018 TruncInst::TruncInst(
2019 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2020 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2021 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2025 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2026 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2027 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2031 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2032 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2033 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2036 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2037 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2038 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2042 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2043 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2044 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2047 FPTruncInst::FPTruncInst(
2048 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2049 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2050 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2053 FPTruncInst::FPTruncInst(
2054 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2055 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2056 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2059 FPExtInst::FPExtInst(
2060 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2061 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2062 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2065 FPExtInst::FPExtInst(
2066 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2067 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2068 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2071 UIToFPInst::UIToFPInst(
2072 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2073 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2074 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2077 UIToFPInst::UIToFPInst(
2078 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2079 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2080 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2083 SIToFPInst::SIToFPInst(
2084 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2085 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2086 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2089 SIToFPInst::SIToFPInst(
2090 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2091 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2092 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2095 FPToUIInst::FPToUIInst(
2096 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2097 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2098 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2101 FPToUIInst::FPToUIInst(
2102 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2103 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2104 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2107 FPToSIInst::FPToSIInst(
2108 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2109 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2110 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2113 FPToSIInst::FPToSIInst(
2114 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2115 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2116 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2119 PtrToIntInst::PtrToIntInst(
2120 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2121 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2122 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2125 PtrToIntInst::PtrToIntInst(
2126 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2127 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2128 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2131 IntToPtrInst::IntToPtrInst(
2132 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2133 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2134 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2137 IntToPtrInst::IntToPtrInst(
2138 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2139 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2140 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2143 BitCastInst::BitCastInst(
2144 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2145 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2146 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2149 BitCastInst::BitCastInst(
2150 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2151 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2152 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2155 //===----------------------------------------------------------------------===//
2157 //===----------------------------------------------------------------------===//
2159 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2160 const std::string &Name, Instruction *InsertBefore)
2161 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2162 Ops[0].init(LHS, this);
2163 Ops[1].init(RHS, this);
2164 SubclassData = predicate;
2166 if (op == Instruction::ICmp) {
2167 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2168 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2169 "Invalid ICmp predicate value");
2170 const Type* Op0Ty = getOperand(0)->getType();
2171 const Type* Op1Ty = getOperand(1)->getType();
2172 assert(Op0Ty == Op1Ty &&
2173 "Both operands to ICmp instruction are not of the same type!");
2174 // Check that the operands are the right type
2175 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2176 "Invalid operand types for ICmp instruction");
2179 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2180 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2181 "Invalid FCmp predicate value");
2182 const Type* Op0Ty = getOperand(0)->getType();
2183 const Type* Op1Ty = getOperand(1)->getType();
2184 assert(Op0Ty == Op1Ty &&
2185 "Both operands to FCmp instruction are not of the same type!");
2186 // Check that the operands are the right type
2187 assert(Op0Ty->isFloatingPoint() &&
2188 "Invalid operand types for FCmp instruction");
2191 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2192 const std::string &Name, BasicBlock *InsertAtEnd)
2193 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2194 Ops[0].init(LHS, this);
2195 Ops[1].init(RHS, this);
2196 SubclassData = predicate;
2198 if (op == Instruction::ICmp) {
2199 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2200 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2201 "Invalid ICmp predicate value");
2203 const Type* Op0Ty = getOperand(0)->getType();
2204 const Type* Op1Ty = getOperand(1)->getType();
2205 assert(Op0Ty == Op1Ty &&
2206 "Both operands to ICmp instruction are not of the same type!");
2207 // Check that the operands are the right type
2208 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2209 "Invalid operand types for ICmp instruction");
2212 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2213 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2214 "Invalid FCmp predicate value");
2215 const Type* Op0Ty = getOperand(0)->getType();
2216 const Type* Op1Ty = getOperand(1)->getType();
2217 assert(Op0Ty == Op1Ty &&
2218 "Both operands to FCmp instruction are not of the same type!");
2219 // Check that the operands are the right type
2220 assert(Op0Ty->isFloatingPoint() &&
2221 "Invalid operand types for FCmp instruction");
2225 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2226 const std::string &Name, Instruction *InsertBefore) {
2227 if (Op == Instruction::ICmp) {
2228 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2231 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2236 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2237 const std::string &Name, BasicBlock *InsertAtEnd) {
2238 if (Op == Instruction::ICmp) {
2239 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2242 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2246 void CmpInst::swapOperands() {
2247 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2250 cast<FCmpInst>(this)->swapOperands();
2253 bool CmpInst::isCommutative() {
2254 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2255 return IC->isCommutative();
2256 return cast<FCmpInst>(this)->isCommutative();
2259 bool CmpInst::isEquality() {
2260 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2261 return IC->isEquality();
2262 return cast<FCmpInst>(this)->isEquality();
2266 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2269 assert(!"Unknown icmp predicate!");
2270 case ICMP_EQ: return ICMP_NE;
2271 case ICMP_NE: return ICMP_EQ;
2272 case ICMP_UGT: return ICMP_ULE;
2273 case ICMP_ULT: return ICMP_UGE;
2274 case ICMP_UGE: return ICMP_ULT;
2275 case ICMP_ULE: return ICMP_UGT;
2276 case ICMP_SGT: return ICMP_SLE;
2277 case ICMP_SLT: return ICMP_SGE;
2278 case ICMP_SGE: return ICMP_SLT;
2279 case ICMP_SLE: return ICMP_SGT;
2283 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2285 default: assert(! "Unknown icmp predicate!");
2286 case ICMP_EQ: case ICMP_NE:
2288 case ICMP_SGT: return ICMP_SLT;
2289 case ICMP_SLT: return ICMP_SGT;
2290 case ICMP_SGE: return ICMP_SLE;
2291 case ICMP_SLE: return ICMP_SGE;
2292 case ICMP_UGT: return ICMP_ULT;
2293 case ICMP_ULT: return ICMP_UGT;
2294 case ICMP_UGE: return ICMP_ULE;
2295 case ICMP_ULE: return ICMP_UGE;
2299 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2301 default: assert(! "Unknown icmp predicate!");
2302 case ICMP_EQ: case ICMP_NE:
2303 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2305 case ICMP_UGT: return ICMP_SGT;
2306 case ICMP_ULT: return ICMP_SLT;
2307 case ICMP_UGE: return ICMP_SGE;
2308 case ICMP_ULE: return ICMP_SLE;
2312 bool ICmpInst::isSignedPredicate(Predicate pred) {
2314 default: assert(! "Unknown icmp predicate!");
2315 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2317 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2318 case ICMP_UGE: case ICMP_ULE:
2323 /// Initialize a set of values that all satisfy the condition with C.
2326 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2329 uint32_t BitWidth = C.getBitWidth();
2331 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2332 case ICmpInst::ICMP_EQ: Upper++; break;
2333 case ICmpInst::ICMP_NE: Lower++; break;
2334 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2335 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2336 case ICmpInst::ICMP_UGT:
2337 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2339 case ICmpInst::ICMP_SGT:
2340 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2342 case ICmpInst::ICMP_ULE:
2343 Lower = APInt::getMinValue(BitWidth); Upper++;
2345 case ICmpInst::ICMP_SLE:
2346 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2348 case ICmpInst::ICMP_UGE:
2349 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2351 case ICmpInst::ICMP_SGE:
2352 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2355 return ConstantRange(Lower, Upper);
2358 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2361 assert(!"Unknown icmp predicate!");
2362 case FCMP_OEQ: return FCMP_UNE;
2363 case FCMP_ONE: return FCMP_UEQ;
2364 case FCMP_OGT: return FCMP_ULE;
2365 case FCMP_OLT: return FCMP_UGE;
2366 case FCMP_OGE: return FCMP_ULT;
2367 case FCMP_OLE: return FCMP_UGT;
2368 case FCMP_UEQ: return FCMP_ONE;
2369 case FCMP_UNE: return FCMP_OEQ;
2370 case FCMP_UGT: return FCMP_OLE;
2371 case FCMP_ULT: return FCMP_OGE;
2372 case FCMP_UGE: return FCMP_OLT;
2373 case FCMP_ULE: return FCMP_OGT;
2374 case FCMP_ORD: return FCMP_UNO;
2375 case FCMP_UNO: return FCMP_ORD;
2376 case FCMP_TRUE: return FCMP_FALSE;
2377 case FCMP_FALSE: return FCMP_TRUE;
2381 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2383 default: assert(!"Unknown fcmp predicate!");
2384 case FCMP_FALSE: case FCMP_TRUE:
2385 case FCMP_OEQ: case FCMP_ONE:
2386 case FCMP_UEQ: case FCMP_UNE:
2387 case FCMP_ORD: case FCMP_UNO:
2389 case FCMP_OGT: return FCMP_OLT;
2390 case FCMP_OLT: return FCMP_OGT;
2391 case FCMP_OGE: return FCMP_OLE;
2392 case FCMP_OLE: return FCMP_OGE;
2393 case FCMP_UGT: return FCMP_ULT;
2394 case FCMP_ULT: return FCMP_UGT;
2395 case FCMP_UGE: return FCMP_ULE;
2396 case FCMP_ULE: return FCMP_UGE;
2400 bool CmpInst::isUnsigned(unsigned short predicate) {
2401 switch (predicate) {
2402 default: return false;
2403 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2404 case ICmpInst::ICMP_UGE: return true;
2408 bool CmpInst::isSigned(unsigned short predicate){
2409 switch (predicate) {
2410 default: return false;
2411 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2412 case ICmpInst::ICMP_SGE: return true;
2416 bool CmpInst::isOrdered(unsigned short predicate) {
2417 switch (predicate) {
2418 default: return false;
2419 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2420 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2421 case FCmpInst::FCMP_ORD: return true;
2425 bool CmpInst::isUnordered(unsigned short predicate) {
2426 switch (predicate) {
2427 default: return false;
2428 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2429 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2430 case FCmpInst::FCMP_UNO: return true;
2434 //===----------------------------------------------------------------------===//
2435 // SwitchInst Implementation
2436 //===----------------------------------------------------------------------===//
2438 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2439 assert(Value && Default);
2440 ReservedSpace = 2+NumCases*2;
2442 OperandList = new Use[ReservedSpace];
2444 OperandList[0].init(Value, this);
2445 OperandList[1].init(Default, this);
2448 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2449 /// switch on and a default destination. The number of additional cases can
2450 /// be specified here to make memory allocation more efficient. This
2451 /// constructor can also autoinsert before another instruction.
2452 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2453 Instruction *InsertBefore)
2454 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2455 init(Value, Default, NumCases);
2458 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2459 /// switch on and a default destination. The number of additional cases can
2460 /// be specified here to make memory allocation more efficient. This
2461 /// constructor also autoinserts at the end of the specified BasicBlock.
2462 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2463 BasicBlock *InsertAtEnd)
2464 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2465 init(Value, Default, NumCases);
2468 SwitchInst::SwitchInst(const SwitchInst &SI)
2469 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2470 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2471 Use *OL = OperandList, *InOL = SI.OperandList;
2472 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2473 OL[i].init(InOL[i], this);
2474 OL[i+1].init(InOL[i+1], this);
2478 SwitchInst::~SwitchInst() {
2479 delete [] OperandList;
2483 /// addCase - Add an entry to the switch instruction...
2485 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2486 unsigned OpNo = NumOperands;
2487 if (OpNo+2 > ReservedSpace)
2488 resizeOperands(0); // Get more space!
2489 // Initialize some new operands.
2490 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2491 NumOperands = OpNo+2;
2492 OperandList[OpNo].init(OnVal, this);
2493 OperandList[OpNo+1].init(Dest, this);
2496 /// removeCase - This method removes the specified successor from the switch
2497 /// instruction. Note that this cannot be used to remove the default
2498 /// destination (successor #0).
2500 void SwitchInst::removeCase(unsigned idx) {
2501 assert(idx != 0 && "Cannot remove the default case!");
2502 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2504 unsigned NumOps = getNumOperands();
2505 Use *OL = OperandList;
2507 // Move everything after this operand down.
2509 // FIXME: we could just swap with the end of the list, then erase. However,
2510 // client might not expect this to happen. The code as it is thrashes the
2511 // use/def lists, which is kinda lame.
2512 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2514 OL[i-2+1] = OL[i+1];
2517 // Nuke the last value.
2518 OL[NumOps-2].set(0);
2519 OL[NumOps-2+1].set(0);
2520 NumOperands = NumOps-2;
2523 /// resizeOperands - resize operands - This adjusts the length of the operands
2524 /// list according to the following behavior:
2525 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2526 /// of operation. This grows the number of ops by 1.5 times.
2527 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2528 /// 3. If NumOps == NumOperands, trim the reserved space.
2530 void SwitchInst::resizeOperands(unsigned NumOps) {
2532 NumOps = getNumOperands()/2*6;
2533 } else if (NumOps*2 > NumOperands) {
2534 // No resize needed.
2535 if (ReservedSpace >= NumOps) return;
2536 } else if (NumOps == NumOperands) {
2537 if (ReservedSpace == NumOps) return;
2542 ReservedSpace = NumOps;
2543 Use *NewOps = new Use[NumOps];
2544 Use *OldOps = OperandList;
2545 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2546 NewOps[i].init(OldOps[i], this);
2550 OperandList = NewOps;
2554 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2555 return getSuccessor(idx);
2557 unsigned SwitchInst::getNumSuccessorsV() const {
2558 return getNumSuccessors();
2560 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2561 setSuccessor(idx, B);
2565 // Define these methods here so vtables don't get emitted into every translation
2566 // unit that uses these classes.
2568 GetElementPtrInst *GetElementPtrInst::clone() const {
2569 return new GetElementPtrInst(*this);
2572 BinaryOperator *BinaryOperator::clone() const {
2573 return create(getOpcode(), Ops[0], Ops[1]);
2576 FCmpInst* FCmpInst::clone() const {
2577 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2579 ICmpInst* ICmpInst::clone() const {
2580 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2583 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2584 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2585 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2586 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2587 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2588 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2589 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2590 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2591 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2592 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2593 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2594 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2595 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2596 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2597 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2598 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2599 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2600 CallInst *CallInst::clone() const { return new CallInst(*this); }
2601 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2602 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2604 ExtractElementInst *ExtractElementInst::clone() const {
2605 return new ExtractElementInst(*this);
2607 InsertElementInst *InsertElementInst::clone() const {
2608 return new InsertElementInst(*this);
2610 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2611 return new ShuffleVectorInst(*this);
2613 PHINode *PHINode::clone() const { return new PHINode(*this); }
2614 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2615 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2616 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2617 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2618 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2619 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}