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/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Support/CallSite.h"
21 #include "llvm/Support/ConstantRange.h"
22 #include "llvm/Support/MathExtras.h"
25 //===----------------------------------------------------------------------===//
27 //===----------------------------------------------------------------------===//
29 CallSite::CallSite(Instruction *C) {
30 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
33 unsigned CallSite::getCallingConv() const {
34 if (CallInst *CI = dyn_cast<CallInst>(I))
35 return CI->getCallingConv();
37 return cast<InvokeInst>(I)->getCallingConv();
39 void CallSite::setCallingConv(unsigned CC) {
40 if (CallInst *CI = dyn_cast<CallInst>(I))
41 CI->setCallingConv(CC);
43 cast<InvokeInst>(I)->setCallingConv(CC);
45 const PAListPtr &CallSite::getParamAttrs() const {
46 if (CallInst *CI = dyn_cast<CallInst>(I))
47 return CI->getParamAttrs();
49 return cast<InvokeInst>(I)->getParamAttrs();
51 void CallSite::setParamAttrs(const PAListPtr &PAL) {
52 if (CallInst *CI = dyn_cast<CallInst>(I))
53 CI->setParamAttrs(PAL);
55 cast<InvokeInst>(I)->setParamAttrs(PAL);
57 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
58 if (CallInst *CI = dyn_cast<CallInst>(I))
59 return CI->paramHasAttr(i, attr);
61 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
63 uint16_t CallSite::getParamAlignment(uint16_t i) const {
64 if (CallInst *CI = dyn_cast<CallInst>(I))
65 return CI->getParamAlignment(i);
67 return cast<InvokeInst>(I)->getParamAlignment(i);
70 bool CallSite::doesNotAccessMemory() const {
71 if (CallInst *CI = dyn_cast<CallInst>(I))
72 return CI->doesNotAccessMemory();
74 return cast<InvokeInst>(I)->doesNotAccessMemory();
76 bool CallSite::onlyReadsMemory() const {
77 if (CallInst *CI = dyn_cast<CallInst>(I))
78 return CI->onlyReadsMemory();
80 return cast<InvokeInst>(I)->onlyReadsMemory();
82 bool CallSite::doesNotThrow() const {
83 if (CallInst *CI = dyn_cast<CallInst>(I))
84 return CI->doesNotThrow();
86 return cast<InvokeInst>(I)->doesNotThrow();
88 void CallSite::setDoesNotThrow(bool doesNotThrow) {
89 if (CallInst *CI = dyn_cast<CallInst>(I))
90 CI->setDoesNotThrow(doesNotThrow);
92 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
95 //===----------------------------------------------------------------------===//
96 // TerminatorInst Class
97 //===----------------------------------------------------------------------===//
99 // Out of line virtual method, so the vtable, etc has a home.
100 TerminatorInst::~TerminatorInst() {
103 //===----------------------------------------------------------------------===//
104 // UnaryInstruction Class
105 //===----------------------------------------------------------------------===//
107 // Out of line virtual method, so the vtable, etc has a home.
108 UnaryInstruction::~UnaryInstruction() {
111 //===----------------------------------------------------------------------===//
113 //===----------------------------------------------------------------------===//
115 PHINode::PHINode(const PHINode &PN)
116 : Instruction(PN.getType(), Instruction::PHI,
117 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
118 ReservedSpace(PN.getNumOperands()) {
119 Use *OL = OperandList;
120 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
121 OL[i].init(PN.getOperand(i), this);
122 OL[i+1].init(PN.getOperand(i+1), this);
126 PHINode::~PHINode() {
127 dropHungoffUses(OperandList);
130 // removeIncomingValue - Remove an incoming value. This is useful if a
131 // predecessor basic block is deleted.
132 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
133 unsigned NumOps = getNumOperands();
134 Use *OL = OperandList;
135 assert(Idx*2 < NumOps && "BB not in PHI node!");
136 Value *Removed = OL[Idx*2];
138 // Move everything after this operand down.
140 // FIXME: we could just swap with the end of the list, then erase. However,
141 // client might not expect this to happen. The code as it is thrashes the
142 // use/def lists, which is kinda lame.
143 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
148 // Nuke the last value.
150 OL[NumOps-2+1].set(0);
151 NumOperands = NumOps-2;
153 // If the PHI node is dead, because it has zero entries, nuke it now.
154 if (NumOps == 2 && DeletePHIIfEmpty) {
155 // If anyone is using this PHI, make them use a dummy value instead...
156 replaceAllUsesWith(UndefValue::get(getType()));
162 /// resizeOperands - resize operands - This adjusts the length of the operands
163 /// list according to the following behavior:
164 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
165 /// of operation. This grows the number of ops by 1.5 times.
166 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
167 /// 3. If NumOps == NumOperands, trim the reserved space.
169 void PHINode::resizeOperands(unsigned NumOps) {
170 unsigned e = getNumOperands();
173 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
174 } else if (NumOps*2 > NumOperands) {
176 if (ReservedSpace >= NumOps) return;
177 } else if (NumOps == NumOperands) {
178 if (ReservedSpace == NumOps) return;
183 ReservedSpace = NumOps;
184 Use *OldOps = OperandList;
185 Use *NewOps = allocHungoffUses(NumOps);
186 for (unsigned i = 0; i != e; ++i) {
187 NewOps[i].init(OldOps[i], this);
189 OperandList = NewOps;
190 if (OldOps) Use::zap(OldOps, OldOps + e, true);
193 /// hasConstantValue - If the specified PHI node always merges together the same
194 /// value, return the value, otherwise return null.
196 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
197 // If the PHI node only has one incoming value, eliminate the PHI node...
198 if (getNumIncomingValues() == 1) {
199 if (getIncomingValue(0) != this) // not X = phi X
200 return getIncomingValue(0);
202 return UndefValue::get(getType()); // Self cycle is dead.
205 // Otherwise if all of the incoming values are the same for the PHI, replace
206 // the PHI node with the incoming value.
209 bool HasUndefInput = false;
210 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
211 if (isa<UndefValue>(getIncomingValue(i))) {
212 HasUndefInput = true;
213 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
214 if (InVal && getIncomingValue(i) != InVal)
215 return 0; // Not the same, bail out.
217 InVal = getIncomingValue(i);
220 // The only case that could cause InVal to be null is if we have a PHI node
221 // that only has entries for itself. In this case, there is no entry into the
222 // loop, so kill the PHI.
224 if (InVal == 0) InVal = UndefValue::get(getType());
226 // If we have a PHI node like phi(X, undef, X), where X is defined by some
227 // instruction, we cannot always return X as the result of the PHI node. Only
228 // do this if X is not an instruction (thus it must dominate the PHI block),
229 // or if the client is prepared to deal with this possibility.
230 if (HasUndefInput && !AllowNonDominatingInstruction)
231 if (Instruction *IV = dyn_cast<Instruction>(InVal))
232 // If it's in the entry block, it dominates everything.
233 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
235 return 0; // Cannot guarantee that InVal dominates this PHINode.
237 // All of the incoming values are the same, return the value now.
242 //===----------------------------------------------------------------------===//
243 // CallInst Implementation
244 //===----------------------------------------------------------------------===//
246 CallInst::~CallInst() {
249 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
250 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
251 Use *OL = OperandList;
252 OL[0].init(Func, this);
254 const FunctionType *FTy =
255 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
256 FTy = FTy; // silence warning.
258 assert((NumParams == FTy->getNumParams() ||
259 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
260 "Calling a function with bad signature!");
261 for (unsigned i = 0; i != NumParams; ++i) {
262 assert((i >= FTy->getNumParams() ||
263 FTy->getParamType(i) == Params[i]->getType()) &&
264 "Calling a function with a bad signature!");
265 OL[i+1].init(Params[i], this);
269 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
270 assert(NumOperands == 3 && "NumOperands not set up?");
271 Use *OL = OperandList;
272 OL[0].init(Func, this);
273 OL[1].init(Actual1, this);
274 OL[2].init(Actual2, this);
276 const FunctionType *FTy =
277 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
278 FTy = FTy; // silence warning.
280 assert((FTy->getNumParams() == 2 ||
281 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
282 "Calling a function with bad signature");
283 assert((0 >= FTy->getNumParams() ||
284 FTy->getParamType(0) == Actual1->getType()) &&
285 "Calling a function with a bad signature!");
286 assert((1 >= FTy->getNumParams() ||
287 FTy->getParamType(1) == Actual2->getType()) &&
288 "Calling a function with a bad signature!");
291 void CallInst::init(Value *Func, Value *Actual) {
292 assert(NumOperands == 2 && "NumOperands not set up?");
293 Use *OL = OperandList;
294 OL[0].init(Func, this);
295 OL[1].init(Actual, this);
297 const FunctionType *FTy =
298 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
299 FTy = FTy; // silence warning.
301 assert((FTy->getNumParams() == 1 ||
302 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
303 "Calling a function with bad signature");
304 assert((0 == FTy->getNumParams() ||
305 FTy->getParamType(0) == Actual->getType()) &&
306 "Calling a function with a bad signature!");
309 void CallInst::init(Value *Func) {
310 assert(NumOperands == 1 && "NumOperands not set up?");
311 Use *OL = OperandList;
312 OL[0].init(Func, this);
314 const FunctionType *FTy =
315 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
316 FTy = FTy; // silence warning.
318 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
321 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
322 Instruction *InsertBefore)
323 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
324 ->getElementType())->getReturnType(),
326 OperandTraits<CallInst>::op_end(this) - 2,
332 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
333 BasicBlock *InsertAtEnd)
334 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
335 ->getElementType())->getReturnType(),
337 OperandTraits<CallInst>::op_end(this) - 2,
342 CallInst::CallInst(Value *Func, const std::string &Name,
343 Instruction *InsertBefore)
344 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
345 ->getElementType())->getReturnType(),
347 OperandTraits<CallInst>::op_end(this) - 1,
353 CallInst::CallInst(Value *Func, const std::string &Name,
354 BasicBlock *InsertAtEnd)
355 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
356 ->getElementType())->getReturnType(),
358 OperandTraits<CallInst>::op_end(this) - 1,
364 CallInst::CallInst(const CallInst &CI)
365 : Instruction(CI.getType(), Instruction::Call,
366 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
367 CI.getNumOperands()) {
368 setParamAttrs(CI.getParamAttrs());
369 SubclassData = CI.SubclassData;
370 Use *OL = OperandList;
371 Use *InOL = CI.OperandList;
372 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
373 OL[i].init(InOL[i], this);
376 void CallInst::addParamAttr(unsigned i, ParameterAttributes attr) {
377 PAListPtr PAL = getParamAttrs();
378 PAL = PAL.addAttr(i, attr);
382 bool CallInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
383 if (ParamAttrs.paramHasAttr(i, attr))
385 if (const Function *F = getCalledFunction())
386 return F->paramHasAttr(i, attr);
390 void CallInst::setDoesNotThrow(bool doesNotThrow) {
391 PAListPtr PAL = getParamAttrs();
393 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
395 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
400 //===----------------------------------------------------------------------===//
401 // InvokeInst Implementation
402 //===----------------------------------------------------------------------===//
404 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
405 Value* const *Args, unsigned NumArgs) {
406 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
407 Use *OL = OperandList;
408 OL[0].init(Fn, this);
409 OL[1].init(IfNormal, this);
410 OL[2].init(IfException, this);
411 const FunctionType *FTy =
412 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
413 FTy = FTy; // silence warning.
415 assert(((NumArgs == FTy->getNumParams()) ||
416 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
417 "Calling a function with bad signature");
419 for (unsigned i = 0, e = NumArgs; i != e; i++) {
420 assert((i >= FTy->getNumParams() ||
421 FTy->getParamType(i) == Args[i]->getType()) &&
422 "Invoking a function with a bad signature!");
424 OL[i+3].init(Args[i], this);
428 InvokeInst::InvokeInst(const InvokeInst &II)
429 : TerminatorInst(II.getType(), Instruction::Invoke,
430 OperandTraits<InvokeInst>::op_end(this)
431 - II.getNumOperands(),
432 II.getNumOperands()) {
433 setParamAttrs(II.getParamAttrs());
434 SubclassData = II.SubclassData;
435 Use *OL = OperandList, *InOL = II.OperandList;
436 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
437 OL[i].init(InOL[i], this);
440 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
441 return getSuccessor(idx);
443 unsigned InvokeInst::getNumSuccessorsV() const {
444 return getNumSuccessors();
446 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
447 return setSuccessor(idx, B);
450 bool InvokeInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
451 if (ParamAttrs.paramHasAttr(i, attr))
453 if (const Function *F = getCalledFunction())
454 return F->paramHasAttr(i, attr);
458 void InvokeInst::addParamAttr(unsigned i, ParameterAttributes attr) {
459 PAListPtr PAL = getParamAttrs();
460 PAL = PAL.addAttr(i, attr);
464 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
465 PAListPtr PAL = getParamAttrs();
467 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
469 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
474 //===----------------------------------------------------------------------===//
475 // ReturnInst Implementation
476 //===----------------------------------------------------------------------===//
478 ReturnInst::ReturnInst(const ReturnInst &RI)
479 : TerminatorInst(Type::VoidTy, Instruction::Ret,
480 OperandTraits<ReturnInst>::op_end(this)
481 - RI.getNumOperands(),
482 RI.getNumOperands()) {
483 unsigned N = RI.getNumOperands();
485 Op<0>().init(RI.Op<0>(), this);
487 Use *OL = OperandList;
488 for (unsigned i = 0; i < N; ++i)
489 OL[i].init(RI.getOperand(i), this);
493 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
494 : TerminatorInst(Type::VoidTy, Instruction::Ret,
495 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
496 retVal != 0, InsertBefore) {
500 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
501 : TerminatorInst(Type::VoidTy, Instruction::Ret,
502 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
503 retVal != 0, InsertAtEnd) {
507 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
508 : TerminatorInst(Type::VoidTy, Instruction::Ret,
509 OperandTraits<ReturnInst>::op_end(this),
513 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
514 Instruction *InsertBefore)
515 : TerminatorInst(Type::VoidTy, Instruction::Ret,
516 OperandTraits<ReturnInst>::op_end(this) - N,
521 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
522 BasicBlock *InsertAtEnd)
523 : TerminatorInst(Type::VoidTy, Instruction::Ret,
524 OperandTraits<ReturnInst>::op_end(this) - N,
530 void ReturnInst::init(Value * const* retVals, unsigned N) {
531 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
534 if (NumOperands == 1) {
536 if (V->getType() == Type::VoidTy)
538 Op<0>().init(V, this);
542 Use *OL = OperandList;
543 for (unsigned i = 0; i < NumOperands; ++i) {
544 Value *V = *retVals++;
545 assert(!isa<BasicBlock>(V) &&
546 "Cannot return basic block. Probably using the incorrect ctor");
551 unsigned ReturnInst::getNumSuccessorsV() const {
552 return getNumSuccessors();
555 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
556 /// emit the vtable for the class in this translation unit.
557 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
558 assert(0 && "ReturnInst has no successors!");
561 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
562 assert(0 && "ReturnInst has no successors!");
567 ReturnInst::~ReturnInst() {
570 //===----------------------------------------------------------------------===//
571 // UnwindInst Implementation
572 //===----------------------------------------------------------------------===//
574 UnwindInst::UnwindInst(Instruction *InsertBefore)
575 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
577 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
578 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
582 unsigned UnwindInst::getNumSuccessorsV() const {
583 return getNumSuccessors();
586 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
587 assert(0 && "UnwindInst has no successors!");
590 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
591 assert(0 && "UnwindInst has no successors!");
596 //===----------------------------------------------------------------------===//
597 // UnreachableInst Implementation
598 //===----------------------------------------------------------------------===//
600 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
601 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
603 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
604 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
607 unsigned UnreachableInst::getNumSuccessorsV() const {
608 return getNumSuccessors();
611 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
612 assert(0 && "UnwindInst has no successors!");
615 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
616 assert(0 && "UnwindInst has no successors!");
621 //===----------------------------------------------------------------------===//
622 // BranchInst Implementation
623 //===----------------------------------------------------------------------===//
625 void BranchInst::AssertOK() {
627 assert(getCondition()->getType() == Type::Int1Ty &&
628 "May only branch on boolean predicates!");
631 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
632 : TerminatorInst(Type::VoidTy, Instruction::Br,
633 OperandTraits<BranchInst>::op_end(this) - 1,
635 assert(IfTrue != 0 && "Branch destination may not be null!");
636 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
638 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
639 Instruction *InsertBefore)
640 : TerminatorInst(Type::VoidTy, Instruction::Br,
641 OperandTraits<BranchInst>::op_end(this) - 3,
643 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
644 Op<1>().init(reinterpret_cast<Value*>(IfFalse), this);
645 Op<2>().init(Cond, this);
651 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
652 : TerminatorInst(Type::VoidTy, Instruction::Br,
653 OperandTraits<BranchInst>::op_end(this) - 1,
655 assert(IfTrue != 0 && "Branch destination may not be null!");
656 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
659 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
660 BasicBlock *InsertAtEnd)
661 : TerminatorInst(Type::VoidTy, Instruction::Br,
662 OperandTraits<BranchInst>::op_end(this) - 3,
664 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
665 Op<1>().init(reinterpret_cast<Value*>(IfFalse), this);
666 Op<2>().init(Cond, this);
673 BranchInst::BranchInst(const BranchInst &BI) :
674 TerminatorInst(Type::VoidTy, Instruction::Br,
675 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
676 BI.getNumOperands()) {
677 OperandList[0].init(BI.getOperand(0), this);
678 if (BI.getNumOperands() != 1) {
679 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
680 OperandList[1].init(BI.getOperand(1), this);
681 OperandList[2].init(BI.getOperand(2), this);
685 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
686 return getSuccessor(idx);
688 unsigned BranchInst::getNumSuccessorsV() const {
689 return getNumSuccessors();
691 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
692 setSuccessor(idx, B);
696 //===----------------------------------------------------------------------===//
697 // AllocationInst Implementation
698 //===----------------------------------------------------------------------===//
700 static Value *getAISize(Value *Amt) {
702 Amt = ConstantInt::get(Type::Int32Ty, 1);
704 assert(!isa<BasicBlock>(Amt) &&
705 "Passed basic block into allocation size parameter! Use other ctor");
706 assert(Amt->getType() == Type::Int32Ty &&
707 "Malloc/Allocation array size is not a 32-bit integer!");
712 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
713 unsigned Align, const std::string &Name,
714 Instruction *InsertBefore)
715 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
718 assert(Ty != Type::VoidTy && "Cannot allocate void!");
722 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
723 unsigned Align, const std::string &Name,
724 BasicBlock *InsertAtEnd)
725 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
728 assert(Ty != Type::VoidTy && "Cannot allocate void!");
732 // Out of line virtual method, so the vtable, etc has a home.
733 AllocationInst::~AllocationInst() {
736 void AllocationInst::setAlignment(unsigned Align) {
737 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
738 SubclassData = Log2_32(Align) + 1;
739 assert(getAlignment() == Align && "Alignment representation error!");
742 bool AllocationInst::isArrayAllocation() const {
743 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
744 return CI->getZExtValue() != 1;
748 const Type *AllocationInst::getAllocatedType() const {
749 return getType()->getElementType();
752 AllocaInst::AllocaInst(const AllocaInst &AI)
753 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
754 Instruction::Alloca, AI.getAlignment()) {
757 MallocInst::MallocInst(const MallocInst &MI)
758 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
759 Instruction::Malloc, MI.getAlignment()) {
762 //===----------------------------------------------------------------------===//
763 // FreeInst Implementation
764 //===----------------------------------------------------------------------===//
766 void FreeInst::AssertOK() {
767 assert(isa<PointerType>(getOperand(0)->getType()) &&
768 "Can not free something of nonpointer type!");
771 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
772 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
776 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
777 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
782 //===----------------------------------------------------------------------===//
783 // LoadInst Implementation
784 //===----------------------------------------------------------------------===//
786 void LoadInst::AssertOK() {
787 assert(isa<PointerType>(getOperand(0)->getType()) &&
788 "Ptr must have pointer type.");
791 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
792 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
793 Load, Ptr, InsertBef) {
800 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
801 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
802 Load, Ptr, InsertAE) {
809 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
810 Instruction *InsertBef)
811 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
812 Load, Ptr, InsertBef) {
813 setVolatile(isVolatile);
819 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
820 unsigned Align, Instruction *InsertBef)
821 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
822 Load, Ptr, InsertBef) {
823 setVolatile(isVolatile);
829 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
830 unsigned Align, BasicBlock *InsertAE)
831 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
832 Load, Ptr, InsertAE) {
833 setVolatile(isVolatile);
839 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
840 BasicBlock *InsertAE)
841 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
842 Load, Ptr, InsertAE) {
843 setVolatile(isVolatile);
851 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
852 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
853 Load, Ptr, InsertBef) {
857 if (Name && Name[0]) setName(Name);
860 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
861 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
862 Load, Ptr, InsertAE) {
866 if (Name && Name[0]) setName(Name);
869 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
870 Instruction *InsertBef)
871 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
872 Load, Ptr, InsertBef) {
873 setVolatile(isVolatile);
876 if (Name && Name[0]) setName(Name);
879 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
880 BasicBlock *InsertAE)
881 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
882 Load, Ptr, InsertAE) {
883 setVolatile(isVolatile);
886 if (Name && Name[0]) setName(Name);
889 void LoadInst::setAlignment(unsigned Align) {
890 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
891 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
894 //===----------------------------------------------------------------------===//
895 // StoreInst Implementation
896 //===----------------------------------------------------------------------===//
898 void StoreInst::AssertOK() {
899 assert(isa<PointerType>(getOperand(1)->getType()) &&
900 "Ptr must have pointer type!");
901 assert(getOperand(0)->getType() ==
902 cast<PointerType>(getOperand(1)->getType())->getElementType()
903 && "Ptr must be a pointer to Val type!");
907 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
908 : Instruction(Type::VoidTy, Store,
909 OperandTraits<StoreInst>::op_begin(this),
910 OperandTraits<StoreInst>::operands(this),
912 Op<0>().init(val, this);
913 Op<1>().init(addr, this);
919 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
920 : Instruction(Type::VoidTy, Store,
921 OperandTraits<StoreInst>::op_begin(this),
922 OperandTraits<StoreInst>::operands(this),
924 Op<0>().init(val, this);
925 Op<1>().init(addr, this);
931 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
932 Instruction *InsertBefore)
933 : Instruction(Type::VoidTy, Store,
934 OperandTraits<StoreInst>::op_begin(this),
935 OperandTraits<StoreInst>::operands(this),
937 Op<0>().init(val, this);
938 Op<1>().init(addr, this);
939 setVolatile(isVolatile);
944 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
945 unsigned Align, Instruction *InsertBefore)
946 : Instruction(Type::VoidTy, Store,
947 OperandTraits<StoreInst>::op_begin(this),
948 OperandTraits<StoreInst>::operands(this),
950 Op<0>().init(val, this);
951 Op<1>().init(addr, this);
952 setVolatile(isVolatile);
957 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
958 unsigned Align, BasicBlock *InsertAtEnd)
959 : Instruction(Type::VoidTy, Store,
960 OperandTraits<StoreInst>::op_begin(this),
961 OperandTraits<StoreInst>::operands(this),
963 Op<0>().init(val, this);
964 Op<1>().init(addr, this);
965 setVolatile(isVolatile);
970 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
971 BasicBlock *InsertAtEnd)
972 : Instruction(Type::VoidTy, Store,
973 OperandTraits<StoreInst>::op_begin(this),
974 OperandTraits<StoreInst>::operands(this),
976 Op<0>().init(val, this);
977 Op<1>().init(addr, this);
978 setVolatile(isVolatile);
983 void StoreInst::setAlignment(unsigned Align) {
984 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
985 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
988 //===----------------------------------------------------------------------===//
989 // GetElementPtrInst Implementation
990 //===----------------------------------------------------------------------===//
992 static unsigned retrieveAddrSpace(const Value *Val) {
993 return cast<PointerType>(Val->getType())->getAddressSpace();
996 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
997 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
998 Use *OL = OperandList;
999 OL[0].init(Ptr, this);
1001 for (unsigned i = 0; i != NumIdx; ++i)
1002 OL[i+1].init(Idx[i], this);
1005 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
1006 assert(NumOperands == 2 && "NumOperands not initialized?");
1007 Use *OL = OperandList;
1008 OL[0].init(Ptr, this);
1009 OL[1].init(Idx, this);
1012 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1013 : Instruction(reinterpret_cast<const Type*>(GEPI.getType()), GetElementPtr,
1014 OperandTraits<GetElementPtrInst>::op_end(this)
1015 - GEPI.getNumOperands(),
1016 GEPI.getNumOperands()) {
1017 Use *OL = OperandList;
1018 Use *GEPIOL = GEPI.OperandList;
1019 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1020 OL[i].init(GEPIOL[i], this);
1023 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1024 const std::string &Name, Instruction *InBe)
1025 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1026 retrieveAddrSpace(Ptr)),
1028 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1034 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1035 const std::string &Name, BasicBlock *IAE)
1036 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1037 retrieveAddrSpace(Ptr)),
1039 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1045 // getIndexedType - Returns the type of the element that would be loaded with
1046 // a load instruction with the specified parameters.
1048 // A null type is returned if the indices are invalid for the specified
1051 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1054 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1055 if (!PTy) return 0; // Type isn't a pointer type!
1056 const Type *Agg = PTy->getElementType();
1058 // Handle the special case of the empty set index set...
1062 return ExtractValueInst::getIndexedType(Agg, Idxs+1, Idxs+NumIdx);
1065 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1066 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1067 if (!PTy) return 0; // Type isn't a pointer type!
1069 // Check the pointer index.
1070 if (!PTy->indexValid(Idx)) return 0;
1072 return PTy->getElementType();
1076 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1077 /// zeros. If so, the result pointer and the first operand have the same
1078 /// value, just potentially different types.
1079 bool GetElementPtrInst::hasAllZeroIndices() const {
1080 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1081 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1082 if (!CI->isZero()) return false;
1090 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1091 /// constant integers. If so, the result pointer and the first operand have
1092 /// a constant offset between them.
1093 bool GetElementPtrInst::hasAllConstantIndices() const {
1094 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1095 if (!isa<ConstantInt>(getOperand(i)))
1102 //===----------------------------------------------------------------------===//
1103 // ExtractElementInst Implementation
1104 //===----------------------------------------------------------------------===//
1106 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1107 const std::string &Name,
1108 Instruction *InsertBef)
1109 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1111 OperandTraits<ExtractElementInst>::op_begin(this),
1113 assert(isValidOperands(Val, Index) &&
1114 "Invalid extractelement instruction operands!");
1115 Op<0>().init(Val, this);
1116 Op<1>().init(Index, this);
1120 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1121 const std::string &Name,
1122 Instruction *InsertBef)
1123 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1125 OperandTraits<ExtractElementInst>::op_begin(this),
1127 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1128 assert(isValidOperands(Val, Index) &&
1129 "Invalid extractelement instruction operands!");
1130 Op<0>().init(Val, this);
1131 Op<1>().init(Index, this);
1136 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1137 const std::string &Name,
1138 BasicBlock *InsertAE)
1139 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1141 OperandTraits<ExtractElementInst>::op_begin(this),
1143 assert(isValidOperands(Val, Index) &&
1144 "Invalid extractelement instruction operands!");
1146 Op<0>().init(Val, this);
1147 Op<1>().init(Index, this);
1151 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1152 const std::string &Name,
1153 BasicBlock *InsertAE)
1154 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1156 OperandTraits<ExtractElementInst>::op_begin(this),
1158 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1159 assert(isValidOperands(Val, Index) &&
1160 "Invalid extractelement instruction operands!");
1162 Op<0>().init(Val, this);
1163 Op<1>().init(Index, this);
1168 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1169 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1175 //===----------------------------------------------------------------------===//
1176 // InsertElementInst Implementation
1177 //===----------------------------------------------------------------------===//
1179 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1180 : Instruction(IE.getType(), InsertElement,
1181 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1182 Op<0>().init(IE.Op<0>(), this);
1183 Op<1>().init(IE.Op<1>(), this);
1184 Op<2>().init(IE.Op<2>(), this);
1186 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1187 const std::string &Name,
1188 Instruction *InsertBef)
1189 : Instruction(Vec->getType(), InsertElement,
1190 OperandTraits<InsertElementInst>::op_begin(this),
1192 assert(isValidOperands(Vec, Elt, Index) &&
1193 "Invalid insertelement instruction operands!");
1194 Op<0>().init(Vec, this);
1195 Op<1>().init(Elt, this);
1196 Op<2>().init(Index, this);
1200 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1201 const std::string &Name,
1202 Instruction *InsertBef)
1203 : Instruction(Vec->getType(), InsertElement,
1204 OperandTraits<InsertElementInst>::op_begin(this),
1206 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1207 assert(isValidOperands(Vec, Elt, Index) &&
1208 "Invalid insertelement instruction operands!");
1209 Op<0>().init(Vec, this);
1210 Op<1>().init(Elt, this);
1211 Op<2>().init(Index, this);
1216 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1217 const std::string &Name,
1218 BasicBlock *InsertAE)
1219 : Instruction(Vec->getType(), InsertElement,
1220 OperandTraits<InsertElementInst>::op_begin(this),
1222 assert(isValidOperands(Vec, Elt, Index) &&
1223 "Invalid insertelement instruction operands!");
1225 Op<0>().init(Vec, this);
1226 Op<1>().init(Elt, this);
1227 Op<2>().init(Index, this);
1231 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1232 const std::string &Name,
1233 BasicBlock *InsertAE)
1234 : Instruction(Vec->getType(), InsertElement,
1235 OperandTraits<InsertElementInst>::op_begin(this),
1237 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1238 assert(isValidOperands(Vec, Elt, Index) &&
1239 "Invalid insertelement instruction operands!");
1241 Op<0>().init(Vec, this);
1242 Op<1>().init(Elt, this);
1243 Op<2>().init(Index, this);
1247 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1248 const Value *Index) {
1249 if (!isa<VectorType>(Vec->getType()))
1250 return false; // First operand of insertelement must be vector type.
1252 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1253 return false;// Second operand of insertelement must be vector element type.
1255 if (Index->getType() != Type::Int32Ty)
1256 return false; // Third operand of insertelement must be uint.
1261 //===----------------------------------------------------------------------===//
1262 // ShuffleVectorInst Implementation
1263 //===----------------------------------------------------------------------===//
1265 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1266 : Instruction(SV.getType(), ShuffleVector,
1267 OperandTraits<ShuffleVectorInst>::op_begin(this),
1268 OperandTraits<ShuffleVectorInst>::operands(this)) {
1269 Op<0>().init(SV.Op<0>(), this);
1270 Op<1>().init(SV.Op<1>(), this);
1271 Op<2>().init(SV.Op<2>(), this);
1274 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1275 const std::string &Name,
1276 Instruction *InsertBefore)
1277 : Instruction(V1->getType(), ShuffleVector,
1278 OperandTraits<ShuffleVectorInst>::op_begin(this),
1279 OperandTraits<ShuffleVectorInst>::operands(this),
1281 assert(isValidOperands(V1, V2, Mask) &&
1282 "Invalid shuffle vector instruction operands!");
1283 Op<0>().init(V1, this);
1284 Op<1>().init(V2, this);
1285 Op<2>().init(Mask, this);
1289 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1290 const std::string &Name,
1291 BasicBlock *InsertAtEnd)
1292 : Instruction(V1->getType(), ShuffleVector,
1293 OperandTraits<ShuffleVectorInst>::op_begin(this),
1294 OperandTraits<ShuffleVectorInst>::operands(this),
1296 assert(isValidOperands(V1, V2, Mask) &&
1297 "Invalid shuffle vector instruction operands!");
1299 Op<0>().init(V1, this);
1300 Op<1>().init(V2, this);
1301 Op<2>().init(Mask, this);
1305 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1306 const Value *Mask) {
1307 if (!isa<VectorType>(V1->getType()) ||
1308 V1->getType() != V2->getType())
1311 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1312 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1313 MaskTy->getElementType() != Type::Int32Ty ||
1314 MaskTy->getNumElements() !=
1315 cast<VectorType>(V1->getType())->getNumElements())
1320 /// getMaskValue - Return the index from the shuffle mask for the specified
1321 /// output result. This is either -1 if the element is undef or a number less
1322 /// than 2*numelements.
1323 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1324 const Constant *Mask = cast<Constant>(getOperand(2));
1325 if (isa<UndefValue>(Mask)) return -1;
1326 if (isa<ConstantAggregateZero>(Mask)) return 0;
1327 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1328 assert(i < MaskCV->getNumOperands() && "Index out of range");
1330 if (isa<UndefValue>(MaskCV->getOperand(i)))
1332 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1335 //===----------------------------------------------------------------------===//
1336 // ExtractValueInst Class
1337 //===----------------------------------------------------------------------===//
1339 // getIndexedType - Returns the type of the element that would be extracted
1340 // with an extractvalue instruction with the specified parameters.
1342 // A null type is returned if the indices are invalid for the specified
1345 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1348 unsigned CurIdx = 0;
1349 for (; CurIdx != NumIdx; ++CurIdx) {
1350 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1351 if (!CT || isa<PointerType>(CT)) return 0;
1352 Value *Index = Idxs[CurIdx];
1353 if (!CT->indexValid(Index)) return 0;
1354 Agg = CT->getTypeAtIndex(Index);
1356 // If the new type forwards to another type, then it is in the middle
1357 // of being refined to another type (and hence, may have dropped all
1358 // references to what it was using before). So, use the new forwarded
1360 if (const Type *Ty = Agg->getForwardedType())
1363 return CurIdx == NumIdx ? Agg : 0;
1366 //===----------------------------------------------------------------------===//
1367 // BinaryOperator Class
1368 //===----------------------------------------------------------------------===//
1370 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1371 const Type *Ty, const std::string &Name,
1372 Instruction *InsertBefore)
1373 : Instruction(Ty, iType,
1374 OperandTraits<BinaryOperator>::op_begin(this),
1375 OperandTraits<BinaryOperator>::operands(this),
1377 Op<0>().init(S1, this);
1378 Op<1>().init(S2, this);
1383 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1384 const Type *Ty, const std::string &Name,
1385 BasicBlock *InsertAtEnd)
1386 : Instruction(Ty, iType,
1387 OperandTraits<BinaryOperator>::op_begin(this),
1388 OperandTraits<BinaryOperator>::operands(this),
1390 Op<0>().init(S1, this);
1391 Op<1>().init(S2, this);
1397 void BinaryOperator::init(BinaryOps iType) {
1398 Value *LHS = getOperand(0), *RHS = getOperand(1);
1399 LHS = LHS; RHS = RHS; // Silence warnings.
1400 assert(LHS->getType() == RHS->getType() &&
1401 "Binary operator operand types must match!");
1406 assert(getType() == LHS->getType() &&
1407 "Arithmetic operation should return same type as operands!");
1408 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1409 isa<VectorType>(getType())) &&
1410 "Tried to create an arithmetic operation on a non-arithmetic type!");
1414 assert(getType() == LHS->getType() &&
1415 "Arithmetic operation should return same type as operands!");
1416 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1417 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1418 "Incorrect operand type (not integer) for S/UDIV");
1421 assert(getType() == LHS->getType() &&
1422 "Arithmetic operation should return same type as operands!");
1423 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1424 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1425 && "Incorrect operand type (not floating point) for FDIV");
1429 assert(getType() == LHS->getType() &&
1430 "Arithmetic operation should return same type as operands!");
1431 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1432 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1433 "Incorrect operand type (not integer) for S/UREM");
1436 assert(getType() == LHS->getType() &&
1437 "Arithmetic operation should return same type as operands!");
1438 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1439 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1440 && "Incorrect operand type (not floating point) for FREM");
1445 assert(getType() == LHS->getType() &&
1446 "Shift operation should return same type as operands!");
1447 assert(getType()->isInteger() &&
1448 "Shift operation requires integer operands");
1452 assert(getType() == LHS->getType() &&
1453 "Logical operation should return same type as operands!");
1454 assert((getType()->isInteger() ||
1455 (isa<VectorType>(getType()) &&
1456 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1457 "Tried to create a logical operation on a non-integral type!");
1465 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1466 const std::string &Name,
1467 Instruction *InsertBefore) {
1468 assert(S1->getType() == S2->getType() &&
1469 "Cannot create binary operator with two operands of differing type!");
1470 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1473 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1474 const std::string &Name,
1475 BasicBlock *InsertAtEnd) {
1476 BinaryOperator *Res = Create(Op, S1, S2, Name);
1477 InsertAtEnd->getInstList().push_back(Res);
1481 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1482 Instruction *InsertBefore) {
1483 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1484 return new BinaryOperator(Instruction::Sub,
1486 Op->getType(), Name, InsertBefore);
1489 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1490 BasicBlock *InsertAtEnd) {
1491 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1492 return new BinaryOperator(Instruction::Sub,
1494 Op->getType(), Name, InsertAtEnd);
1497 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1498 Instruction *InsertBefore) {
1500 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1501 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1502 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1504 C = ConstantInt::getAllOnesValue(Op->getType());
1507 return new BinaryOperator(Instruction::Xor, Op, C,
1508 Op->getType(), Name, InsertBefore);
1511 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1512 BasicBlock *InsertAtEnd) {
1514 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1515 // Create a vector of all ones values.
1516 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1518 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1520 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1523 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1524 Op->getType(), Name, InsertAtEnd);
1528 // isConstantAllOnes - Helper function for several functions below
1529 static inline bool isConstantAllOnes(const Value *V) {
1530 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1531 return CI->isAllOnesValue();
1532 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1533 return CV->isAllOnesValue();
1537 bool BinaryOperator::isNeg(const Value *V) {
1538 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1539 if (Bop->getOpcode() == Instruction::Sub)
1540 return Bop->getOperand(0) ==
1541 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1545 bool BinaryOperator::isNot(const Value *V) {
1546 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1547 return (Bop->getOpcode() == Instruction::Xor &&
1548 (isConstantAllOnes(Bop->getOperand(1)) ||
1549 isConstantAllOnes(Bop->getOperand(0))));
1553 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1554 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1555 return cast<BinaryOperator>(BinOp)->getOperand(1);
1558 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1559 return getNegArgument(const_cast<Value*>(BinOp));
1562 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1563 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1564 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1565 Value *Op0 = BO->getOperand(0);
1566 Value *Op1 = BO->getOperand(1);
1567 if (isConstantAllOnes(Op0)) return Op1;
1569 assert(isConstantAllOnes(Op1));
1573 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1574 return getNotArgument(const_cast<Value*>(BinOp));
1578 // swapOperands - Exchange the two operands to this instruction. This
1579 // instruction is safe to use on any binary instruction and does not
1580 // modify the semantics of the instruction. If the instruction is
1581 // order dependent (SetLT f.e.) the opcode is changed.
1583 bool BinaryOperator::swapOperands() {
1584 if (!isCommutative())
1585 return true; // Can't commute operands
1586 Op<0>().swap(Op<1>());
1590 //===----------------------------------------------------------------------===//
1592 //===----------------------------------------------------------------------===//
1594 // Just determine if this cast only deals with integral->integral conversion.
1595 bool CastInst::isIntegerCast() const {
1596 switch (getOpcode()) {
1597 default: return false;
1598 case Instruction::ZExt:
1599 case Instruction::SExt:
1600 case Instruction::Trunc:
1602 case Instruction::BitCast:
1603 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1607 bool CastInst::isLosslessCast() const {
1608 // Only BitCast can be lossless, exit fast if we're not BitCast
1609 if (getOpcode() != Instruction::BitCast)
1612 // Identity cast is always lossless
1613 const Type* SrcTy = getOperand(0)->getType();
1614 const Type* DstTy = getType();
1618 // Pointer to pointer is always lossless.
1619 if (isa<PointerType>(SrcTy))
1620 return isa<PointerType>(DstTy);
1621 return false; // Other types have no identity values
1624 /// This function determines if the CastInst does not require any bits to be
1625 /// changed in order to effect the cast. Essentially, it identifies cases where
1626 /// no code gen is necessary for the cast, hence the name no-op cast. For
1627 /// example, the following are all no-op casts:
1628 /// # bitcast i32* %x to i8*
1629 /// # bitcast <2 x i32> %x to <4 x i16>
1630 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1631 /// @brief Determine if a cast is a no-op.
1632 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1633 switch (getOpcode()) {
1635 assert(!"Invalid CastOp");
1636 case Instruction::Trunc:
1637 case Instruction::ZExt:
1638 case Instruction::SExt:
1639 case Instruction::FPTrunc:
1640 case Instruction::FPExt:
1641 case Instruction::UIToFP:
1642 case Instruction::SIToFP:
1643 case Instruction::FPToUI:
1644 case Instruction::FPToSI:
1645 return false; // These always modify bits
1646 case Instruction::BitCast:
1647 return true; // BitCast never modifies bits.
1648 case Instruction::PtrToInt:
1649 return IntPtrTy->getPrimitiveSizeInBits() ==
1650 getType()->getPrimitiveSizeInBits();
1651 case Instruction::IntToPtr:
1652 return IntPtrTy->getPrimitiveSizeInBits() ==
1653 getOperand(0)->getType()->getPrimitiveSizeInBits();
1657 /// This function determines if a pair of casts can be eliminated and what
1658 /// opcode should be used in the elimination. This assumes that there are two
1659 /// instructions like this:
1660 /// * %F = firstOpcode SrcTy %x to MidTy
1661 /// * %S = secondOpcode MidTy %F to DstTy
1662 /// The function returns a resultOpcode so these two casts can be replaced with:
1663 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1664 /// If no such cast is permited, the function returns 0.
1665 unsigned CastInst::isEliminableCastPair(
1666 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1667 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1669 // Define the 144 possibilities for these two cast instructions. The values
1670 // in this matrix determine what to do in a given situation and select the
1671 // case in the switch below. The rows correspond to firstOp, the columns
1672 // correspond to secondOp. In looking at the table below, keep in mind
1673 // the following cast properties:
1675 // Size Compare Source Destination
1676 // Operator Src ? Size Type Sign Type Sign
1677 // -------- ------------ ------------------- ---------------------
1678 // TRUNC > Integer Any Integral Any
1679 // ZEXT < Integral Unsigned Integer Any
1680 // SEXT < Integral Signed Integer Any
1681 // FPTOUI n/a FloatPt n/a Integral Unsigned
1682 // FPTOSI n/a FloatPt n/a Integral Signed
1683 // UITOFP n/a Integral Unsigned FloatPt n/a
1684 // SITOFP n/a Integral Signed FloatPt n/a
1685 // FPTRUNC > FloatPt n/a FloatPt n/a
1686 // FPEXT < FloatPt n/a FloatPt n/a
1687 // PTRTOINT n/a Pointer n/a Integral Unsigned
1688 // INTTOPTR n/a Integral Unsigned Pointer n/a
1689 // BITCONVERT = FirstClass n/a FirstClass n/a
1691 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1692 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1693 // into "fptoui double to ulong", but this loses information about the range
1694 // of the produced value (we no longer know the top-part is all zeros).
1695 // Further this conversion is often much more expensive for typical hardware,
1696 // and causes issues when building libgcc. We disallow fptosi+sext for the
1698 const unsigned numCastOps =
1699 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1700 static const uint8_t CastResults[numCastOps][numCastOps] = {
1701 // T F F U S F F P I B -+
1702 // R Z S P P I I T P 2 N T |
1703 // U E E 2 2 2 2 R E I T C +- secondOp
1704 // N X X U S F F N X N 2 V |
1705 // C T T I I P P C T T P T -+
1706 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1707 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1708 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1709 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1710 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1711 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1712 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1713 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1714 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1715 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1716 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1717 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1720 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1721 [secondOp-Instruction::CastOpsBegin];
1724 // categorically disallowed
1727 // allowed, use first cast's opcode
1730 // allowed, use second cast's opcode
1733 // no-op cast in second op implies firstOp as long as the DestTy
1735 if (DstTy->isInteger())
1739 // no-op cast in second op implies firstOp as long as the DestTy
1740 // is floating point
1741 if (DstTy->isFloatingPoint())
1745 // no-op cast in first op implies secondOp as long as the SrcTy
1747 if (SrcTy->isInteger())
1751 // no-op cast in first op implies secondOp as long as the SrcTy
1752 // is a floating point
1753 if (SrcTy->isFloatingPoint())
1757 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1758 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1759 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1760 if (MidSize >= PtrSize)
1761 return Instruction::BitCast;
1765 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1766 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1767 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1768 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1769 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1770 if (SrcSize == DstSize)
1771 return Instruction::BitCast;
1772 else if (SrcSize < DstSize)
1776 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1777 return Instruction::ZExt;
1779 // fpext followed by ftrunc is allowed if the bit size returned to is
1780 // the same as the original, in which case its just a bitcast
1782 return Instruction::BitCast;
1783 return 0; // If the types are not the same we can't eliminate it.
1785 // bitcast followed by ptrtoint is allowed as long as the bitcast
1786 // is a pointer to pointer cast.
1787 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1791 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1792 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1796 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1797 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1798 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1799 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1800 if (SrcSize <= PtrSize && SrcSize == DstSize)
1801 return Instruction::BitCast;
1805 // cast combination can't happen (error in input). This is for all cases
1806 // where the MidTy is not the same for the two cast instructions.
1807 assert(!"Invalid Cast Combination");
1810 assert(!"Error in CastResults table!!!");
1816 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1817 const std::string &Name, Instruction *InsertBefore) {
1818 // Construct and return the appropriate CastInst subclass
1820 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1821 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1822 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1823 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1824 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1825 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1826 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1827 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1828 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1829 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1830 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1831 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1833 assert(!"Invalid opcode provided");
1838 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1839 const std::string &Name, BasicBlock *InsertAtEnd) {
1840 // Construct and return the appropriate CastInst subclass
1842 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1843 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1844 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1845 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1846 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1847 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1848 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1849 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1850 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1851 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1852 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1853 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1855 assert(!"Invalid opcode provided");
1860 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1861 const std::string &Name,
1862 Instruction *InsertBefore) {
1863 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1864 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1865 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1868 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1869 const std::string &Name,
1870 BasicBlock *InsertAtEnd) {
1871 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1872 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1873 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1876 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1877 const std::string &Name,
1878 Instruction *InsertBefore) {
1879 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1880 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1881 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
1884 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1885 const std::string &Name,
1886 BasicBlock *InsertAtEnd) {
1887 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1888 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1889 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1892 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
1893 const std::string &Name,
1894 Instruction *InsertBefore) {
1895 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1896 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1897 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1900 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
1901 const std::string &Name,
1902 BasicBlock *InsertAtEnd) {
1903 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1904 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1905 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1908 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
1909 const std::string &Name,
1910 BasicBlock *InsertAtEnd) {
1911 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1912 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1915 if (Ty->isInteger())
1916 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1917 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1920 /// @brief Create a BitCast or a PtrToInt cast instruction
1921 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
1922 const std::string &Name,
1923 Instruction *InsertBefore) {
1924 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1925 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1928 if (Ty->isInteger())
1929 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1930 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1933 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
1934 bool isSigned, const std::string &Name,
1935 Instruction *InsertBefore) {
1936 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1937 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1938 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1939 Instruction::CastOps opcode =
1940 (SrcBits == DstBits ? Instruction::BitCast :
1941 (SrcBits > DstBits ? Instruction::Trunc :
1942 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1943 return Create(opcode, C, Ty, Name, InsertBefore);
1946 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
1947 bool isSigned, const std::string &Name,
1948 BasicBlock *InsertAtEnd) {
1949 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1950 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1951 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1952 Instruction::CastOps opcode =
1953 (SrcBits == DstBits ? Instruction::BitCast :
1954 (SrcBits > DstBits ? Instruction::Trunc :
1955 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1956 return Create(opcode, C, Ty, Name, InsertAtEnd);
1959 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
1960 const std::string &Name,
1961 Instruction *InsertBefore) {
1962 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1964 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1965 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1966 Instruction::CastOps opcode =
1967 (SrcBits == DstBits ? Instruction::BitCast :
1968 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1969 return Create(opcode, C, Ty, Name, InsertBefore);
1972 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
1973 const std::string &Name,
1974 BasicBlock *InsertAtEnd) {
1975 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1977 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1978 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1979 Instruction::CastOps opcode =
1980 (SrcBits == DstBits ? Instruction::BitCast :
1981 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1982 return Create(opcode, C, Ty, Name, InsertAtEnd);
1985 // Check whether it is valid to call getCastOpcode for these types.
1986 // This routine must be kept in sync with getCastOpcode.
1987 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1988 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1991 if (SrcTy == DestTy)
1994 // Get the bit sizes, we'll need these
1995 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1996 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1998 // Run through the possibilities ...
1999 if (DestTy->isInteger()) { // Casting to integral
2000 if (SrcTy->isInteger()) { // Casting from integral
2002 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2004 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2005 // Casting from vector
2006 return DestBits == PTy->getBitWidth();
2007 } else { // Casting from something else
2008 return isa<PointerType>(SrcTy);
2010 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2011 if (SrcTy->isInteger()) { // Casting from integral
2013 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2015 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2016 // Casting from vector
2017 return DestBits == PTy->getBitWidth();
2018 } else { // Casting from something else
2021 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2022 // Casting to vector
2023 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2024 // Casting from vector
2025 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2026 } else { // Casting from something else
2027 return DestPTy->getBitWidth() == SrcBits;
2029 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2030 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2032 } else if (SrcTy->isInteger()) { // Casting from integral
2034 } else { // Casting from something else
2037 } else { // Casting to something else
2042 // Provide a way to get a "cast" where the cast opcode is inferred from the
2043 // types and size of the operand. This, basically, is a parallel of the
2044 // logic in the castIsValid function below. This axiom should hold:
2045 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2046 // should not assert in castIsValid. In other words, this produces a "correct"
2047 // casting opcode for the arguments passed to it.
2048 // This routine must be kept in sync with isCastable.
2049 Instruction::CastOps
2050 CastInst::getCastOpcode(
2051 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2052 // Get the bit sizes, we'll need these
2053 const Type *SrcTy = Src->getType();
2054 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2055 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2057 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2058 "Only first class types are castable!");
2060 // Run through the possibilities ...
2061 if (DestTy->isInteger()) { // Casting to integral
2062 if (SrcTy->isInteger()) { // Casting from integral
2063 if (DestBits < SrcBits)
2064 return Trunc; // int -> smaller int
2065 else if (DestBits > SrcBits) { // its an extension
2067 return SExt; // signed -> SEXT
2069 return ZExt; // unsigned -> ZEXT
2071 return BitCast; // Same size, No-op cast
2073 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2075 return FPToSI; // FP -> sint
2077 return FPToUI; // FP -> uint
2078 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2079 assert(DestBits == PTy->getBitWidth() &&
2080 "Casting vector to integer of different width");
2081 return BitCast; // Same size, no-op cast
2083 assert(isa<PointerType>(SrcTy) &&
2084 "Casting from a value that is not first-class type");
2085 return PtrToInt; // ptr -> int
2087 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2088 if (SrcTy->isInteger()) { // Casting from integral
2090 return SIToFP; // sint -> FP
2092 return UIToFP; // uint -> FP
2093 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2094 if (DestBits < SrcBits) {
2095 return FPTrunc; // FP -> smaller FP
2096 } else if (DestBits > SrcBits) {
2097 return FPExt; // FP -> larger FP
2099 return BitCast; // same size, no-op cast
2101 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2102 assert(DestBits == PTy->getBitWidth() &&
2103 "Casting vector to floating point of different width");
2104 return BitCast; // same size, no-op cast
2106 assert(0 && "Casting pointer or non-first class to float");
2108 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2109 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2110 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2111 "Casting vector to vector of different widths");
2112 return BitCast; // vector -> vector
2113 } else if (DestPTy->getBitWidth() == SrcBits) {
2114 return BitCast; // float/int -> vector
2116 assert(!"Illegal cast to vector (wrong type or size)");
2118 } else if (isa<PointerType>(DestTy)) {
2119 if (isa<PointerType>(SrcTy)) {
2120 return BitCast; // ptr -> ptr
2121 } else if (SrcTy->isInteger()) {
2122 return IntToPtr; // int -> ptr
2124 assert(!"Casting pointer to other than pointer or int");
2127 assert(!"Casting to type that is not first-class");
2130 // If we fall through to here we probably hit an assertion cast above
2131 // and assertions are not turned on. Anything we return is an error, so
2132 // BitCast is as good a choice as any.
2136 //===----------------------------------------------------------------------===//
2137 // CastInst SubClass Constructors
2138 //===----------------------------------------------------------------------===//
2140 /// Check that the construction parameters for a CastInst are correct. This
2141 /// could be broken out into the separate constructors but it is useful to have
2142 /// it in one place and to eliminate the redundant code for getting the sizes
2143 /// of the types involved.
2145 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2147 // Check for type sanity on the arguments
2148 const Type *SrcTy = S->getType();
2149 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2152 // Get the size of the types in bits, we'll need this later
2153 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2154 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2156 // Switch on the opcode provided
2158 default: return false; // This is an input error
2159 case Instruction::Trunc:
2160 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2161 case Instruction::ZExt:
2162 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2163 case Instruction::SExt:
2164 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2165 case Instruction::FPTrunc:
2166 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2167 SrcBitSize > DstBitSize;
2168 case Instruction::FPExt:
2169 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2170 SrcBitSize < DstBitSize;
2171 case Instruction::UIToFP:
2172 case Instruction::SIToFP:
2173 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2174 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2175 return SVTy->getElementType()->isInteger() &&
2176 DVTy->getElementType()->isFloatingPoint() &&
2177 SVTy->getNumElements() == DVTy->getNumElements();
2180 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2181 case Instruction::FPToUI:
2182 case Instruction::FPToSI:
2183 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2184 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2185 return SVTy->getElementType()->isFloatingPoint() &&
2186 DVTy->getElementType()->isInteger() &&
2187 SVTy->getNumElements() == DVTy->getNumElements();
2190 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2191 case Instruction::PtrToInt:
2192 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2193 case Instruction::IntToPtr:
2194 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2195 case Instruction::BitCast:
2196 // BitCast implies a no-op cast of type only. No bits change.
2197 // However, you can't cast pointers to anything but pointers.
2198 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2201 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2202 // these cases, the cast is okay if the source and destination bit widths
2204 return SrcBitSize == DstBitSize;
2208 TruncInst::TruncInst(
2209 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2210 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2211 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2214 TruncInst::TruncInst(
2215 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2216 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2217 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2221 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2222 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2223 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2227 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2228 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2229 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2232 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2233 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2234 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2238 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2239 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2240 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2243 FPTruncInst::FPTruncInst(
2244 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2245 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2246 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2249 FPTruncInst::FPTruncInst(
2250 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2251 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2252 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2255 FPExtInst::FPExtInst(
2256 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2257 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2258 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2261 FPExtInst::FPExtInst(
2262 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2263 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2264 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2267 UIToFPInst::UIToFPInst(
2268 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2269 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2270 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2273 UIToFPInst::UIToFPInst(
2274 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2275 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2276 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2279 SIToFPInst::SIToFPInst(
2280 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2281 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2282 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2285 SIToFPInst::SIToFPInst(
2286 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2287 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2288 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2291 FPToUIInst::FPToUIInst(
2292 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2293 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2294 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2297 FPToUIInst::FPToUIInst(
2298 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2299 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2300 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2303 FPToSIInst::FPToSIInst(
2304 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2305 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2306 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2309 FPToSIInst::FPToSIInst(
2310 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2311 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2312 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2315 PtrToIntInst::PtrToIntInst(
2316 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2317 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2318 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2321 PtrToIntInst::PtrToIntInst(
2322 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2323 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2324 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2327 IntToPtrInst::IntToPtrInst(
2328 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2329 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2330 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2333 IntToPtrInst::IntToPtrInst(
2334 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2335 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2336 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2339 BitCastInst::BitCastInst(
2340 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2341 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2342 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2345 BitCastInst::BitCastInst(
2346 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2347 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2348 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2351 //===----------------------------------------------------------------------===//
2353 //===----------------------------------------------------------------------===//
2355 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2356 Value *LHS, Value *RHS, const std::string &Name,
2357 Instruction *InsertBefore)
2358 : Instruction(ty, op,
2359 OperandTraits<CmpInst>::op_begin(this),
2360 OperandTraits<CmpInst>::operands(this),
2362 Op<0>().init(LHS, this);
2363 Op<1>().init(RHS, this);
2364 SubclassData = predicate;
2368 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2369 Value *LHS, Value *RHS, const std::string &Name,
2370 BasicBlock *InsertAtEnd)
2371 : Instruction(ty, op,
2372 OperandTraits<CmpInst>::op_begin(this),
2373 OperandTraits<CmpInst>::operands(this),
2375 Op<0>().init(LHS, this);
2376 Op<1>().init(RHS, this);
2377 SubclassData = predicate;
2382 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2383 const std::string &Name, Instruction *InsertBefore) {
2384 if (Op == Instruction::ICmp) {
2385 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2388 if (Op == Instruction::FCmp) {
2389 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2392 if (Op == Instruction::VICmp) {
2393 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2396 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2401 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2402 const std::string &Name, BasicBlock *InsertAtEnd) {
2403 if (Op == Instruction::ICmp) {
2404 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2407 if (Op == Instruction::FCmp) {
2408 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2411 if (Op == Instruction::VICmp) {
2412 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2415 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2419 void CmpInst::swapOperands() {
2420 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2423 cast<FCmpInst>(this)->swapOperands();
2426 bool CmpInst::isCommutative() {
2427 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2428 return IC->isCommutative();
2429 return cast<FCmpInst>(this)->isCommutative();
2432 bool CmpInst::isEquality() {
2433 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2434 return IC->isEquality();
2435 return cast<FCmpInst>(this)->isEquality();
2439 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2442 assert(!"Unknown icmp predicate!");
2443 case ICMP_EQ: return ICMP_NE;
2444 case ICMP_NE: return ICMP_EQ;
2445 case ICMP_UGT: return ICMP_ULE;
2446 case ICMP_ULT: return ICMP_UGE;
2447 case ICMP_UGE: return ICMP_ULT;
2448 case ICMP_ULE: return ICMP_UGT;
2449 case ICMP_SGT: return ICMP_SLE;
2450 case ICMP_SLT: return ICMP_SGE;
2451 case ICMP_SGE: return ICMP_SLT;
2452 case ICMP_SLE: return ICMP_SGT;
2456 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2458 default: assert(! "Unknown icmp predicate!");
2459 case ICMP_EQ: case ICMP_NE:
2461 case ICMP_SGT: return ICMP_SLT;
2462 case ICMP_SLT: return ICMP_SGT;
2463 case ICMP_SGE: return ICMP_SLE;
2464 case ICMP_SLE: return ICMP_SGE;
2465 case ICMP_UGT: return ICMP_ULT;
2466 case ICMP_ULT: return ICMP_UGT;
2467 case ICMP_UGE: return ICMP_ULE;
2468 case ICMP_ULE: return ICMP_UGE;
2472 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2474 default: assert(! "Unknown icmp predicate!");
2475 case ICMP_EQ: case ICMP_NE:
2476 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2478 case ICMP_UGT: return ICMP_SGT;
2479 case ICMP_ULT: return ICMP_SLT;
2480 case ICMP_UGE: return ICMP_SGE;
2481 case ICMP_ULE: return ICMP_SLE;
2485 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2487 default: assert(! "Unknown icmp predicate!");
2488 case ICMP_EQ: case ICMP_NE:
2489 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2491 case ICMP_SGT: return ICMP_UGT;
2492 case ICMP_SLT: return ICMP_ULT;
2493 case ICMP_SGE: return ICMP_UGE;
2494 case ICMP_SLE: return ICMP_ULE;
2498 bool ICmpInst::isSignedPredicate(Predicate pred) {
2500 default: assert(! "Unknown icmp predicate!");
2501 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2503 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2504 case ICMP_UGE: case ICMP_ULE:
2509 /// Initialize a set of values that all satisfy the condition with C.
2512 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2515 uint32_t BitWidth = C.getBitWidth();
2517 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2518 case ICmpInst::ICMP_EQ: Upper++; break;
2519 case ICmpInst::ICMP_NE: Lower++; break;
2520 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2521 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2522 case ICmpInst::ICMP_UGT:
2523 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2525 case ICmpInst::ICMP_SGT:
2526 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2528 case ICmpInst::ICMP_ULE:
2529 Lower = APInt::getMinValue(BitWidth); Upper++;
2531 case ICmpInst::ICMP_SLE:
2532 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2534 case ICmpInst::ICMP_UGE:
2535 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2537 case ICmpInst::ICMP_SGE:
2538 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2541 return ConstantRange(Lower, Upper);
2544 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2547 assert(!"Unknown icmp predicate!");
2548 case FCMP_OEQ: return FCMP_UNE;
2549 case FCMP_ONE: return FCMP_UEQ;
2550 case FCMP_OGT: return FCMP_ULE;
2551 case FCMP_OLT: return FCMP_UGE;
2552 case FCMP_OGE: return FCMP_ULT;
2553 case FCMP_OLE: return FCMP_UGT;
2554 case FCMP_UEQ: return FCMP_ONE;
2555 case FCMP_UNE: return FCMP_OEQ;
2556 case FCMP_UGT: return FCMP_OLE;
2557 case FCMP_ULT: return FCMP_OGE;
2558 case FCMP_UGE: return FCMP_OLT;
2559 case FCMP_ULE: return FCMP_OGT;
2560 case FCMP_ORD: return FCMP_UNO;
2561 case FCMP_UNO: return FCMP_ORD;
2562 case FCMP_TRUE: return FCMP_FALSE;
2563 case FCMP_FALSE: return FCMP_TRUE;
2567 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2569 default: assert(!"Unknown fcmp predicate!");
2570 case FCMP_FALSE: case FCMP_TRUE:
2571 case FCMP_OEQ: case FCMP_ONE:
2572 case FCMP_UEQ: case FCMP_UNE:
2573 case FCMP_ORD: case FCMP_UNO:
2575 case FCMP_OGT: return FCMP_OLT;
2576 case FCMP_OLT: return FCMP_OGT;
2577 case FCMP_OGE: return FCMP_OLE;
2578 case FCMP_OLE: return FCMP_OGE;
2579 case FCMP_UGT: return FCMP_ULT;
2580 case FCMP_ULT: return FCMP_UGT;
2581 case FCMP_UGE: return FCMP_ULE;
2582 case FCMP_ULE: return FCMP_UGE;
2586 bool CmpInst::isUnsigned(unsigned short predicate) {
2587 switch (predicate) {
2588 default: return false;
2589 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2590 case ICmpInst::ICMP_UGE: return true;
2594 bool CmpInst::isSigned(unsigned short predicate){
2595 switch (predicate) {
2596 default: return false;
2597 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2598 case ICmpInst::ICMP_SGE: return true;
2602 bool CmpInst::isOrdered(unsigned short predicate) {
2603 switch (predicate) {
2604 default: return false;
2605 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2606 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2607 case FCmpInst::FCMP_ORD: return true;
2611 bool CmpInst::isUnordered(unsigned short predicate) {
2612 switch (predicate) {
2613 default: return false;
2614 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2615 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2616 case FCmpInst::FCMP_UNO: return true;
2620 //===----------------------------------------------------------------------===//
2621 // SwitchInst Implementation
2622 //===----------------------------------------------------------------------===//
2624 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2625 assert(Value && Default);
2626 ReservedSpace = 2+NumCases*2;
2628 OperandList = allocHungoffUses(ReservedSpace);
2630 OperandList[0].init(Value, this);
2631 OperandList[1].init(Default, this);
2634 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2635 /// switch on and a default destination. The number of additional cases can
2636 /// be specified here to make memory allocation more efficient. This
2637 /// constructor can also autoinsert before another instruction.
2638 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2639 Instruction *InsertBefore)
2640 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2641 init(Value, Default, NumCases);
2644 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2645 /// switch on and a default destination. The number of additional cases can
2646 /// be specified here to make memory allocation more efficient. This
2647 /// constructor also autoinserts at the end of the specified BasicBlock.
2648 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2649 BasicBlock *InsertAtEnd)
2650 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2651 init(Value, Default, NumCases);
2654 SwitchInst::SwitchInst(const SwitchInst &SI)
2655 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2656 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2657 Use *OL = OperandList, *InOL = SI.OperandList;
2658 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2659 OL[i].init(InOL[i], this);
2660 OL[i+1].init(InOL[i+1], this);
2664 SwitchInst::~SwitchInst() {
2665 dropHungoffUses(OperandList);
2669 /// addCase - Add an entry to the switch instruction...
2671 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2672 unsigned OpNo = NumOperands;
2673 if (OpNo+2 > ReservedSpace)
2674 resizeOperands(0); // Get more space!
2675 // Initialize some new operands.
2676 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2677 NumOperands = OpNo+2;
2678 OperandList[OpNo].init(OnVal, this);
2679 OperandList[OpNo+1].init(Dest, this);
2682 /// removeCase - This method removes the specified successor from the switch
2683 /// instruction. Note that this cannot be used to remove the default
2684 /// destination (successor #0).
2686 void SwitchInst::removeCase(unsigned idx) {
2687 assert(idx != 0 && "Cannot remove the default case!");
2688 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2690 unsigned NumOps = getNumOperands();
2691 Use *OL = OperandList;
2693 // Move everything after this operand down.
2695 // FIXME: we could just swap with the end of the list, then erase. However,
2696 // client might not expect this to happen. The code as it is thrashes the
2697 // use/def lists, which is kinda lame.
2698 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2700 OL[i-2+1] = OL[i+1];
2703 // Nuke the last value.
2704 OL[NumOps-2].set(0);
2705 OL[NumOps-2+1].set(0);
2706 NumOperands = NumOps-2;
2709 /// resizeOperands - resize operands - This adjusts the length of the operands
2710 /// list according to the following behavior:
2711 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2712 /// of operation. This grows the number of ops by 3 times.
2713 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2714 /// 3. If NumOps == NumOperands, trim the reserved space.
2716 void SwitchInst::resizeOperands(unsigned NumOps) {
2717 unsigned e = getNumOperands();
2720 } else if (NumOps*2 > NumOperands) {
2721 // No resize needed.
2722 if (ReservedSpace >= NumOps) return;
2723 } else if (NumOps == NumOperands) {
2724 if (ReservedSpace == NumOps) return;
2729 ReservedSpace = NumOps;
2730 Use *NewOps = allocHungoffUses(NumOps);
2731 Use *OldOps = OperandList;
2732 for (unsigned i = 0; i != e; ++i) {
2733 NewOps[i].init(OldOps[i], this);
2735 OperandList = NewOps;
2736 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2740 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2741 return getSuccessor(idx);
2743 unsigned SwitchInst::getNumSuccessorsV() const {
2744 return getNumSuccessors();
2746 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2747 setSuccessor(idx, B);
2750 //===----------------------------------------------------------------------===//
2751 // GetResultInst Implementation
2752 //===----------------------------------------------------------------------===//
2754 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2755 const std::string &Name,
2756 Instruction *InsertBef)
2757 : UnaryInstruction(cast<StructType>(Aggregate->getType())
2758 ->getElementType(Index),
2759 GetResult, Aggregate, InsertBef),
2761 assert(isValidOperands(Aggregate, Index)
2762 && "Invalid GetResultInst operands!");
2766 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2770 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2771 unsigned NumElements = STy->getNumElements();
2772 if (Index >= NumElements || NumElements == 0)
2775 // getresult aggregate value's element types are restricted to
2776 // avoid nested aggregates.
2777 for (unsigned i = 0; i < NumElements; ++i)
2778 if (!STy->getElementType(i)->isFirstClassType())
2781 // Otherwise, Aggregate is valid.
2787 // Define these methods here so vtables don't get emitted into every translation
2788 // unit that uses these classes.
2790 GetElementPtrInst *GetElementPtrInst::clone() const {
2791 return new(getNumOperands()) GetElementPtrInst(*this);
2794 BinaryOperator *BinaryOperator::clone() const {
2795 return Create(getOpcode(), Op<0>(), Op<1>());
2798 FCmpInst* FCmpInst::clone() const {
2799 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2801 ICmpInst* ICmpInst::clone() const {
2802 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2805 VFCmpInst* VFCmpInst::clone() const {
2806 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2808 VICmpInst* VICmpInst::clone() const {
2809 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2812 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2813 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2814 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2815 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2816 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2817 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2818 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2819 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2820 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2821 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2822 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2823 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2824 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2825 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2826 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2827 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2828 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2829 CallInst *CallInst::clone() const {
2830 return new(getNumOperands()) CallInst(*this);
2832 SelectInst *SelectInst::clone() const {
2833 return new(getNumOperands()) SelectInst(*this);
2835 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2837 ExtractElementInst *ExtractElementInst::clone() const {
2838 return new ExtractElementInst(*this);
2840 InsertElementInst *InsertElementInst::clone() const {
2841 return InsertElementInst::Create(*this);
2843 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2844 return new ShuffleVectorInst(*this);
2846 PHINode *PHINode::clone() const { return new PHINode(*this); }
2847 ReturnInst *ReturnInst::clone() const {
2848 return new(getNumOperands()) ReturnInst(*this);
2850 BranchInst *BranchInst::clone() const {
2851 return new(getNumOperands()) BranchInst(*this);
2853 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2854 InvokeInst *InvokeInst::clone() const {
2855 return new(getNumOperands()) InvokeInst(*this);
2857 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2858 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2859 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }