1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/ConstantRange.h"
21 #include "llvm/Support/MathExtras.h"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 CallSite::CallSite(Instruction *C) {
29 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
32 unsigned CallSite::getCallingConv() const {
33 if (CallInst *CI = dyn_cast<CallInst>(I))
34 return CI->getCallingConv();
36 return cast<InvokeInst>(I)->getCallingConv();
38 void CallSite::setCallingConv(unsigned CC) {
39 if (CallInst *CI = dyn_cast<CallInst>(I))
40 CI->setCallingConv(CC);
42 cast<InvokeInst>(I)->setCallingConv(CC);
44 const PAListPtr &CallSite::getParamAttrs() const {
45 if (CallInst *CI = dyn_cast<CallInst>(I))
46 return CI->getParamAttrs();
48 return cast<InvokeInst>(I)->getParamAttrs();
50 void CallSite::setParamAttrs(const PAListPtr &PAL) {
51 if (CallInst *CI = dyn_cast<CallInst>(I))
52 CI->setParamAttrs(PAL);
54 cast<InvokeInst>(I)->setParamAttrs(PAL);
56 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
57 if (CallInst *CI = dyn_cast<CallInst>(I))
58 return CI->paramHasAttr(i, attr);
60 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
62 uint16_t CallSite::getParamAlignment(uint16_t i) const {
63 if (CallInst *CI = dyn_cast<CallInst>(I))
64 return CI->getParamAlignment(i);
66 return cast<InvokeInst>(I)->getParamAlignment(i);
69 bool CallSite::doesNotAccessMemory() const {
70 if (CallInst *CI = dyn_cast<CallInst>(I))
71 return CI->doesNotAccessMemory();
73 return cast<InvokeInst>(I)->doesNotAccessMemory();
75 bool CallSite::onlyReadsMemory() const {
76 if (CallInst *CI = dyn_cast<CallInst>(I))
77 return CI->onlyReadsMemory();
79 return cast<InvokeInst>(I)->onlyReadsMemory();
81 bool CallSite::doesNotThrow() const {
82 if (CallInst *CI = dyn_cast<CallInst>(I))
83 return CI->doesNotThrow();
85 return cast<InvokeInst>(I)->doesNotThrow();
87 void CallSite::setDoesNotThrow(bool doesNotThrow) {
88 if (CallInst *CI = dyn_cast<CallInst>(I))
89 CI->setDoesNotThrow(doesNotThrow);
91 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
94 bool CallSite::hasArgument(const Value *Arg) const {
95 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
101 //===----------------------------------------------------------------------===//
102 // TerminatorInst Class
103 //===----------------------------------------------------------------------===//
105 // Out of line virtual method, so the vtable, etc has a home.
106 TerminatorInst::~TerminatorInst() {
109 //===----------------------------------------------------------------------===//
110 // UnaryInstruction Class
111 //===----------------------------------------------------------------------===//
113 // Out of line virtual method, so the vtable, etc has a home.
114 UnaryInstruction::~UnaryInstruction() {
117 //===----------------------------------------------------------------------===//
119 //===----------------------------------------------------------------------===//
121 PHINode::PHINode(const PHINode &PN)
122 : Instruction(PN.getType(), Instruction::PHI,
123 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
124 ReservedSpace(PN.getNumOperands()) {
125 Use *OL = OperandList;
126 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
127 OL[i] = PN.getOperand(i);
128 OL[i+1] = PN.getOperand(i+1);
132 PHINode::~PHINode() {
133 dropHungoffUses(OperandList);
136 // removeIncomingValue - Remove an incoming value. This is useful if a
137 // predecessor basic block is deleted.
138 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
139 unsigned NumOps = getNumOperands();
140 Use *OL = OperandList;
141 assert(Idx*2 < NumOps && "BB not in PHI node!");
142 Value *Removed = OL[Idx*2];
144 // Move everything after this operand down.
146 // FIXME: we could just swap with the end of the list, then erase. However,
147 // client might not expect this to happen. The code as it is thrashes the
148 // use/def lists, which is kinda lame.
149 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
154 // Nuke the last value.
156 OL[NumOps-2+1].set(0);
157 NumOperands = NumOps-2;
159 // If the PHI node is dead, because it has zero entries, nuke it now.
160 if (NumOps == 2 && DeletePHIIfEmpty) {
161 // If anyone is using this PHI, make them use a dummy value instead...
162 replaceAllUsesWith(UndefValue::get(getType()));
168 /// resizeOperands - resize operands - This adjusts the length of the operands
169 /// list according to the following behavior:
170 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
171 /// of operation. This grows the number of ops by 1.5 times.
172 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
173 /// 3. If NumOps == NumOperands, trim the reserved space.
175 void PHINode::resizeOperands(unsigned NumOps) {
176 unsigned e = getNumOperands();
179 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
180 } else if (NumOps*2 > NumOperands) {
182 if (ReservedSpace >= NumOps) return;
183 } else if (NumOps == NumOperands) {
184 if (ReservedSpace == NumOps) return;
189 ReservedSpace = NumOps;
190 Use *OldOps = OperandList;
191 Use *NewOps = allocHungoffUses(NumOps);
192 for (unsigned i = 0; i != e; ++i) {
193 NewOps[i] = OldOps[i];
195 OperandList = NewOps;
196 if (OldOps) Use::zap(OldOps, OldOps + e, true);
199 /// hasConstantValue - If the specified PHI node always merges together the same
200 /// value, return the value, otherwise return null.
202 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
203 // If the PHI node only has one incoming value, eliminate the PHI node...
204 if (getNumIncomingValues() == 1) {
205 if (getIncomingValue(0) != this) // not X = phi X
206 return getIncomingValue(0);
208 return UndefValue::get(getType()); // Self cycle is dead.
211 // Otherwise if all of the incoming values are the same for the PHI, replace
212 // the PHI node with the incoming value.
215 bool HasUndefInput = false;
216 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
217 if (isa<UndefValue>(getIncomingValue(i))) {
218 HasUndefInput = true;
219 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
220 if (InVal && getIncomingValue(i) != InVal)
221 return 0; // Not the same, bail out.
223 InVal = getIncomingValue(i);
226 // The only case that could cause InVal to be null is if we have a PHI node
227 // that only has entries for itself. In this case, there is no entry into the
228 // loop, so kill the PHI.
230 if (InVal == 0) InVal = UndefValue::get(getType());
232 // If we have a PHI node like phi(X, undef, X), where X is defined by some
233 // instruction, we cannot always return X as the result of the PHI node. Only
234 // do this if X is not an instruction (thus it must dominate the PHI block),
235 // or if the client is prepared to deal with this possibility.
236 if (HasUndefInput && !AllowNonDominatingInstruction)
237 if (Instruction *IV = dyn_cast<Instruction>(InVal))
238 // If it's in the entry block, it dominates everything.
239 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
241 return 0; // Cannot guarantee that InVal dominates this PHINode.
243 // All of the incoming values are the same, return the value now.
248 //===----------------------------------------------------------------------===//
249 // CallInst Implementation
250 //===----------------------------------------------------------------------===//
252 CallInst::~CallInst() {
255 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
256 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
257 Use *OL = OperandList;
260 const FunctionType *FTy =
261 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
262 FTy = FTy; // silence warning.
264 assert((NumParams == FTy->getNumParams() ||
265 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
266 "Calling a function with bad signature!");
267 for (unsigned i = 0; i != NumParams; ++i) {
268 assert((i >= FTy->getNumParams() ||
269 FTy->getParamType(i) == Params[i]->getType()) &&
270 "Calling a function with a bad signature!");
275 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
276 assert(NumOperands == 3 && "NumOperands not set up?");
277 Use *OL = OperandList;
282 const FunctionType *FTy =
283 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
284 FTy = FTy; // silence warning.
286 assert((FTy->getNumParams() == 2 ||
287 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
288 "Calling a function with bad signature");
289 assert((0 >= FTy->getNumParams() ||
290 FTy->getParamType(0) == Actual1->getType()) &&
291 "Calling a function with a bad signature!");
292 assert((1 >= FTy->getNumParams() ||
293 FTy->getParamType(1) == Actual2->getType()) &&
294 "Calling a function with a bad signature!");
297 void CallInst::init(Value *Func, Value *Actual) {
298 assert(NumOperands == 2 && "NumOperands not set up?");
299 Use *OL = OperandList;
303 const FunctionType *FTy =
304 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
305 FTy = FTy; // silence warning.
307 assert((FTy->getNumParams() == 1 ||
308 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
309 "Calling a function with bad signature");
310 assert((0 == FTy->getNumParams() ||
311 FTy->getParamType(0) == Actual->getType()) &&
312 "Calling a function with a bad signature!");
315 void CallInst::init(Value *Func) {
316 assert(NumOperands == 1 && "NumOperands not set up?");
317 Use *OL = OperandList;
320 const FunctionType *FTy =
321 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
322 FTy = FTy; // silence warning.
324 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
327 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
328 Instruction *InsertBefore)
329 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
330 ->getElementType())->getReturnType(),
332 OperandTraits<CallInst>::op_end(this) - 2,
338 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
339 BasicBlock *InsertAtEnd)
340 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
341 ->getElementType())->getReturnType(),
343 OperandTraits<CallInst>::op_end(this) - 2,
348 CallInst::CallInst(Value *Func, const std::string &Name,
349 Instruction *InsertBefore)
350 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
351 ->getElementType())->getReturnType(),
353 OperandTraits<CallInst>::op_end(this) - 1,
359 CallInst::CallInst(Value *Func, const std::string &Name,
360 BasicBlock *InsertAtEnd)
361 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
362 ->getElementType())->getReturnType(),
364 OperandTraits<CallInst>::op_end(this) - 1,
370 CallInst::CallInst(const CallInst &CI)
371 : Instruction(CI.getType(), Instruction::Call,
372 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
373 CI.getNumOperands()) {
374 setParamAttrs(CI.getParamAttrs());
375 SubclassData = CI.SubclassData;
376 Use *OL = OperandList;
377 Use *InOL = CI.OperandList;
378 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
382 void CallInst::addParamAttr(unsigned i, ParameterAttributes attr) {
383 PAListPtr PAL = getParamAttrs();
384 PAL = PAL.addAttr(i, attr);
388 bool CallInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
389 if (ParamAttrs.paramHasAttr(i, attr))
391 if (const Function *F = getCalledFunction())
392 return F->paramHasAttr(i, attr);
396 void CallInst::setDoesNotThrow(bool doesNotThrow) {
397 PAListPtr PAL = getParamAttrs();
399 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
401 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
406 //===----------------------------------------------------------------------===//
407 // InvokeInst Implementation
408 //===----------------------------------------------------------------------===//
410 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
411 Value* const *Args, unsigned NumArgs) {
412 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
413 Use *OL = OperandList;
417 const FunctionType *FTy =
418 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
419 FTy = FTy; // silence warning.
421 assert(((NumArgs == FTy->getNumParams()) ||
422 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
423 "Calling a function with bad signature");
425 for (unsigned i = 0, e = NumArgs; i != e; i++) {
426 assert((i >= FTy->getNumParams() ||
427 FTy->getParamType(i) == Args[i]->getType()) &&
428 "Invoking a function with a bad signature!");
434 InvokeInst::InvokeInst(const InvokeInst &II)
435 : TerminatorInst(II.getType(), Instruction::Invoke,
436 OperandTraits<InvokeInst>::op_end(this)
437 - II.getNumOperands(),
438 II.getNumOperands()) {
439 setParamAttrs(II.getParamAttrs());
440 SubclassData = II.SubclassData;
441 Use *OL = OperandList, *InOL = II.OperandList;
442 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
446 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
447 return getSuccessor(idx);
449 unsigned InvokeInst::getNumSuccessorsV() const {
450 return getNumSuccessors();
452 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
453 return setSuccessor(idx, B);
456 bool InvokeInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
457 if (ParamAttrs.paramHasAttr(i, attr))
459 if (const Function *F = getCalledFunction())
460 return F->paramHasAttr(i, attr);
464 void InvokeInst::addParamAttr(unsigned i, ParameterAttributes attr) {
465 PAListPtr PAL = getParamAttrs();
466 PAL = PAL.addAttr(i, attr);
470 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
471 PAListPtr PAL = getParamAttrs();
473 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
475 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
480 //===----------------------------------------------------------------------===//
481 // ReturnInst Implementation
482 //===----------------------------------------------------------------------===//
484 ReturnInst::ReturnInst(const ReturnInst &RI)
485 : TerminatorInst(Type::VoidTy, Instruction::Ret,
486 OperandTraits<ReturnInst>::op_end(this)
487 - RI.getNumOperands(),
488 RI.getNumOperands()) {
489 unsigned N = RI.getNumOperands();
491 Op<0>() = RI.Op<0>();
493 Use *OL = OperandList;
494 for (unsigned i = 0; i < N; ++i)
495 OL[i] = RI.getOperand(i);
499 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
500 : TerminatorInst(Type::VoidTy, Instruction::Ret,
501 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
502 retVal != 0, InsertBefore) {
506 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
507 : TerminatorInst(Type::VoidTy, Instruction::Ret,
508 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
509 retVal != 0, InsertAtEnd) {
513 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
514 : TerminatorInst(Type::VoidTy, Instruction::Ret,
515 OperandTraits<ReturnInst>::op_end(this),
519 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
520 Instruction *InsertBefore)
521 : TerminatorInst(Type::VoidTy, Instruction::Ret,
522 OperandTraits<ReturnInst>::op_end(this) - N,
527 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
528 BasicBlock *InsertAtEnd)
529 : TerminatorInst(Type::VoidTy, Instruction::Ret,
530 OperandTraits<ReturnInst>::op_end(this) - N,
536 void ReturnInst::init(Value * const* retVals, unsigned N) {
537 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
540 if (NumOperands == 1) {
542 if (V->getType() == Type::VoidTy)
548 Use *OL = OperandList;
549 for (unsigned i = 0; i < NumOperands; ++i) {
550 Value *V = *retVals++;
551 assert(!isa<BasicBlock>(V) &&
552 "Cannot return basic block. Probably using the incorrect ctor");
557 unsigned ReturnInst::getNumSuccessorsV() const {
558 return getNumSuccessors();
561 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
562 /// emit the vtable for the class in this translation unit.
563 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
564 assert(0 && "ReturnInst has no successors!");
567 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
568 assert(0 && "ReturnInst has no successors!");
573 ReturnInst::~ReturnInst() {
576 //===----------------------------------------------------------------------===//
577 // UnwindInst Implementation
578 //===----------------------------------------------------------------------===//
580 UnwindInst::UnwindInst(Instruction *InsertBefore)
581 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
583 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
584 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
588 unsigned UnwindInst::getNumSuccessorsV() const {
589 return getNumSuccessors();
592 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
593 assert(0 && "UnwindInst has no successors!");
596 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
597 assert(0 && "UnwindInst has no successors!");
602 //===----------------------------------------------------------------------===//
603 // UnreachableInst Implementation
604 //===----------------------------------------------------------------------===//
606 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
607 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
609 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
610 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
613 unsigned UnreachableInst::getNumSuccessorsV() const {
614 return getNumSuccessors();
617 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
618 assert(0 && "UnwindInst has no successors!");
621 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
622 assert(0 && "UnwindInst has no successors!");
627 //===----------------------------------------------------------------------===//
628 // BranchInst Implementation
629 //===----------------------------------------------------------------------===//
631 void BranchInst::AssertOK() {
633 assert(getCondition()->getType() == Type::Int1Ty &&
634 "May only branch on boolean predicates!");
637 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
638 : TerminatorInst(Type::VoidTy, Instruction::Br,
639 OperandTraits<BranchInst>::op_end(this) - 1,
641 assert(IfTrue != 0 && "Branch destination may not be null!");
644 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
645 Instruction *InsertBefore)
646 : TerminatorInst(Type::VoidTy, Instruction::Br,
647 OperandTraits<BranchInst>::op_end(this) - 3,
657 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
658 : TerminatorInst(Type::VoidTy, Instruction::Br,
659 OperandTraits<BranchInst>::op_end(this) - 1,
661 assert(IfTrue != 0 && "Branch destination may not be null!");
665 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
666 BasicBlock *InsertAtEnd)
667 : TerminatorInst(Type::VoidTy, Instruction::Br,
668 OperandTraits<BranchInst>::op_end(this) - 3,
679 BranchInst::BranchInst(const BranchInst &BI) :
680 TerminatorInst(Type::VoidTy, Instruction::Br,
681 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
682 BI.getNumOperands()) {
683 OperandList[0] = BI.getOperand(0);
684 if (BI.getNumOperands() != 1) {
685 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
686 OperandList[1] = BI.getOperand(1);
687 OperandList[2] = BI.getOperand(2);
691 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
692 return getSuccessor(idx);
694 unsigned BranchInst::getNumSuccessorsV() const {
695 return getNumSuccessors();
697 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
698 setSuccessor(idx, B);
702 //===----------------------------------------------------------------------===//
703 // AllocationInst Implementation
704 //===----------------------------------------------------------------------===//
706 static Value *getAISize(Value *Amt) {
708 Amt = ConstantInt::get(Type::Int32Ty, 1);
710 assert(!isa<BasicBlock>(Amt) &&
711 "Passed basic block into allocation size parameter! Use other ctor");
712 assert(Amt->getType() == Type::Int32Ty &&
713 "Malloc/Allocation array size is not a 32-bit integer!");
718 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
719 unsigned Align, const std::string &Name,
720 Instruction *InsertBefore)
721 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
724 assert(Ty != Type::VoidTy && "Cannot allocate void!");
728 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
729 unsigned Align, const std::string &Name,
730 BasicBlock *InsertAtEnd)
731 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
734 assert(Ty != Type::VoidTy && "Cannot allocate void!");
738 // Out of line virtual method, so the vtable, etc has a home.
739 AllocationInst::~AllocationInst() {
742 void AllocationInst::setAlignment(unsigned Align) {
743 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
744 SubclassData = Log2_32(Align) + 1;
745 assert(getAlignment() == Align && "Alignment representation error!");
748 bool AllocationInst::isArrayAllocation() const {
749 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
750 return CI->getZExtValue() != 1;
754 const Type *AllocationInst::getAllocatedType() const {
755 return getType()->getElementType();
758 AllocaInst::AllocaInst(const AllocaInst &AI)
759 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
760 Instruction::Alloca, AI.getAlignment()) {
763 MallocInst::MallocInst(const MallocInst &MI)
764 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
765 Instruction::Malloc, MI.getAlignment()) {
768 //===----------------------------------------------------------------------===//
769 // FreeInst Implementation
770 //===----------------------------------------------------------------------===//
772 void FreeInst::AssertOK() {
773 assert(isa<PointerType>(getOperand(0)->getType()) &&
774 "Can not free something of nonpointer type!");
777 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
778 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
782 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
783 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
788 //===----------------------------------------------------------------------===//
789 // LoadInst Implementation
790 //===----------------------------------------------------------------------===//
792 void LoadInst::AssertOK() {
793 assert(isa<PointerType>(getOperand(0)->getType()) &&
794 "Ptr must have pointer type.");
797 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
798 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
799 Load, Ptr, InsertBef) {
806 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
807 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
808 Load, Ptr, InsertAE) {
815 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
816 Instruction *InsertBef)
817 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
818 Load, Ptr, InsertBef) {
819 setVolatile(isVolatile);
825 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
826 unsigned Align, Instruction *InsertBef)
827 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
828 Load, Ptr, InsertBef) {
829 setVolatile(isVolatile);
835 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
836 unsigned Align, BasicBlock *InsertAE)
837 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
838 Load, Ptr, InsertAE) {
839 setVolatile(isVolatile);
845 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
846 BasicBlock *InsertAE)
847 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
848 Load, Ptr, InsertAE) {
849 setVolatile(isVolatile);
857 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
858 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
859 Load, Ptr, InsertBef) {
863 if (Name && Name[0]) setName(Name);
866 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
867 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
868 Load, Ptr, InsertAE) {
872 if (Name && Name[0]) setName(Name);
875 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
876 Instruction *InsertBef)
877 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
878 Load, Ptr, InsertBef) {
879 setVolatile(isVolatile);
882 if (Name && Name[0]) setName(Name);
885 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
886 BasicBlock *InsertAE)
887 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
888 Load, Ptr, InsertAE) {
889 setVolatile(isVolatile);
892 if (Name && Name[0]) setName(Name);
895 void LoadInst::setAlignment(unsigned Align) {
896 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
897 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
900 //===----------------------------------------------------------------------===//
901 // StoreInst Implementation
902 //===----------------------------------------------------------------------===//
904 void StoreInst::AssertOK() {
905 assert(isa<PointerType>(getOperand(1)->getType()) &&
906 "Ptr must have pointer type!");
907 assert(getOperand(0)->getType() ==
908 cast<PointerType>(getOperand(1)->getType())->getElementType()
909 && "Ptr must be a pointer to Val type!");
913 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
914 : Instruction(Type::VoidTy, Store,
915 OperandTraits<StoreInst>::op_begin(this),
916 OperandTraits<StoreInst>::operands(this),
925 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
926 : Instruction(Type::VoidTy, Store,
927 OperandTraits<StoreInst>::op_begin(this),
928 OperandTraits<StoreInst>::operands(this),
937 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
938 Instruction *InsertBefore)
939 : Instruction(Type::VoidTy, Store,
940 OperandTraits<StoreInst>::op_begin(this),
941 OperandTraits<StoreInst>::operands(this),
945 setVolatile(isVolatile);
950 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
951 unsigned Align, Instruction *InsertBefore)
952 : Instruction(Type::VoidTy, Store,
953 OperandTraits<StoreInst>::op_begin(this),
954 OperandTraits<StoreInst>::operands(this),
958 setVolatile(isVolatile);
963 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
964 unsigned Align, BasicBlock *InsertAtEnd)
965 : Instruction(Type::VoidTy, Store,
966 OperandTraits<StoreInst>::op_begin(this),
967 OperandTraits<StoreInst>::operands(this),
971 setVolatile(isVolatile);
976 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
977 BasicBlock *InsertAtEnd)
978 : Instruction(Type::VoidTy, Store,
979 OperandTraits<StoreInst>::op_begin(this),
980 OperandTraits<StoreInst>::operands(this),
984 setVolatile(isVolatile);
989 void StoreInst::setAlignment(unsigned Align) {
990 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
991 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
994 //===----------------------------------------------------------------------===//
995 // GetElementPtrInst Implementation
996 //===----------------------------------------------------------------------===//
998 static unsigned retrieveAddrSpace(const Value *Val) {
999 return cast<PointerType>(Val->getType())->getAddressSpace();
1002 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1003 const std::string &Name) {
1004 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1005 Use *OL = OperandList;
1008 for (unsigned i = 0; i != NumIdx; ++i)
1014 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1015 assert(NumOperands == 2 && "NumOperands not initialized?");
1016 Use *OL = OperandList;
1023 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1024 : Instruction(GEPI.getType(), GetElementPtr,
1025 OperandTraits<GetElementPtrInst>::op_end(this)
1026 - GEPI.getNumOperands(),
1027 GEPI.getNumOperands()) {
1028 Use *OL = OperandList;
1029 Use *GEPIOL = GEPI.OperandList;
1030 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1034 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1035 const std::string &Name, Instruction *InBe)
1036 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1037 retrieveAddrSpace(Ptr)),
1039 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1041 init(Ptr, Idx, Name);
1044 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1045 const std::string &Name, BasicBlock *IAE)
1046 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1047 retrieveAddrSpace(Ptr)),
1049 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1051 init(Ptr, Idx, Name);
1054 // getIndexedType - Returns the type of the element that would be loaded with
1055 // a load instruction with the specified parameters.
1057 // A null type is returned if the indices are invalid for the specified
1060 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1063 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1064 if (!PTy) return 0; // Type isn't a pointer type!
1065 const Type *Agg = PTy->getElementType();
1067 // Handle the special case of the empty set index set...
1071 unsigned CurIdx = 1;
1072 for (; CurIdx != NumIdx; ++CurIdx) {
1073 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1074 if (!CT || isa<PointerType>(CT)) return 0;
1075 Value *Index = Idxs[CurIdx];
1076 if (!CT->indexValid(Index)) return 0;
1077 Agg = CT->getTypeAtIndex(Index);
1079 // If the new type forwards to another type, then it is in the middle
1080 // of being refined to another type (and hence, may have dropped all
1081 // references to what it was using before). So, use the new forwarded
1083 if (const Type *Ty = Agg->getForwardedType())
1086 return CurIdx == NumIdx ? Agg : 0;
1089 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1090 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1091 if (!PTy) return 0; // Type isn't a pointer type!
1093 // Check the pointer index.
1094 if (!PTy->indexValid(Idx)) return 0;
1096 return PTy->getElementType();
1100 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1101 /// zeros. If so, the result pointer and the first operand have the same
1102 /// value, just potentially different types.
1103 bool GetElementPtrInst::hasAllZeroIndices() const {
1104 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1105 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1106 if (!CI->isZero()) return false;
1114 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1115 /// constant integers. If so, the result pointer and the first operand have
1116 /// a constant offset between them.
1117 bool GetElementPtrInst::hasAllConstantIndices() const {
1118 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1119 if (!isa<ConstantInt>(getOperand(i)))
1126 //===----------------------------------------------------------------------===//
1127 // ExtractElementInst Implementation
1128 //===----------------------------------------------------------------------===//
1130 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1131 const std::string &Name,
1132 Instruction *InsertBef)
1133 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1135 OperandTraits<ExtractElementInst>::op_begin(this),
1137 assert(isValidOperands(Val, Index) &&
1138 "Invalid extractelement instruction operands!");
1144 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1145 const std::string &Name,
1146 Instruction *InsertBef)
1147 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1149 OperandTraits<ExtractElementInst>::op_begin(this),
1151 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1152 assert(isValidOperands(Val, Index) &&
1153 "Invalid extractelement instruction operands!");
1160 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1161 const std::string &Name,
1162 BasicBlock *InsertAE)
1163 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1165 OperandTraits<ExtractElementInst>::op_begin(this),
1167 assert(isValidOperands(Val, Index) &&
1168 "Invalid extractelement instruction operands!");
1175 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1176 const std::string &Name,
1177 BasicBlock *InsertAE)
1178 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1180 OperandTraits<ExtractElementInst>::op_begin(this),
1182 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1183 assert(isValidOperands(Val, Index) &&
1184 "Invalid extractelement instruction operands!");
1192 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1193 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1199 //===----------------------------------------------------------------------===//
1200 // InsertElementInst Implementation
1201 //===----------------------------------------------------------------------===//
1203 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1204 : Instruction(IE.getType(), InsertElement,
1205 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1206 Op<0>() = IE.Op<0>();
1207 Op<1>() = IE.Op<1>();
1208 Op<2>() = IE.Op<2>();
1210 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1211 const std::string &Name,
1212 Instruction *InsertBef)
1213 : Instruction(Vec->getType(), InsertElement,
1214 OperandTraits<InsertElementInst>::op_begin(this),
1216 assert(isValidOperands(Vec, Elt, Index) &&
1217 "Invalid insertelement instruction operands!");
1224 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1225 const std::string &Name,
1226 Instruction *InsertBef)
1227 : Instruction(Vec->getType(), InsertElement,
1228 OperandTraits<InsertElementInst>::op_begin(this),
1230 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1231 assert(isValidOperands(Vec, Elt, Index) &&
1232 "Invalid insertelement instruction operands!");
1240 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1241 const std::string &Name,
1242 BasicBlock *InsertAE)
1243 : Instruction(Vec->getType(), InsertElement,
1244 OperandTraits<InsertElementInst>::op_begin(this),
1246 assert(isValidOperands(Vec, Elt, Index) &&
1247 "Invalid insertelement instruction operands!");
1255 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1256 const std::string &Name,
1257 BasicBlock *InsertAE)
1258 : Instruction(Vec->getType(), InsertElement,
1259 OperandTraits<InsertElementInst>::op_begin(this),
1261 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1262 assert(isValidOperands(Vec, Elt, Index) &&
1263 "Invalid insertelement instruction operands!");
1271 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1272 const Value *Index) {
1273 if (!isa<VectorType>(Vec->getType()))
1274 return false; // First operand of insertelement must be vector type.
1276 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1277 return false;// Second operand of insertelement must be vector element type.
1279 if (Index->getType() != Type::Int32Ty)
1280 return false; // Third operand of insertelement must be uint.
1285 //===----------------------------------------------------------------------===//
1286 // ShuffleVectorInst Implementation
1287 //===----------------------------------------------------------------------===//
1289 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1290 : Instruction(SV.getType(), ShuffleVector,
1291 OperandTraits<ShuffleVectorInst>::op_begin(this),
1292 OperandTraits<ShuffleVectorInst>::operands(this)) {
1293 Op<0>() = SV.Op<0>();
1294 Op<1>() = SV.Op<1>();
1295 Op<2>() = SV.Op<2>();
1298 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1299 const std::string &Name,
1300 Instruction *InsertBefore)
1301 : Instruction(V1->getType(), ShuffleVector,
1302 OperandTraits<ShuffleVectorInst>::op_begin(this),
1303 OperandTraits<ShuffleVectorInst>::operands(this),
1305 assert(isValidOperands(V1, V2, Mask) &&
1306 "Invalid shuffle vector instruction operands!");
1313 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1314 const std::string &Name,
1315 BasicBlock *InsertAtEnd)
1316 : Instruction(V1->getType(), ShuffleVector,
1317 OperandTraits<ShuffleVectorInst>::op_begin(this),
1318 OperandTraits<ShuffleVectorInst>::operands(this),
1320 assert(isValidOperands(V1, V2, Mask) &&
1321 "Invalid shuffle vector instruction operands!");
1329 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1330 const Value *Mask) {
1331 if (!isa<VectorType>(V1->getType()) ||
1332 V1->getType() != V2->getType())
1335 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1336 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1337 MaskTy->getElementType() != Type::Int32Ty ||
1338 MaskTy->getNumElements() !=
1339 cast<VectorType>(V1->getType())->getNumElements())
1344 /// getMaskValue - Return the index from the shuffle mask for the specified
1345 /// output result. This is either -1 if the element is undef or a number less
1346 /// than 2*numelements.
1347 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1348 const Constant *Mask = cast<Constant>(getOperand(2));
1349 if (isa<UndefValue>(Mask)) return -1;
1350 if (isa<ConstantAggregateZero>(Mask)) return 0;
1351 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1352 assert(i < MaskCV->getNumOperands() && "Index out of range");
1354 if (isa<UndefValue>(MaskCV->getOperand(i)))
1356 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1359 //===----------------------------------------------------------------------===//
1360 // InsertValueInst Class
1361 //===----------------------------------------------------------------------===//
1363 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1364 unsigned NumIdx, const std::string &Name) {
1365 assert(NumOperands == 2 && "NumOperands not initialized?");
1369 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1373 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1374 const std::string &Name) {
1375 assert(NumOperands == 2 && "NumOperands not initialized?");
1379 Indices.push_back(Idx);
1383 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1384 : Instruction(IVI.getType(), InsertValue,
1385 OperandTraits<InsertValueInst>::op_begin(this), 2),
1386 Indices(IVI.Indices) {
1389 InsertValueInst::InsertValueInst(Value *Agg,
1392 const std::string &Name,
1393 Instruction *InsertBefore)
1394 : Instruction(Agg->getType(), InsertValue,
1395 OperandTraits<InsertValueInst>::op_begin(this),
1397 init(Agg, Val, Idx, Name);
1400 InsertValueInst::InsertValueInst(Value *Agg,
1403 const std::string &Name,
1404 BasicBlock *InsertAtEnd)
1405 : Instruction(Agg->getType(), InsertValue,
1406 OperandTraits<InsertValueInst>::op_begin(this),
1408 init(Agg, Val, Idx, Name);
1411 //===----------------------------------------------------------------------===//
1412 // ExtractValueInst Class
1413 //===----------------------------------------------------------------------===//
1415 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1416 const std::string &Name) {
1417 assert(NumOperands == 1 && "NumOperands not initialized?");
1419 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1423 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
1424 assert(NumOperands == 1 && "NumOperands not initialized?");
1426 Indices.push_back(Idx);
1430 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1431 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1432 Indices(EVI.Indices) {
1435 // getIndexedType - Returns the type of the element that would be extracted
1436 // with an extractvalue instruction with the specified parameters.
1438 // A null type is returned if the indices are invalid for the specified
1441 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1442 const unsigned *Idxs,
1444 unsigned CurIdx = 0;
1445 for (; CurIdx != NumIdx; ++CurIdx) {
1446 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1447 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1448 unsigned Index = Idxs[CurIdx];
1449 if (!CT->indexValid(Index)) return 0;
1450 Agg = CT->getTypeAtIndex(Index);
1452 // If the new type forwards to another type, then it is in the middle
1453 // of being refined to another type (and hence, may have dropped all
1454 // references to what it was using before). So, use the new forwarded
1456 if (const Type *Ty = Agg->getForwardedType())
1459 return CurIdx == NumIdx ? Agg : 0;
1462 ExtractValueInst::ExtractValueInst(Value *Agg,
1464 const std::string &Name,
1465 BasicBlock *InsertAtEnd)
1466 : UnaryInstruction(checkType(getIndexedType(Agg->getType(), &Idx, 1)),
1467 ExtractValue, Agg, InsertAtEnd) {
1471 ExtractValueInst::ExtractValueInst(Value *Agg,
1473 const std::string &Name,
1474 Instruction *InsertBefore)
1475 : UnaryInstruction(checkType(getIndexedType(Agg->getType(), &Idx, 1)),
1476 ExtractValue, Agg, InsertBefore) {
1480 //===----------------------------------------------------------------------===//
1481 // BinaryOperator Class
1482 //===----------------------------------------------------------------------===//
1484 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1485 const Type *Ty, const std::string &Name,
1486 Instruction *InsertBefore)
1487 : Instruction(Ty, iType,
1488 OperandTraits<BinaryOperator>::op_begin(this),
1489 OperandTraits<BinaryOperator>::operands(this),
1497 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1498 const Type *Ty, const std::string &Name,
1499 BasicBlock *InsertAtEnd)
1500 : Instruction(Ty, iType,
1501 OperandTraits<BinaryOperator>::op_begin(this),
1502 OperandTraits<BinaryOperator>::operands(this),
1511 void BinaryOperator::init(BinaryOps iType) {
1512 Value *LHS = getOperand(0), *RHS = getOperand(1);
1513 LHS = LHS; RHS = RHS; // Silence warnings.
1514 assert(LHS->getType() == RHS->getType() &&
1515 "Binary operator operand types must match!");
1520 assert(getType() == LHS->getType() &&
1521 "Arithmetic operation should return same type as operands!");
1522 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1523 isa<VectorType>(getType())) &&
1524 "Tried to create an arithmetic operation on a non-arithmetic type!");
1528 assert(getType() == LHS->getType() &&
1529 "Arithmetic operation should return same type as operands!");
1530 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1531 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1532 "Incorrect operand type (not integer) for S/UDIV");
1535 assert(getType() == LHS->getType() &&
1536 "Arithmetic operation should return same type as operands!");
1537 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1538 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1539 && "Incorrect operand type (not floating point) for FDIV");
1543 assert(getType() == LHS->getType() &&
1544 "Arithmetic operation should return same type as operands!");
1545 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1546 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1547 "Incorrect operand type (not integer) for S/UREM");
1550 assert(getType() == LHS->getType() &&
1551 "Arithmetic operation should return same type as operands!");
1552 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1553 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1554 && "Incorrect operand type (not floating point) for FREM");
1559 assert(getType() == LHS->getType() &&
1560 "Shift operation should return same type as operands!");
1561 assert(getType()->isInteger() &&
1562 "Shift operation requires integer operands");
1566 assert(getType() == LHS->getType() &&
1567 "Logical operation should return same type as operands!");
1568 assert((getType()->isInteger() ||
1569 (isa<VectorType>(getType()) &&
1570 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1571 "Tried to create a logical operation on a non-integral type!");
1579 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1580 const std::string &Name,
1581 Instruction *InsertBefore) {
1582 assert(S1->getType() == S2->getType() &&
1583 "Cannot create binary operator with two operands of differing type!");
1584 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1587 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1588 const std::string &Name,
1589 BasicBlock *InsertAtEnd) {
1590 BinaryOperator *Res = Create(Op, S1, S2, Name);
1591 InsertAtEnd->getInstList().push_back(Res);
1595 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1596 Instruction *InsertBefore) {
1597 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1598 return new BinaryOperator(Instruction::Sub,
1600 Op->getType(), Name, InsertBefore);
1603 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1604 BasicBlock *InsertAtEnd) {
1605 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1606 return new BinaryOperator(Instruction::Sub,
1608 Op->getType(), Name, InsertAtEnd);
1611 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1612 Instruction *InsertBefore) {
1614 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1615 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1616 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1618 C = ConstantInt::getAllOnesValue(Op->getType());
1621 return new BinaryOperator(Instruction::Xor, Op, C,
1622 Op->getType(), Name, InsertBefore);
1625 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1626 BasicBlock *InsertAtEnd) {
1628 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1629 // Create a vector of all ones values.
1630 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1632 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1634 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1637 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1638 Op->getType(), Name, InsertAtEnd);
1642 // isConstantAllOnes - Helper function for several functions below
1643 static inline bool isConstantAllOnes(const Value *V) {
1644 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1645 return CI->isAllOnesValue();
1646 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1647 return CV->isAllOnesValue();
1651 bool BinaryOperator::isNeg(const Value *V) {
1652 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1653 if (Bop->getOpcode() == Instruction::Sub)
1654 return Bop->getOperand(0) ==
1655 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1659 bool BinaryOperator::isNot(const Value *V) {
1660 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1661 return (Bop->getOpcode() == Instruction::Xor &&
1662 (isConstantAllOnes(Bop->getOperand(1)) ||
1663 isConstantAllOnes(Bop->getOperand(0))));
1667 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1668 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1669 return cast<BinaryOperator>(BinOp)->getOperand(1);
1672 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1673 return getNegArgument(const_cast<Value*>(BinOp));
1676 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1677 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1678 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1679 Value *Op0 = BO->getOperand(0);
1680 Value *Op1 = BO->getOperand(1);
1681 if (isConstantAllOnes(Op0)) return Op1;
1683 assert(isConstantAllOnes(Op1));
1687 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1688 return getNotArgument(const_cast<Value*>(BinOp));
1692 // swapOperands - Exchange the two operands to this instruction. This
1693 // instruction is safe to use on any binary instruction and does not
1694 // modify the semantics of the instruction. If the instruction is
1695 // order dependent (SetLT f.e.) the opcode is changed.
1697 bool BinaryOperator::swapOperands() {
1698 if (!isCommutative())
1699 return true; // Can't commute operands
1700 Op<0>().swap(Op<1>());
1704 //===----------------------------------------------------------------------===//
1706 //===----------------------------------------------------------------------===//
1708 // Just determine if this cast only deals with integral->integral conversion.
1709 bool CastInst::isIntegerCast() const {
1710 switch (getOpcode()) {
1711 default: return false;
1712 case Instruction::ZExt:
1713 case Instruction::SExt:
1714 case Instruction::Trunc:
1716 case Instruction::BitCast:
1717 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1721 bool CastInst::isLosslessCast() const {
1722 // Only BitCast can be lossless, exit fast if we're not BitCast
1723 if (getOpcode() != Instruction::BitCast)
1726 // Identity cast is always lossless
1727 const Type* SrcTy = getOperand(0)->getType();
1728 const Type* DstTy = getType();
1732 // Pointer to pointer is always lossless.
1733 if (isa<PointerType>(SrcTy))
1734 return isa<PointerType>(DstTy);
1735 return false; // Other types have no identity values
1738 /// This function determines if the CastInst does not require any bits to be
1739 /// changed in order to effect the cast. Essentially, it identifies cases where
1740 /// no code gen is necessary for the cast, hence the name no-op cast. For
1741 /// example, the following are all no-op casts:
1742 /// # bitcast i32* %x to i8*
1743 /// # bitcast <2 x i32> %x to <4 x i16>
1744 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1745 /// @brief Determine if a cast is a no-op.
1746 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1747 switch (getOpcode()) {
1749 assert(!"Invalid CastOp");
1750 case Instruction::Trunc:
1751 case Instruction::ZExt:
1752 case Instruction::SExt:
1753 case Instruction::FPTrunc:
1754 case Instruction::FPExt:
1755 case Instruction::UIToFP:
1756 case Instruction::SIToFP:
1757 case Instruction::FPToUI:
1758 case Instruction::FPToSI:
1759 return false; // These always modify bits
1760 case Instruction::BitCast:
1761 return true; // BitCast never modifies bits.
1762 case Instruction::PtrToInt:
1763 return IntPtrTy->getPrimitiveSizeInBits() ==
1764 getType()->getPrimitiveSizeInBits();
1765 case Instruction::IntToPtr:
1766 return IntPtrTy->getPrimitiveSizeInBits() ==
1767 getOperand(0)->getType()->getPrimitiveSizeInBits();
1771 /// This function determines if a pair of casts can be eliminated and what
1772 /// opcode should be used in the elimination. This assumes that there are two
1773 /// instructions like this:
1774 /// * %F = firstOpcode SrcTy %x to MidTy
1775 /// * %S = secondOpcode MidTy %F to DstTy
1776 /// The function returns a resultOpcode so these two casts can be replaced with:
1777 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1778 /// If no such cast is permited, the function returns 0.
1779 unsigned CastInst::isEliminableCastPair(
1780 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1781 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1783 // Define the 144 possibilities for these two cast instructions. The values
1784 // in this matrix determine what to do in a given situation and select the
1785 // case in the switch below. The rows correspond to firstOp, the columns
1786 // correspond to secondOp. In looking at the table below, keep in mind
1787 // the following cast properties:
1789 // Size Compare Source Destination
1790 // Operator Src ? Size Type Sign Type Sign
1791 // -------- ------------ ------------------- ---------------------
1792 // TRUNC > Integer Any Integral Any
1793 // ZEXT < Integral Unsigned Integer Any
1794 // SEXT < Integral Signed Integer Any
1795 // FPTOUI n/a FloatPt n/a Integral Unsigned
1796 // FPTOSI n/a FloatPt n/a Integral Signed
1797 // UITOFP n/a Integral Unsigned FloatPt n/a
1798 // SITOFP n/a Integral Signed FloatPt n/a
1799 // FPTRUNC > FloatPt n/a FloatPt n/a
1800 // FPEXT < FloatPt n/a FloatPt n/a
1801 // PTRTOINT n/a Pointer n/a Integral Unsigned
1802 // INTTOPTR n/a Integral Unsigned Pointer n/a
1803 // BITCONVERT = FirstClass n/a FirstClass n/a
1805 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1806 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1807 // into "fptoui double to ulong", but this loses information about the range
1808 // of the produced value (we no longer know the top-part is all zeros).
1809 // Further this conversion is often much more expensive for typical hardware,
1810 // and causes issues when building libgcc. We disallow fptosi+sext for the
1812 const unsigned numCastOps =
1813 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1814 static const uint8_t CastResults[numCastOps][numCastOps] = {
1815 // T F F U S F F P I B -+
1816 // R Z S P P I I T P 2 N T |
1817 // U E E 2 2 2 2 R E I T C +- secondOp
1818 // N X X U S F F N X N 2 V |
1819 // C T T I I P P C T T P T -+
1820 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1821 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1822 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1823 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1824 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1825 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1826 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1827 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1828 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1829 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1830 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1831 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1834 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1835 [secondOp-Instruction::CastOpsBegin];
1838 // categorically disallowed
1841 // allowed, use first cast's opcode
1844 // allowed, use second cast's opcode
1847 // no-op cast in second op implies firstOp as long as the DestTy
1849 if (DstTy->isInteger())
1853 // no-op cast in second op implies firstOp as long as the DestTy
1854 // is floating point
1855 if (DstTy->isFloatingPoint())
1859 // no-op cast in first op implies secondOp as long as the SrcTy
1861 if (SrcTy->isInteger())
1865 // no-op cast in first op implies secondOp as long as the SrcTy
1866 // is a floating point
1867 if (SrcTy->isFloatingPoint())
1871 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1872 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1873 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1874 if (MidSize >= PtrSize)
1875 return Instruction::BitCast;
1879 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1880 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1881 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1882 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1883 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1884 if (SrcSize == DstSize)
1885 return Instruction::BitCast;
1886 else if (SrcSize < DstSize)
1890 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1891 return Instruction::ZExt;
1893 // fpext followed by ftrunc is allowed if the bit size returned to is
1894 // the same as the original, in which case its just a bitcast
1896 return Instruction::BitCast;
1897 return 0; // If the types are not the same we can't eliminate it.
1899 // bitcast followed by ptrtoint is allowed as long as the bitcast
1900 // is a pointer to pointer cast.
1901 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1905 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1906 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1910 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1911 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1912 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1913 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1914 if (SrcSize <= PtrSize && SrcSize == DstSize)
1915 return Instruction::BitCast;
1919 // cast combination can't happen (error in input). This is for all cases
1920 // where the MidTy is not the same for the two cast instructions.
1921 assert(!"Invalid Cast Combination");
1924 assert(!"Error in CastResults table!!!");
1930 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1931 const std::string &Name, Instruction *InsertBefore) {
1932 // Construct and return the appropriate CastInst subclass
1934 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1935 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1936 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1937 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1938 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1939 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1940 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1941 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1942 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1943 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1944 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1945 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1947 assert(!"Invalid opcode provided");
1952 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1953 const std::string &Name, BasicBlock *InsertAtEnd) {
1954 // Construct and return the appropriate CastInst subclass
1956 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1957 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1958 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1959 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1960 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1961 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1962 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1963 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1964 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1965 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1966 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1967 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1969 assert(!"Invalid opcode provided");
1974 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1975 const std::string &Name,
1976 Instruction *InsertBefore) {
1977 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1978 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1979 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1982 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1983 const std::string &Name,
1984 BasicBlock *InsertAtEnd) {
1985 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1986 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1987 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1990 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1991 const std::string &Name,
1992 Instruction *InsertBefore) {
1993 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1994 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1995 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
1998 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1999 const std::string &Name,
2000 BasicBlock *InsertAtEnd) {
2001 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2002 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2003 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2006 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2007 const std::string &Name,
2008 Instruction *InsertBefore) {
2009 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2010 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2011 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2014 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2015 const std::string &Name,
2016 BasicBlock *InsertAtEnd) {
2017 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2018 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2019 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2022 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2023 const std::string &Name,
2024 BasicBlock *InsertAtEnd) {
2025 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2026 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2029 if (Ty->isInteger())
2030 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2031 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2034 /// @brief Create a BitCast or a PtrToInt cast instruction
2035 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2036 const std::string &Name,
2037 Instruction *InsertBefore) {
2038 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2039 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2042 if (Ty->isInteger())
2043 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2044 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2047 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2048 bool isSigned, const std::string &Name,
2049 Instruction *InsertBefore) {
2050 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2051 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2052 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2053 Instruction::CastOps opcode =
2054 (SrcBits == DstBits ? Instruction::BitCast :
2055 (SrcBits > DstBits ? Instruction::Trunc :
2056 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2057 return Create(opcode, C, Ty, Name, InsertBefore);
2060 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2061 bool isSigned, const std::string &Name,
2062 BasicBlock *InsertAtEnd) {
2063 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2064 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2065 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2066 Instruction::CastOps opcode =
2067 (SrcBits == DstBits ? Instruction::BitCast :
2068 (SrcBits > DstBits ? Instruction::Trunc :
2069 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2070 return Create(opcode, C, Ty, Name, InsertAtEnd);
2073 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2074 const std::string &Name,
2075 Instruction *InsertBefore) {
2076 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2078 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2079 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2080 Instruction::CastOps opcode =
2081 (SrcBits == DstBits ? Instruction::BitCast :
2082 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2083 return Create(opcode, C, Ty, Name, InsertBefore);
2086 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2087 const std::string &Name,
2088 BasicBlock *InsertAtEnd) {
2089 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2091 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2092 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2093 Instruction::CastOps opcode =
2094 (SrcBits == DstBits ? Instruction::BitCast :
2095 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2096 return Create(opcode, C, Ty, Name, InsertAtEnd);
2099 // Check whether it is valid to call getCastOpcode for these types.
2100 // This routine must be kept in sync with getCastOpcode.
2101 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2102 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2105 if (SrcTy == DestTy)
2108 // Get the bit sizes, we'll need these
2109 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2110 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2112 // Run through the possibilities ...
2113 if (DestTy->isInteger()) { // Casting to integral
2114 if (SrcTy->isInteger()) { // Casting from integral
2116 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2118 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2119 // Casting from vector
2120 return DestBits == PTy->getBitWidth();
2121 } else { // Casting from something else
2122 return isa<PointerType>(SrcTy);
2124 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2125 if (SrcTy->isInteger()) { // Casting from integral
2127 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2129 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2130 // Casting from vector
2131 return DestBits == PTy->getBitWidth();
2132 } else { // Casting from something else
2135 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2136 // Casting to vector
2137 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2138 // Casting from vector
2139 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2140 } else { // Casting from something else
2141 return DestPTy->getBitWidth() == SrcBits;
2143 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2144 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2146 } else if (SrcTy->isInteger()) { // Casting from integral
2148 } else { // Casting from something else
2151 } else { // Casting to something else
2156 // Provide a way to get a "cast" where the cast opcode is inferred from the
2157 // types and size of the operand. This, basically, is a parallel of the
2158 // logic in the castIsValid function below. This axiom should hold:
2159 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2160 // should not assert in castIsValid. In other words, this produces a "correct"
2161 // casting opcode for the arguments passed to it.
2162 // This routine must be kept in sync with isCastable.
2163 Instruction::CastOps
2164 CastInst::getCastOpcode(
2165 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2166 // Get the bit sizes, we'll need these
2167 const Type *SrcTy = Src->getType();
2168 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2169 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2171 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2172 "Only first class types are castable!");
2174 // Run through the possibilities ...
2175 if (DestTy->isInteger()) { // Casting to integral
2176 if (SrcTy->isInteger()) { // Casting from integral
2177 if (DestBits < SrcBits)
2178 return Trunc; // int -> smaller int
2179 else if (DestBits > SrcBits) { // its an extension
2181 return SExt; // signed -> SEXT
2183 return ZExt; // unsigned -> ZEXT
2185 return BitCast; // Same size, No-op cast
2187 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2189 return FPToSI; // FP -> sint
2191 return FPToUI; // FP -> uint
2192 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2193 assert(DestBits == PTy->getBitWidth() &&
2194 "Casting vector to integer of different width");
2195 return BitCast; // Same size, no-op cast
2197 assert(isa<PointerType>(SrcTy) &&
2198 "Casting from a value that is not first-class type");
2199 return PtrToInt; // ptr -> int
2201 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2202 if (SrcTy->isInteger()) { // Casting from integral
2204 return SIToFP; // sint -> FP
2206 return UIToFP; // uint -> FP
2207 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2208 if (DestBits < SrcBits) {
2209 return FPTrunc; // FP -> smaller FP
2210 } else if (DestBits > SrcBits) {
2211 return FPExt; // FP -> larger FP
2213 return BitCast; // same size, no-op cast
2215 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2216 assert(DestBits == PTy->getBitWidth() &&
2217 "Casting vector to floating point of different width");
2218 return BitCast; // same size, no-op cast
2220 assert(0 && "Casting pointer or non-first class to float");
2222 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2223 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2224 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2225 "Casting vector to vector of different widths");
2226 return BitCast; // vector -> vector
2227 } else if (DestPTy->getBitWidth() == SrcBits) {
2228 return BitCast; // float/int -> vector
2230 assert(!"Illegal cast to vector (wrong type or size)");
2232 } else if (isa<PointerType>(DestTy)) {
2233 if (isa<PointerType>(SrcTy)) {
2234 return BitCast; // ptr -> ptr
2235 } else if (SrcTy->isInteger()) {
2236 return IntToPtr; // int -> ptr
2238 assert(!"Casting pointer to other than pointer or int");
2241 assert(!"Casting to type that is not first-class");
2244 // If we fall through to here we probably hit an assertion cast above
2245 // and assertions are not turned on. Anything we return is an error, so
2246 // BitCast is as good a choice as any.
2250 //===----------------------------------------------------------------------===//
2251 // CastInst SubClass Constructors
2252 //===----------------------------------------------------------------------===//
2254 /// Check that the construction parameters for a CastInst are correct. This
2255 /// could be broken out into the separate constructors but it is useful to have
2256 /// it in one place and to eliminate the redundant code for getting the sizes
2257 /// of the types involved.
2259 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2261 // Check for type sanity on the arguments
2262 const Type *SrcTy = S->getType();
2263 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2266 // Get the size of the types in bits, we'll need this later
2267 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2268 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2270 // Switch on the opcode provided
2272 default: return false; // This is an input error
2273 case Instruction::Trunc:
2274 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2275 case Instruction::ZExt:
2276 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2277 case Instruction::SExt:
2278 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2279 case Instruction::FPTrunc:
2280 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2281 SrcBitSize > DstBitSize;
2282 case Instruction::FPExt:
2283 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2284 SrcBitSize < DstBitSize;
2285 case Instruction::UIToFP:
2286 case Instruction::SIToFP:
2287 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2288 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2289 return SVTy->getElementType()->isInteger() &&
2290 DVTy->getElementType()->isFloatingPoint() &&
2291 SVTy->getNumElements() == DVTy->getNumElements();
2294 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2295 case Instruction::FPToUI:
2296 case Instruction::FPToSI:
2297 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2298 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2299 return SVTy->getElementType()->isFloatingPoint() &&
2300 DVTy->getElementType()->isInteger() &&
2301 SVTy->getNumElements() == DVTy->getNumElements();
2304 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2305 case Instruction::PtrToInt:
2306 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2307 case Instruction::IntToPtr:
2308 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2309 case Instruction::BitCast:
2310 // BitCast implies a no-op cast of type only. No bits change.
2311 // However, you can't cast pointers to anything but pointers.
2312 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2315 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2316 // these cases, the cast is okay if the source and destination bit widths
2318 return SrcBitSize == DstBitSize;
2322 TruncInst::TruncInst(
2323 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2324 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2325 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2328 TruncInst::TruncInst(
2329 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2330 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2331 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2335 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2336 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2337 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2341 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2342 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2343 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2346 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2347 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2348 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2352 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2353 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2354 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2357 FPTruncInst::FPTruncInst(
2358 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2359 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2360 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2363 FPTruncInst::FPTruncInst(
2364 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2365 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2366 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2369 FPExtInst::FPExtInst(
2370 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2371 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2372 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2375 FPExtInst::FPExtInst(
2376 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2377 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2378 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2381 UIToFPInst::UIToFPInst(
2382 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2383 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2384 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2387 UIToFPInst::UIToFPInst(
2388 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2389 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2390 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2393 SIToFPInst::SIToFPInst(
2394 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2395 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2396 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2399 SIToFPInst::SIToFPInst(
2400 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2401 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2402 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2405 FPToUIInst::FPToUIInst(
2406 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2407 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2408 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2411 FPToUIInst::FPToUIInst(
2412 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2413 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2414 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2417 FPToSIInst::FPToSIInst(
2418 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2419 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2420 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2423 FPToSIInst::FPToSIInst(
2424 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2425 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2426 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2429 PtrToIntInst::PtrToIntInst(
2430 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2431 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2432 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2435 PtrToIntInst::PtrToIntInst(
2436 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2437 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2438 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2441 IntToPtrInst::IntToPtrInst(
2442 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2443 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2444 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2447 IntToPtrInst::IntToPtrInst(
2448 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2449 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2450 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2453 BitCastInst::BitCastInst(
2454 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2455 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2456 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2459 BitCastInst::BitCastInst(
2460 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2461 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2462 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2465 //===----------------------------------------------------------------------===//
2467 //===----------------------------------------------------------------------===//
2469 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2470 Value *LHS, Value *RHS, const std::string &Name,
2471 Instruction *InsertBefore)
2472 : Instruction(ty, op,
2473 OperandTraits<CmpInst>::op_begin(this),
2474 OperandTraits<CmpInst>::operands(this),
2478 SubclassData = predicate;
2482 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2483 Value *LHS, Value *RHS, const std::string &Name,
2484 BasicBlock *InsertAtEnd)
2485 : Instruction(ty, op,
2486 OperandTraits<CmpInst>::op_begin(this),
2487 OperandTraits<CmpInst>::operands(this),
2491 SubclassData = predicate;
2496 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2497 const std::string &Name, Instruction *InsertBefore) {
2498 if (Op == Instruction::ICmp) {
2499 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2502 if (Op == Instruction::FCmp) {
2503 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2506 if (Op == Instruction::VICmp) {
2507 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2510 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2515 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2516 const std::string &Name, BasicBlock *InsertAtEnd) {
2517 if (Op == Instruction::ICmp) {
2518 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2521 if (Op == Instruction::FCmp) {
2522 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2525 if (Op == Instruction::VICmp) {
2526 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2529 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2533 void CmpInst::swapOperands() {
2534 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2537 cast<FCmpInst>(this)->swapOperands();
2540 bool CmpInst::isCommutative() {
2541 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2542 return IC->isCommutative();
2543 return cast<FCmpInst>(this)->isCommutative();
2546 bool CmpInst::isEquality() {
2547 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2548 return IC->isEquality();
2549 return cast<FCmpInst>(this)->isEquality();
2553 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2555 default: assert(!"Unknown cmp predicate!");
2556 case ICMP_EQ: return ICMP_NE;
2557 case ICMP_NE: return ICMP_EQ;
2558 case ICMP_UGT: return ICMP_ULE;
2559 case ICMP_ULT: return ICMP_UGE;
2560 case ICMP_UGE: return ICMP_ULT;
2561 case ICMP_ULE: return ICMP_UGT;
2562 case ICMP_SGT: return ICMP_SLE;
2563 case ICMP_SLT: return ICMP_SGE;
2564 case ICMP_SGE: return ICMP_SLT;
2565 case ICMP_SLE: return ICMP_SGT;
2567 case FCMP_OEQ: return FCMP_UNE;
2568 case FCMP_ONE: return FCMP_UEQ;
2569 case FCMP_OGT: return FCMP_ULE;
2570 case FCMP_OLT: return FCMP_UGE;
2571 case FCMP_OGE: return FCMP_ULT;
2572 case FCMP_OLE: return FCMP_UGT;
2573 case FCMP_UEQ: return FCMP_ONE;
2574 case FCMP_UNE: return FCMP_OEQ;
2575 case FCMP_UGT: return FCMP_OLE;
2576 case FCMP_ULT: return FCMP_OGE;
2577 case FCMP_UGE: return FCMP_OLT;
2578 case FCMP_ULE: return FCMP_OGT;
2579 case FCMP_ORD: return FCMP_UNO;
2580 case FCMP_UNO: return FCMP_ORD;
2581 case FCMP_TRUE: return FCMP_FALSE;
2582 case FCMP_FALSE: return FCMP_TRUE;
2586 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2588 default: assert(! "Unknown icmp predicate!");
2589 case ICMP_EQ: case ICMP_NE:
2590 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2592 case ICMP_UGT: return ICMP_SGT;
2593 case ICMP_ULT: return ICMP_SLT;
2594 case ICMP_UGE: return ICMP_SGE;
2595 case ICMP_ULE: return ICMP_SLE;
2599 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2601 default: assert(! "Unknown icmp predicate!");
2602 case ICMP_EQ: case ICMP_NE:
2603 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2605 case ICMP_SGT: return ICMP_UGT;
2606 case ICMP_SLT: return ICMP_ULT;
2607 case ICMP_SGE: return ICMP_UGE;
2608 case ICMP_SLE: return ICMP_ULE;
2612 bool ICmpInst::isSignedPredicate(Predicate pred) {
2614 default: assert(! "Unknown icmp predicate!");
2615 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2617 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2618 case ICMP_UGE: case ICMP_ULE:
2623 /// Initialize a set of values that all satisfy the condition with C.
2626 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2629 uint32_t BitWidth = C.getBitWidth();
2631 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2632 case ICmpInst::ICMP_EQ: Upper++; break;
2633 case ICmpInst::ICMP_NE: Lower++; break;
2634 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2635 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2636 case ICmpInst::ICMP_UGT:
2637 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2639 case ICmpInst::ICMP_SGT:
2640 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2642 case ICmpInst::ICMP_ULE:
2643 Lower = APInt::getMinValue(BitWidth); Upper++;
2645 case ICmpInst::ICMP_SLE:
2646 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2648 case ICmpInst::ICMP_UGE:
2649 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2651 case ICmpInst::ICMP_SGE:
2652 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2655 return ConstantRange(Lower, Upper);
2658 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2660 default: assert(!"Unknown cmp predicate!");
2661 case ICMP_EQ: case ICMP_NE:
2663 case ICMP_SGT: return ICMP_SLT;
2664 case ICMP_SLT: return ICMP_SGT;
2665 case ICMP_SGE: return ICMP_SLE;
2666 case ICMP_SLE: return ICMP_SGE;
2667 case ICMP_UGT: return ICMP_ULT;
2668 case ICMP_ULT: return ICMP_UGT;
2669 case ICMP_UGE: return ICMP_ULE;
2670 case ICMP_ULE: return ICMP_UGE;
2672 case FCMP_FALSE: case FCMP_TRUE:
2673 case FCMP_OEQ: case FCMP_ONE:
2674 case FCMP_UEQ: case FCMP_UNE:
2675 case FCMP_ORD: case FCMP_UNO:
2677 case FCMP_OGT: return FCMP_OLT;
2678 case FCMP_OLT: return FCMP_OGT;
2679 case FCMP_OGE: return FCMP_OLE;
2680 case FCMP_OLE: return FCMP_OGE;
2681 case FCMP_UGT: return FCMP_ULT;
2682 case FCMP_ULT: return FCMP_UGT;
2683 case FCMP_UGE: return FCMP_ULE;
2684 case FCMP_ULE: return FCMP_UGE;
2688 bool CmpInst::isUnsigned(unsigned short predicate) {
2689 switch (predicate) {
2690 default: return false;
2691 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2692 case ICmpInst::ICMP_UGE: return true;
2696 bool CmpInst::isSigned(unsigned short predicate){
2697 switch (predicate) {
2698 default: return false;
2699 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2700 case ICmpInst::ICMP_SGE: return true;
2704 bool CmpInst::isOrdered(unsigned short predicate) {
2705 switch (predicate) {
2706 default: return false;
2707 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2708 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2709 case FCmpInst::FCMP_ORD: return true;
2713 bool CmpInst::isUnordered(unsigned short predicate) {
2714 switch (predicate) {
2715 default: return false;
2716 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2717 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2718 case FCmpInst::FCMP_UNO: return true;
2722 //===----------------------------------------------------------------------===//
2723 // SwitchInst Implementation
2724 //===----------------------------------------------------------------------===//
2726 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2727 assert(Value && Default);
2728 ReservedSpace = 2+NumCases*2;
2730 OperandList = allocHungoffUses(ReservedSpace);
2732 OperandList[0] = Value;
2733 OperandList[1] = Default;
2736 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2737 /// switch on and a default destination. The number of additional cases can
2738 /// be specified here to make memory allocation more efficient. This
2739 /// constructor can also autoinsert before another instruction.
2740 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2741 Instruction *InsertBefore)
2742 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2743 init(Value, Default, NumCases);
2746 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2747 /// switch on and a default destination. The number of additional cases can
2748 /// be specified here to make memory allocation more efficient. This
2749 /// constructor also autoinserts at the end of the specified BasicBlock.
2750 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2751 BasicBlock *InsertAtEnd)
2752 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2753 init(Value, Default, NumCases);
2756 SwitchInst::SwitchInst(const SwitchInst &SI)
2757 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2758 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2759 Use *OL = OperandList, *InOL = SI.OperandList;
2760 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2762 OL[i+1] = InOL[i+1];
2766 SwitchInst::~SwitchInst() {
2767 dropHungoffUses(OperandList);
2771 /// addCase - Add an entry to the switch instruction...
2773 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2774 unsigned OpNo = NumOperands;
2775 if (OpNo+2 > ReservedSpace)
2776 resizeOperands(0); // Get more space!
2777 // Initialize some new operands.
2778 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2779 NumOperands = OpNo+2;
2780 OperandList[OpNo] = OnVal;
2781 OperandList[OpNo+1] = Dest;
2784 /// removeCase - This method removes the specified successor from the switch
2785 /// instruction. Note that this cannot be used to remove the default
2786 /// destination (successor #0).
2788 void SwitchInst::removeCase(unsigned idx) {
2789 assert(idx != 0 && "Cannot remove the default case!");
2790 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2792 unsigned NumOps = getNumOperands();
2793 Use *OL = OperandList;
2795 // Move everything after this operand down.
2797 // FIXME: we could just swap with the end of the list, then erase. However,
2798 // client might not expect this to happen. The code as it is thrashes the
2799 // use/def lists, which is kinda lame.
2800 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2802 OL[i-2+1] = OL[i+1];
2805 // Nuke the last value.
2806 OL[NumOps-2].set(0);
2807 OL[NumOps-2+1].set(0);
2808 NumOperands = NumOps-2;
2811 /// resizeOperands - resize operands - This adjusts the length of the operands
2812 /// list according to the following behavior:
2813 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2814 /// of operation. This grows the number of ops by 3 times.
2815 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2816 /// 3. If NumOps == NumOperands, trim the reserved space.
2818 void SwitchInst::resizeOperands(unsigned NumOps) {
2819 unsigned e = getNumOperands();
2822 } else if (NumOps*2 > NumOperands) {
2823 // No resize needed.
2824 if (ReservedSpace >= NumOps) return;
2825 } else if (NumOps == NumOperands) {
2826 if (ReservedSpace == NumOps) return;
2831 ReservedSpace = NumOps;
2832 Use *NewOps = allocHungoffUses(NumOps);
2833 Use *OldOps = OperandList;
2834 for (unsigned i = 0; i != e; ++i) {
2835 NewOps[i] = OldOps[i];
2837 OperandList = NewOps;
2838 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2842 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2843 return getSuccessor(idx);
2845 unsigned SwitchInst::getNumSuccessorsV() const {
2846 return getNumSuccessors();
2848 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2849 setSuccessor(idx, B);
2852 //===----------------------------------------------------------------------===//
2853 // GetResultInst Implementation
2854 //===----------------------------------------------------------------------===//
2856 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2857 const std::string &Name,
2858 Instruction *InsertBef)
2859 : UnaryInstruction(cast<StructType>(Aggregate->getType())
2860 ->getElementType(Index),
2861 GetResult, Aggregate, InsertBef),
2863 assert(isValidOperands(Aggregate, Index)
2864 && "Invalid GetResultInst operands!");
2868 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2872 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2873 unsigned NumElements = STy->getNumElements();
2874 if (Index >= NumElements || NumElements == 0)
2877 // getresult aggregate value's element types are restricted to
2878 // avoid nested aggregates.
2879 for (unsigned i = 0; i < NumElements; ++i)
2880 if (!STy->getElementType(i)->isFirstClassType())
2883 // Otherwise, Aggregate is valid.
2889 // Define these methods here so vtables don't get emitted into every translation
2890 // unit that uses these classes.
2892 GetElementPtrInst *GetElementPtrInst::clone() const {
2893 return new(getNumOperands()) GetElementPtrInst(*this);
2896 BinaryOperator *BinaryOperator::clone() const {
2897 return Create(getOpcode(), Op<0>(), Op<1>());
2900 FCmpInst* FCmpInst::clone() const {
2901 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2903 ICmpInst* ICmpInst::clone() const {
2904 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2907 VFCmpInst* VFCmpInst::clone() const {
2908 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2910 VICmpInst* VICmpInst::clone() const {
2911 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2914 ExtractValueInst *ExtractValueInst::clone() const {
2915 return new ExtractValueInst(*this);
2917 InsertValueInst *InsertValueInst::clone() const {
2918 return new InsertValueInst(*this);
2922 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2923 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2924 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2925 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2926 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2927 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2928 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2929 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2930 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2931 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2932 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2933 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2934 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2935 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2936 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2937 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2938 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2939 CallInst *CallInst::clone() const {
2940 return new(getNumOperands()) CallInst(*this);
2942 SelectInst *SelectInst::clone() const {
2943 return new(getNumOperands()) SelectInst(*this);
2945 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2947 ExtractElementInst *ExtractElementInst::clone() const {
2948 return new ExtractElementInst(*this);
2950 InsertElementInst *InsertElementInst::clone() const {
2951 return InsertElementInst::Create(*this);
2953 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2954 return new ShuffleVectorInst(*this);
2956 PHINode *PHINode::clone() const { return new PHINode(*this); }
2957 ReturnInst *ReturnInst::clone() const {
2958 return new(getNumOperands()) ReturnInst(*this);
2960 BranchInst *BranchInst::clone() const {
2961 return new(getNumOperands()) BranchInst(*this);
2963 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2964 InvokeInst *InvokeInst::clone() const {
2965 return new(getNumOperands()) InvokeInst(*this);
2967 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2968 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2969 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }