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 bool CallInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
377 if (ParamAttrs.paramHasAttr(i, attr))
379 if (const Function *F = getCalledFunction())
380 return F->paramHasAttr(i, attr);
384 void CallInst::setDoesNotThrow(bool doesNotThrow) {
385 PAListPtr PAL = getParamAttrs();
387 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
389 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
394 //===----------------------------------------------------------------------===//
395 // InvokeInst Implementation
396 //===----------------------------------------------------------------------===//
398 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
399 Value* const *Args, unsigned NumArgs) {
400 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
401 Use *OL = OperandList;
402 OL[0].init(Fn, this);
403 OL[1].init(IfNormal, this);
404 OL[2].init(IfException, this);
405 const FunctionType *FTy =
406 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
407 FTy = FTy; // silence warning.
409 assert(((NumArgs == FTy->getNumParams()) ||
410 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
411 "Calling a function with bad signature");
413 for (unsigned i = 0, e = NumArgs; i != e; i++) {
414 assert((i >= FTy->getNumParams() ||
415 FTy->getParamType(i) == Args[i]->getType()) &&
416 "Invoking a function with a bad signature!");
418 OL[i+3].init(Args[i], this);
422 InvokeInst::InvokeInst(const InvokeInst &II)
423 : TerminatorInst(II.getType(), Instruction::Invoke,
424 OperandTraits<InvokeInst>::op_end(this) - II.getNumOperands(),
425 II.getNumOperands()) {
426 setParamAttrs(II.getParamAttrs());
427 SubclassData = II.SubclassData;
428 Use *OL = OperandList, *InOL = II.OperandList;
429 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
430 OL[i].init(InOL[i], this);
433 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
434 return getSuccessor(idx);
436 unsigned InvokeInst::getNumSuccessorsV() const {
437 return getNumSuccessors();
439 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
440 return setSuccessor(idx, B);
443 bool InvokeInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
444 if (ParamAttrs.paramHasAttr(i, attr))
446 if (const Function *F = getCalledFunction())
447 return F->paramHasAttr(i, attr);
451 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
452 PAListPtr PAL = getParamAttrs();
454 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
456 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
461 //===----------------------------------------------------------------------===//
462 // ReturnInst Implementation
463 //===----------------------------------------------------------------------===//
465 ReturnInst::ReturnInst(const ReturnInst &RI)
466 : TerminatorInst(Type::VoidTy, Instruction::Ret,
467 OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(),
468 RI.getNumOperands()) {
469 unsigned N = RI.getNumOperands();
471 Op<0>().init(RI.Op<0>(), this);
473 Use *OL = OperandList;
474 for (unsigned i = 0; i < N; ++i)
475 OL[i].init(RI.getOperand(i), this);
479 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
480 : TerminatorInst(Type::VoidTy, Instruction::Ret,
481 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
482 retVal != 0, InsertBefore) {
486 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
487 : TerminatorInst(Type::VoidTy, Instruction::Ret,
488 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
489 retVal != 0, InsertAtEnd) {
493 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
494 : TerminatorInst(Type::VoidTy, Instruction::Ret,
495 OperandTraits<ReturnInst>::op_end(this),
499 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
500 Instruction *InsertBefore)
501 : TerminatorInst(Type::VoidTy, Instruction::Ret,
502 OperandTraits<ReturnInst>::op_end(this) - N,
507 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
508 BasicBlock *InsertAtEnd)
509 : TerminatorInst(Type::VoidTy, Instruction::Ret,
510 OperandTraits<ReturnInst>::op_end(this) - N,
516 void ReturnInst::init(Value * const* retVals, unsigned N) {
517 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
520 if (NumOperands == 1) {
522 if (V->getType() == Type::VoidTy)
524 Op<0>().init(V, this);
528 Use *OL = OperandList;
529 for (unsigned i = 0; i < NumOperands; ++i) {
530 Value *V = *retVals++;
531 assert(!isa<BasicBlock>(V) &&
532 "Cannot return basic block. Probably using the incorrect ctor");
537 unsigned ReturnInst::getNumSuccessorsV() const {
538 return getNumSuccessors();
541 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
542 /// emit the vtable for the class in this translation unit.
543 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
544 assert(0 && "ReturnInst has no successors!");
547 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
548 assert(0 && "ReturnInst has no successors!");
553 ReturnInst::~ReturnInst() {
556 //===----------------------------------------------------------------------===//
557 // UnwindInst Implementation
558 //===----------------------------------------------------------------------===//
560 UnwindInst::UnwindInst(Instruction *InsertBefore)
561 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
563 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
564 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
568 unsigned UnwindInst::getNumSuccessorsV() const {
569 return getNumSuccessors();
572 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
573 assert(0 && "UnwindInst has no successors!");
576 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
577 assert(0 && "UnwindInst has no successors!");
582 //===----------------------------------------------------------------------===//
583 // UnreachableInst Implementation
584 //===----------------------------------------------------------------------===//
586 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
587 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
589 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
590 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
593 unsigned UnreachableInst::getNumSuccessorsV() const {
594 return getNumSuccessors();
597 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
598 assert(0 && "UnwindInst has no successors!");
601 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
602 assert(0 && "UnwindInst has no successors!");
607 //===----------------------------------------------------------------------===//
608 // BranchInst Implementation
609 //===----------------------------------------------------------------------===//
611 void BranchInst::AssertOK() {
613 assert(getCondition()->getType() == Type::Int1Ty &&
614 "May only branch on boolean predicates!");
617 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
618 : TerminatorInst(Type::VoidTy, Instruction::Br,
619 OperandTraits<BranchInst>::op_end(this) - 1,
621 assert(IfTrue != 0 && "Branch destination may not be null!");
622 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
624 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
625 Instruction *InsertBefore)
626 : TerminatorInst(Type::VoidTy, Instruction::Br,
627 OperandTraits<BranchInst>::op_end(this) - 3,
629 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
630 Op<1>().init(reinterpret_cast<Value*>(IfFalse), this);
631 Op<2>().init(Cond, this);
637 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
638 : TerminatorInst(Type::VoidTy, Instruction::Br,
639 OperandTraits<BranchInst>::op_end(this) - 1,
641 assert(IfTrue != 0 && "Branch destination may not be null!");
642 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
645 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
646 BasicBlock *InsertAtEnd)
647 : TerminatorInst(Type::VoidTy, Instruction::Br,
648 OperandTraits<BranchInst>::op_end(this) - 3,
650 Op<0>().init(reinterpret_cast<Value*>(IfTrue), this);
651 Op<1>().init(reinterpret_cast<Value*>(IfFalse), this);
652 Op<2>().init(Cond, this);
659 BranchInst::BranchInst(const BranchInst &BI) :
660 TerminatorInst(Type::VoidTy, Instruction::Br,
661 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
662 BI.getNumOperands()) {
663 OperandList[0].init(BI.getOperand(0), this);
664 if (BI.getNumOperands() != 1) {
665 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
666 OperandList[1].init(BI.getOperand(1), this);
667 OperandList[2].init(BI.getOperand(2), this);
671 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
672 return getSuccessor(idx);
674 unsigned BranchInst::getNumSuccessorsV() const {
675 return getNumSuccessors();
677 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
678 setSuccessor(idx, B);
682 //===----------------------------------------------------------------------===//
683 // AllocationInst Implementation
684 //===----------------------------------------------------------------------===//
686 static Value *getAISize(Value *Amt) {
688 Amt = ConstantInt::get(Type::Int32Ty, 1);
690 assert(!isa<BasicBlock>(Amt) &&
691 "Passed basic block into allocation size parameter! Use other ctor");
692 assert(Amt->getType() == Type::Int32Ty &&
693 "Malloc/Allocation array size is not a 32-bit integer!");
698 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
699 unsigned Align, const std::string &Name,
700 Instruction *InsertBefore)
701 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
704 assert(Ty != Type::VoidTy && "Cannot allocate void!");
708 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
709 unsigned Align, const std::string &Name,
710 BasicBlock *InsertAtEnd)
711 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
714 assert(Ty != Type::VoidTy && "Cannot allocate void!");
718 // Out of line virtual method, so the vtable, etc has a home.
719 AllocationInst::~AllocationInst() {
722 void AllocationInst::setAlignment(unsigned Align) {
723 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
724 SubclassData = Log2_32(Align) + 1;
725 assert(getAlignment() == Align && "Alignment representation error!");
728 bool AllocationInst::isArrayAllocation() const {
729 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
730 return CI->getZExtValue() != 1;
734 const Type *AllocationInst::getAllocatedType() const {
735 return getType()->getElementType();
738 AllocaInst::AllocaInst(const AllocaInst &AI)
739 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
740 Instruction::Alloca, AI.getAlignment()) {
743 MallocInst::MallocInst(const MallocInst &MI)
744 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
745 Instruction::Malloc, MI.getAlignment()) {
748 //===----------------------------------------------------------------------===//
749 // FreeInst Implementation
750 //===----------------------------------------------------------------------===//
752 void FreeInst::AssertOK() {
753 assert(isa<PointerType>(getOperand(0)->getType()) &&
754 "Can not free something of nonpointer type!");
757 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
758 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
762 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
763 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
768 //===----------------------------------------------------------------------===//
769 // LoadInst Implementation
770 //===----------------------------------------------------------------------===//
772 void LoadInst::AssertOK() {
773 assert(isa<PointerType>(getOperand(0)->getType()) &&
774 "Ptr must have pointer type.");
777 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
778 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
779 Load, Ptr, InsertBef) {
786 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
787 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
788 Load, Ptr, InsertAE) {
795 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
796 Instruction *InsertBef)
797 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
798 Load, Ptr, InsertBef) {
799 setVolatile(isVolatile);
805 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
806 unsigned Align, Instruction *InsertBef)
807 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
808 Load, Ptr, InsertBef) {
809 setVolatile(isVolatile);
815 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
816 unsigned Align, BasicBlock *InsertAE)
817 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
818 Load, Ptr, InsertAE) {
819 setVolatile(isVolatile);
825 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
826 BasicBlock *InsertAE)
827 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
828 Load, Ptr, InsertAE) {
829 setVolatile(isVolatile);
837 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
838 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
839 Load, Ptr, InsertBef) {
843 if (Name && Name[0]) setName(Name);
846 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
847 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
848 Load, Ptr, InsertAE) {
852 if (Name && Name[0]) setName(Name);
855 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
856 Instruction *InsertBef)
857 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
858 Load, Ptr, InsertBef) {
859 setVolatile(isVolatile);
862 if (Name && Name[0]) setName(Name);
865 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
866 BasicBlock *InsertAE)
867 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
868 Load, Ptr, InsertAE) {
869 setVolatile(isVolatile);
872 if (Name && Name[0]) setName(Name);
875 void LoadInst::setAlignment(unsigned Align) {
876 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
877 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
880 //===----------------------------------------------------------------------===//
881 // StoreInst Implementation
882 //===----------------------------------------------------------------------===//
884 void StoreInst::AssertOK() {
885 assert(isa<PointerType>(getOperand(1)->getType()) &&
886 "Ptr must have pointer type!");
887 assert(getOperand(0)->getType() ==
888 cast<PointerType>(getOperand(1)->getType())->getElementType()
889 && "Ptr must be a pointer to Val type!");
893 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
894 : Instruction(Type::VoidTy, Store,
895 OperandTraits<StoreInst>::op_begin(this),
896 OperandTraits<StoreInst>::operands(this),
898 Op<0>().init(val, this);
899 Op<1>().init(addr, this);
905 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
906 : Instruction(Type::VoidTy, Store,
907 OperandTraits<StoreInst>::op_begin(this),
908 OperandTraits<StoreInst>::operands(this),
910 Op<0>().init(val, this);
911 Op<1>().init(addr, this);
917 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
918 Instruction *InsertBefore)
919 : Instruction(Type::VoidTy, Store,
920 OperandTraits<StoreInst>::op_begin(this),
921 OperandTraits<StoreInst>::operands(this),
923 Op<0>().init(val, this);
924 Op<1>().init(addr, this);
925 setVolatile(isVolatile);
930 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
931 unsigned Align, Instruction *InsertBefore)
932 : Instruction(Type::VoidTy, Store,
933 OperandTraits<StoreInst>::op_begin(this),
934 OperandTraits<StoreInst>::operands(this),
936 Op<0>().init(val, this);
937 Op<1>().init(addr, this);
938 setVolatile(isVolatile);
943 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
944 unsigned Align, BasicBlock *InsertAtEnd)
945 : Instruction(Type::VoidTy, Store,
946 OperandTraits<StoreInst>::op_begin(this),
947 OperandTraits<StoreInst>::operands(this),
949 Op<0>().init(val, this);
950 Op<1>().init(addr, this);
951 setVolatile(isVolatile);
956 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
957 BasicBlock *InsertAtEnd)
958 : Instruction(Type::VoidTy, Store,
959 OperandTraits<StoreInst>::op_begin(this),
960 OperandTraits<StoreInst>::operands(this),
962 Op<0>().init(val, this);
963 Op<1>().init(addr, this);
964 setVolatile(isVolatile);
969 void StoreInst::setAlignment(unsigned Align) {
970 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
971 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
974 //===----------------------------------------------------------------------===//
975 // GetElementPtrInst Implementation
976 //===----------------------------------------------------------------------===//
978 static unsigned retrieveAddrSpace(const Value *Val) {
979 return cast<PointerType>(Val->getType())->getAddressSpace();
982 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
983 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
984 Use *OL = OperandList;
985 OL[0].init(Ptr, this);
987 for (unsigned i = 0; i != NumIdx; ++i)
988 OL[i+1].init(Idx[i], this);
991 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
992 assert(NumOperands == 2 && "NumOperands not initialized?");
993 Use *OL = OperandList;
994 OL[0].init(Ptr, this);
995 OL[1].init(Idx, this);
998 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
999 : Instruction(reinterpret_cast<const Type*>(GEPI.getType()), GetElementPtr,
1000 OperandTraits<GetElementPtrInst>::op_end(this) - GEPI.getNumOperands(),
1001 GEPI.getNumOperands()) {
1002 Use *OL = OperandList;
1003 Use *GEPIOL = GEPI.OperandList;
1004 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1005 OL[i].init(GEPIOL[i], this);
1008 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1009 const std::string &Name, Instruction *InBe)
1010 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1011 retrieveAddrSpace(Ptr)),
1013 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1019 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1020 const std::string &Name, BasicBlock *IAE)
1021 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1022 retrieveAddrSpace(Ptr)),
1024 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1030 // getIndexedType - Returns the type of the element that would be loaded with
1031 // a load instruction with the specified parameters.
1033 // A null type is returned if the indices are invalid for the specified
1036 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1039 bool AllowCompositeLeaf) {
1040 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
1042 // Handle the special case of the empty set index set...
1044 if (AllowCompositeLeaf ||
1045 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
1046 return cast<PointerType>(Ptr)->getElementType();
1051 unsigned CurIdx = 0;
1052 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1053 if (NumIdx == CurIdx) {
1054 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1055 return 0; // Can't load a whole structure or array!?!?
1058 Value *Index = Idxs[CurIdx++];
1059 if (isa<PointerType>(CT) && CurIdx != 1)
1060 return 0; // Can only index into pointer types at the first index!
1061 if (!CT->indexValid(Index)) return 0;
1062 Ptr = CT->getTypeAtIndex(Index);
1064 // If the new type forwards to another type, then it is in the middle
1065 // of being refined to another type (and hence, may have dropped all
1066 // references to what it was using before). So, use the new forwarded
1068 if (const Type * Ty = Ptr->getForwardedType()) {
1072 return CurIdx == NumIdx ? Ptr : 0;
1075 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1076 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1077 if (!PTy) return 0; // Type isn't a pointer type!
1079 // Check the pointer index.
1080 if (!PTy->indexValid(Idx)) return 0;
1082 return PTy->getElementType();
1086 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1087 /// zeros. If so, the result pointer and the first operand have the same
1088 /// value, just potentially different types.
1089 bool GetElementPtrInst::hasAllZeroIndices() const {
1090 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1091 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1092 if (!CI->isZero()) return false;
1100 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1101 /// constant integers. If so, the result pointer and the first operand have
1102 /// a constant offset between them.
1103 bool GetElementPtrInst::hasAllConstantIndices() const {
1104 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1105 if (!isa<ConstantInt>(getOperand(i)))
1112 //===----------------------------------------------------------------------===//
1113 // ExtractElementInst Implementation
1114 //===----------------------------------------------------------------------===//
1116 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1117 const std::string &Name,
1118 Instruction *InsertBef)
1119 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1121 OperandTraits<ExtractElementInst>::op_begin(this),
1123 assert(isValidOperands(Val, Index) &&
1124 "Invalid extractelement instruction operands!");
1125 Op<0>().init(Val, this);
1126 Op<1>().init(Index, this);
1130 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1131 const std::string &Name,
1132 Instruction *InsertBef)
1133 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1135 OperandTraits<ExtractElementInst>::op_begin(this),
1137 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1138 assert(isValidOperands(Val, Index) &&
1139 "Invalid extractelement instruction operands!");
1140 Op<0>().init(Val, this);
1141 Op<1>().init(Index, this);
1146 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1147 const std::string &Name,
1148 BasicBlock *InsertAE)
1149 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1151 OperandTraits<ExtractElementInst>::op_begin(this),
1153 assert(isValidOperands(Val, Index) &&
1154 "Invalid extractelement instruction operands!");
1156 Op<0>().init(Val, this);
1157 Op<1>().init(Index, this);
1161 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1162 const std::string &Name,
1163 BasicBlock *InsertAE)
1164 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1166 OperandTraits<ExtractElementInst>::op_begin(this),
1168 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1169 assert(isValidOperands(Val, Index) &&
1170 "Invalid extractelement instruction operands!");
1172 Op<0>().init(Val, this);
1173 Op<1>().init(Index, this);
1178 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1179 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1185 //===----------------------------------------------------------------------===//
1186 // InsertElementInst Implementation
1187 //===----------------------------------------------------------------------===//
1189 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1190 : Instruction(IE.getType(), InsertElement,
1191 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1192 Op<0>().init(IE.Op<0>(), this);
1193 Op<1>().init(IE.Op<1>(), this);
1194 Op<2>().init(IE.Op<2>(), this);
1196 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1197 const std::string &Name,
1198 Instruction *InsertBef)
1199 : Instruction(Vec->getType(), InsertElement,
1200 OperandTraits<InsertElementInst>::op_begin(this),
1202 assert(isValidOperands(Vec, Elt, Index) &&
1203 "Invalid insertelement instruction operands!");
1204 Op<0>().init(Vec, this);
1205 Op<1>().init(Elt, this);
1206 Op<2>().init(Index, this);
1210 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1211 const std::string &Name,
1212 Instruction *InsertBef)
1213 : Instruction(Vec->getType(), InsertElement,
1214 OperandTraits<InsertElementInst>::op_begin(this),
1216 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1217 assert(isValidOperands(Vec, Elt, Index) &&
1218 "Invalid insertelement instruction operands!");
1219 Op<0>().init(Vec, this);
1220 Op<1>().init(Elt, this);
1221 Op<2>().init(Index, this);
1226 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1227 const std::string &Name,
1228 BasicBlock *InsertAE)
1229 : Instruction(Vec->getType(), InsertElement,
1230 OperandTraits<InsertElementInst>::op_begin(this),
1232 assert(isValidOperands(Vec, Elt, Index) &&
1233 "Invalid insertelement instruction operands!");
1235 Op<0>().init(Vec, this);
1236 Op<1>().init(Elt, this);
1237 Op<2>().init(Index, this);
1241 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1242 const std::string &Name,
1243 BasicBlock *InsertAE)
1244 : Instruction(Vec->getType(), InsertElement,
1245 OperandTraits<InsertElementInst>::op_begin(this),
1247 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1248 assert(isValidOperands(Vec, Elt, Index) &&
1249 "Invalid insertelement instruction operands!");
1251 Op<0>().init(Vec, this);
1252 Op<1>().init(Elt, this);
1253 Op<2>().init(Index, this);
1257 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1258 const Value *Index) {
1259 if (!isa<VectorType>(Vec->getType()))
1260 return false; // First operand of insertelement must be vector type.
1262 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1263 return false;// Second operand of insertelement must be vector element type.
1265 if (Index->getType() != Type::Int32Ty)
1266 return false; // Third operand of insertelement must be uint.
1271 //===----------------------------------------------------------------------===//
1272 // ShuffleVectorInst Implementation
1273 //===----------------------------------------------------------------------===//
1275 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1276 : Instruction(SV.getType(), ShuffleVector,
1277 OperandTraits<ShuffleVectorInst>::op_begin(this),
1278 OperandTraits<ShuffleVectorInst>::operands(this)) {
1279 Op<0>().init(SV.Op<0>(), this);
1280 Op<1>().init(SV.Op<1>(), this);
1281 Op<2>().init(SV.Op<2>(), this);
1284 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1285 const std::string &Name,
1286 Instruction *InsertBefore)
1287 : Instruction(V1->getType(), ShuffleVector,
1288 OperandTraits<ShuffleVectorInst>::op_begin(this),
1289 OperandTraits<ShuffleVectorInst>::operands(this),
1291 assert(isValidOperands(V1, V2, Mask) &&
1292 "Invalid shuffle vector instruction operands!");
1293 Op<0>().init(V1, this);
1294 Op<1>().init(V2, this);
1295 Op<2>().init(Mask, this);
1299 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1300 const std::string &Name,
1301 BasicBlock *InsertAtEnd)
1302 : Instruction(V1->getType(), ShuffleVector,
1303 OperandTraits<ShuffleVectorInst>::op_begin(this),
1304 OperandTraits<ShuffleVectorInst>::operands(this),
1306 assert(isValidOperands(V1, V2, Mask) &&
1307 "Invalid shuffle vector instruction operands!");
1309 Op<0>().init(V1, this);
1310 Op<1>().init(V2, this);
1311 Op<2>().init(Mask, this);
1315 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1316 const Value *Mask) {
1317 if (!isa<VectorType>(V1->getType()) ||
1318 V1->getType() != V2->getType())
1321 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1322 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1323 MaskTy->getElementType() != Type::Int32Ty ||
1324 MaskTy->getNumElements() !=
1325 cast<VectorType>(V1->getType())->getNumElements())
1330 /// getMaskValue - Return the index from the shuffle mask for the specified
1331 /// output result. This is either -1 if the element is undef or a number less
1332 /// than 2*numelements.
1333 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1334 const Constant *Mask = cast<Constant>(getOperand(2));
1335 if (isa<UndefValue>(Mask)) return -1;
1336 if (isa<ConstantAggregateZero>(Mask)) return 0;
1337 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1338 assert(i < MaskCV->getNumOperands() && "Index out of range");
1340 if (isa<UndefValue>(MaskCV->getOperand(i)))
1342 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1346 //===----------------------------------------------------------------------===//
1347 // BinaryOperator Class
1348 //===----------------------------------------------------------------------===//
1350 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1351 const Type *Ty, const std::string &Name,
1352 Instruction *InsertBefore)
1353 : Instruction(Ty, iType,
1354 OperandTraits<BinaryOperator>::op_begin(this),
1355 OperandTraits<BinaryOperator>::operands(this),
1357 Op<0>().init(S1, this);
1358 Op<1>().init(S2, this);
1363 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1364 const Type *Ty, const std::string &Name,
1365 BasicBlock *InsertAtEnd)
1366 : Instruction(Ty, iType,
1367 OperandTraits<BinaryOperator>::op_begin(this),
1368 OperandTraits<BinaryOperator>::operands(this),
1370 Op<0>().init(S1, this);
1371 Op<1>().init(S2, this);
1377 void BinaryOperator::init(BinaryOps iType) {
1378 Value *LHS = getOperand(0), *RHS = getOperand(1);
1379 LHS = LHS; RHS = RHS; // Silence warnings.
1380 assert(LHS->getType() == RHS->getType() &&
1381 "Binary operator operand types must match!");
1386 assert(getType() == LHS->getType() &&
1387 "Arithmetic operation should return same type as operands!");
1388 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1389 isa<VectorType>(getType())) &&
1390 "Tried to create an arithmetic operation on a non-arithmetic type!");
1394 assert(getType() == LHS->getType() &&
1395 "Arithmetic operation should return same type as operands!");
1396 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1397 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1398 "Incorrect operand type (not integer) for S/UDIV");
1401 assert(getType() == LHS->getType() &&
1402 "Arithmetic operation should return same type as operands!");
1403 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1404 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1405 && "Incorrect operand type (not floating point) for FDIV");
1409 assert(getType() == LHS->getType() &&
1410 "Arithmetic operation should return same type as operands!");
1411 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1412 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1413 "Incorrect operand type (not integer) for S/UREM");
1416 assert(getType() == LHS->getType() &&
1417 "Arithmetic operation should return same type as operands!");
1418 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1419 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1420 && "Incorrect operand type (not floating point) for FREM");
1425 assert(getType() == LHS->getType() &&
1426 "Shift operation should return same type as operands!");
1427 assert(getType()->isInteger() &&
1428 "Shift operation requires integer operands");
1432 assert(getType() == LHS->getType() &&
1433 "Logical operation should return same type as operands!");
1434 assert((getType()->isInteger() ||
1435 (isa<VectorType>(getType()) &&
1436 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1437 "Tried to create a logical operation on a non-integral type!");
1445 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1446 const std::string &Name,
1447 Instruction *InsertBefore) {
1448 assert(S1->getType() == S2->getType() &&
1449 "Cannot create binary operator with two operands of differing type!");
1450 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1453 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1454 const std::string &Name,
1455 BasicBlock *InsertAtEnd) {
1456 BinaryOperator *Res = create(Op, S1, S2, Name);
1457 InsertAtEnd->getInstList().push_back(Res);
1461 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1462 Instruction *InsertBefore) {
1463 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1464 return new BinaryOperator(Instruction::Sub,
1466 Op->getType(), Name, InsertBefore);
1469 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1470 BasicBlock *InsertAtEnd) {
1471 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1472 return new BinaryOperator(Instruction::Sub,
1474 Op->getType(), Name, InsertAtEnd);
1477 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1478 Instruction *InsertBefore) {
1480 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1481 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1482 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1484 C = ConstantInt::getAllOnesValue(Op->getType());
1487 return new BinaryOperator(Instruction::Xor, Op, C,
1488 Op->getType(), Name, InsertBefore);
1491 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1492 BasicBlock *InsertAtEnd) {
1494 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1495 // Create a vector of all ones values.
1496 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1498 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1500 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1503 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1504 Op->getType(), Name, InsertAtEnd);
1508 // isConstantAllOnes - Helper function for several functions below
1509 static inline bool isConstantAllOnes(const Value *V) {
1510 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1511 return CI->isAllOnesValue();
1512 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1513 return CV->isAllOnesValue();
1517 bool BinaryOperator::isNeg(const Value *V) {
1518 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1519 if (Bop->getOpcode() == Instruction::Sub)
1520 return Bop->getOperand(0) ==
1521 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1525 bool BinaryOperator::isNot(const Value *V) {
1526 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1527 return (Bop->getOpcode() == Instruction::Xor &&
1528 (isConstantAllOnes(Bop->getOperand(1)) ||
1529 isConstantAllOnes(Bop->getOperand(0))));
1533 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1534 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1535 return cast<BinaryOperator>(BinOp)->getOperand(1);
1538 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1539 return getNegArgument(const_cast<Value*>(BinOp));
1542 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1543 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1544 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1545 Value *Op0 = BO->getOperand(0);
1546 Value *Op1 = BO->getOperand(1);
1547 if (isConstantAllOnes(Op0)) return Op1;
1549 assert(isConstantAllOnes(Op1));
1553 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1554 return getNotArgument(const_cast<Value*>(BinOp));
1558 // swapOperands - Exchange the two operands to this instruction. This
1559 // instruction is safe to use on any binary instruction and does not
1560 // modify the semantics of the instruction. If the instruction is
1561 // order dependent (SetLT f.e.) the opcode is changed.
1563 bool BinaryOperator::swapOperands() {
1564 if (!isCommutative())
1565 return true; // Can't commute operands
1566 std::swap(Op<0>(), Op<1>());
1570 //===----------------------------------------------------------------------===//
1572 //===----------------------------------------------------------------------===//
1574 // Just determine if this cast only deals with integral->integral conversion.
1575 bool CastInst::isIntegerCast() const {
1576 switch (getOpcode()) {
1577 default: return false;
1578 case Instruction::ZExt:
1579 case Instruction::SExt:
1580 case Instruction::Trunc:
1582 case Instruction::BitCast:
1583 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1587 bool CastInst::isLosslessCast() const {
1588 // Only BitCast can be lossless, exit fast if we're not BitCast
1589 if (getOpcode() != Instruction::BitCast)
1592 // Identity cast is always lossless
1593 const Type* SrcTy = getOperand(0)->getType();
1594 const Type* DstTy = getType();
1598 // Pointer to pointer is always lossless.
1599 if (isa<PointerType>(SrcTy))
1600 return isa<PointerType>(DstTy);
1601 return false; // Other types have no identity values
1604 /// This function determines if the CastInst does not require any bits to be
1605 /// changed in order to effect the cast. Essentially, it identifies cases where
1606 /// no code gen is necessary for the cast, hence the name no-op cast. For
1607 /// example, the following are all no-op casts:
1608 /// # bitcast i32* %x to i8*
1609 /// # bitcast <2 x i32> %x to <4 x i16>
1610 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1611 /// @brief Determine if a cast is a no-op.
1612 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1613 switch (getOpcode()) {
1615 assert(!"Invalid CastOp");
1616 case Instruction::Trunc:
1617 case Instruction::ZExt:
1618 case Instruction::SExt:
1619 case Instruction::FPTrunc:
1620 case Instruction::FPExt:
1621 case Instruction::UIToFP:
1622 case Instruction::SIToFP:
1623 case Instruction::FPToUI:
1624 case Instruction::FPToSI:
1625 return false; // These always modify bits
1626 case Instruction::BitCast:
1627 return true; // BitCast never modifies bits.
1628 case Instruction::PtrToInt:
1629 return IntPtrTy->getPrimitiveSizeInBits() ==
1630 getType()->getPrimitiveSizeInBits();
1631 case Instruction::IntToPtr:
1632 return IntPtrTy->getPrimitiveSizeInBits() ==
1633 getOperand(0)->getType()->getPrimitiveSizeInBits();
1637 /// This function determines if a pair of casts can be eliminated and what
1638 /// opcode should be used in the elimination. This assumes that there are two
1639 /// instructions like this:
1640 /// * %F = firstOpcode SrcTy %x to MidTy
1641 /// * %S = secondOpcode MidTy %F to DstTy
1642 /// The function returns a resultOpcode so these two casts can be replaced with:
1643 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1644 /// If no such cast is permited, the function returns 0.
1645 unsigned CastInst::isEliminableCastPair(
1646 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1647 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1649 // Define the 144 possibilities for these two cast instructions. The values
1650 // in this matrix determine what to do in a given situation and select the
1651 // case in the switch below. The rows correspond to firstOp, the columns
1652 // correspond to secondOp. In looking at the table below, keep in mind
1653 // the following cast properties:
1655 // Size Compare Source Destination
1656 // Operator Src ? Size Type Sign Type Sign
1657 // -------- ------------ ------------------- ---------------------
1658 // TRUNC > Integer Any Integral Any
1659 // ZEXT < Integral Unsigned Integer Any
1660 // SEXT < Integral Signed Integer Any
1661 // FPTOUI n/a FloatPt n/a Integral Unsigned
1662 // FPTOSI n/a FloatPt n/a Integral Signed
1663 // UITOFP n/a Integral Unsigned FloatPt n/a
1664 // SITOFP n/a Integral Signed FloatPt n/a
1665 // FPTRUNC > FloatPt n/a FloatPt n/a
1666 // FPEXT < FloatPt n/a FloatPt n/a
1667 // PTRTOINT n/a Pointer n/a Integral Unsigned
1668 // INTTOPTR n/a Integral Unsigned Pointer n/a
1669 // BITCONVERT = FirstClass n/a FirstClass n/a
1671 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1672 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1673 // into "fptoui double to ulong", but this loses information about the range
1674 // of the produced value (we no longer know the top-part is all zeros).
1675 // Further this conversion is often much more expensive for typical hardware,
1676 // and causes issues when building libgcc. We disallow fptosi+sext for the
1678 const unsigned numCastOps =
1679 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1680 static const uint8_t CastResults[numCastOps][numCastOps] = {
1681 // T F F U S F F P I B -+
1682 // R Z S P P I I T P 2 N T |
1683 // U E E 2 2 2 2 R E I T C +- secondOp
1684 // N X X U S F F N X N 2 V |
1685 // C T T I I P P C T T P T -+
1686 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1687 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1688 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1689 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1690 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1691 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1692 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1693 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1694 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1695 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1696 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1697 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1700 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1701 [secondOp-Instruction::CastOpsBegin];
1704 // categorically disallowed
1707 // allowed, use first cast's opcode
1710 // allowed, use second cast's opcode
1713 // no-op cast in second op implies firstOp as long as the DestTy
1715 if (DstTy->isInteger())
1719 // no-op cast in second op implies firstOp as long as the DestTy
1720 // is floating point
1721 if (DstTy->isFloatingPoint())
1725 // no-op cast in first op implies secondOp as long as the SrcTy
1727 if (SrcTy->isInteger())
1731 // no-op cast in first op implies secondOp as long as the SrcTy
1732 // is a floating point
1733 if (SrcTy->isFloatingPoint())
1737 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1738 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1739 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1740 if (MidSize >= PtrSize)
1741 return Instruction::BitCast;
1745 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1746 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1747 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1748 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1749 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1750 if (SrcSize == DstSize)
1751 return Instruction::BitCast;
1752 else if (SrcSize < DstSize)
1756 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1757 return Instruction::ZExt;
1759 // fpext followed by ftrunc is allowed if the bit size returned to is
1760 // the same as the original, in which case its just a bitcast
1762 return Instruction::BitCast;
1763 return 0; // If the types are not the same we can't eliminate it.
1765 // bitcast followed by ptrtoint is allowed as long as the bitcast
1766 // is a pointer to pointer cast.
1767 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1771 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1772 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1776 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1777 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1778 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1779 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1780 if (SrcSize <= PtrSize && SrcSize == DstSize)
1781 return Instruction::BitCast;
1785 // cast combination can't happen (error in input). This is for all cases
1786 // where the MidTy is not the same for the two cast instructions.
1787 assert(!"Invalid Cast Combination");
1790 assert(!"Error in CastResults table!!!");
1796 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1797 const std::string &Name, Instruction *InsertBefore) {
1798 // Construct and return the appropriate CastInst subclass
1800 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1801 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1802 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1803 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1804 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1805 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1806 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1807 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1808 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1809 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1810 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1811 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1813 assert(!"Invalid opcode provided");
1818 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1819 const std::string &Name, BasicBlock *InsertAtEnd) {
1820 // Construct and return the appropriate CastInst subclass
1822 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1823 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1824 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1825 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1826 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1827 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1828 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1829 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1830 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1831 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1832 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1833 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1835 assert(!"Invalid opcode provided");
1840 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1841 const std::string &Name,
1842 Instruction *InsertBefore) {
1843 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1844 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1845 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1848 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1849 const std::string &Name,
1850 BasicBlock *InsertAtEnd) {
1851 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1852 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1853 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1856 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1857 const std::string &Name,
1858 Instruction *InsertBefore) {
1859 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1860 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1861 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1864 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1865 const std::string &Name,
1866 BasicBlock *InsertAtEnd) {
1867 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1868 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1869 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1872 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1873 const std::string &Name,
1874 Instruction *InsertBefore) {
1875 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1876 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1877 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1880 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1881 const std::string &Name,
1882 BasicBlock *InsertAtEnd) {
1883 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1884 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1885 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1888 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1889 const std::string &Name,
1890 BasicBlock *InsertAtEnd) {
1891 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1892 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1895 if (Ty->isInteger())
1896 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1897 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1900 /// @brief Create a BitCast or a PtrToInt cast instruction
1901 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1902 const std::string &Name,
1903 Instruction *InsertBefore) {
1904 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1905 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1908 if (Ty->isInteger())
1909 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1910 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1913 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1914 bool isSigned, const std::string &Name,
1915 Instruction *InsertBefore) {
1916 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1917 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1918 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1919 Instruction::CastOps opcode =
1920 (SrcBits == DstBits ? Instruction::BitCast :
1921 (SrcBits > DstBits ? Instruction::Trunc :
1922 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1923 return create(opcode, C, Ty, Name, InsertBefore);
1926 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1927 bool isSigned, const std::string &Name,
1928 BasicBlock *InsertAtEnd) {
1929 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1930 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1931 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1932 Instruction::CastOps opcode =
1933 (SrcBits == DstBits ? Instruction::BitCast :
1934 (SrcBits > DstBits ? Instruction::Trunc :
1935 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1936 return create(opcode, C, Ty, Name, InsertAtEnd);
1939 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1940 const std::string &Name,
1941 Instruction *InsertBefore) {
1942 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1944 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1945 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1946 Instruction::CastOps opcode =
1947 (SrcBits == DstBits ? Instruction::BitCast :
1948 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1949 return create(opcode, C, Ty, Name, InsertBefore);
1952 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1953 const std::string &Name,
1954 BasicBlock *InsertAtEnd) {
1955 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1957 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1958 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1959 Instruction::CastOps opcode =
1960 (SrcBits == DstBits ? Instruction::BitCast :
1961 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1962 return create(opcode, C, Ty, Name, InsertAtEnd);
1965 // Check whether it is valid to call getCastOpcode for these types.
1966 // This routine must be kept in sync with getCastOpcode.
1967 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1968 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1971 if (SrcTy == DestTy)
1974 // Get the bit sizes, we'll need these
1975 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1976 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1978 // Run through the possibilities ...
1979 if (DestTy->isInteger()) { // Casting to integral
1980 if (SrcTy->isInteger()) { // Casting from integral
1982 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1984 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1985 // Casting from vector
1986 return DestBits == PTy->getBitWidth();
1987 } else { // Casting from something else
1988 return isa<PointerType>(SrcTy);
1990 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1991 if (SrcTy->isInteger()) { // Casting from integral
1993 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1995 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1996 // Casting from vector
1997 return DestBits == PTy->getBitWidth();
1998 } else { // Casting from something else
2001 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2002 // Casting to vector
2003 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2004 // Casting from vector
2005 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2006 } else { // Casting from something else
2007 return DestPTy->getBitWidth() == SrcBits;
2009 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2010 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2012 } else if (SrcTy->isInteger()) { // Casting from integral
2014 } else { // Casting from something else
2017 } else { // Casting to something else
2022 // Provide a way to get a "cast" where the cast opcode is inferred from the
2023 // types and size of the operand. This, basically, is a parallel of the
2024 // logic in the castIsValid function below. This axiom should hold:
2025 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2026 // should not assert in castIsValid. In other words, this produces a "correct"
2027 // casting opcode for the arguments passed to it.
2028 // This routine must be kept in sync with isCastable.
2029 Instruction::CastOps
2030 CastInst::getCastOpcode(
2031 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2032 // Get the bit sizes, we'll need these
2033 const Type *SrcTy = Src->getType();
2034 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2035 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2037 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2038 "Only first class types are castable!");
2040 // Run through the possibilities ...
2041 if (DestTy->isInteger()) { // Casting to integral
2042 if (SrcTy->isInteger()) { // Casting from integral
2043 if (DestBits < SrcBits)
2044 return Trunc; // int -> smaller int
2045 else if (DestBits > SrcBits) { // its an extension
2047 return SExt; // signed -> SEXT
2049 return ZExt; // unsigned -> ZEXT
2051 return BitCast; // Same size, No-op cast
2053 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2055 return FPToSI; // FP -> sint
2057 return FPToUI; // FP -> uint
2058 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2059 assert(DestBits == PTy->getBitWidth() &&
2060 "Casting vector to integer of different width");
2061 return BitCast; // Same size, no-op cast
2063 assert(isa<PointerType>(SrcTy) &&
2064 "Casting from a value that is not first-class type");
2065 return PtrToInt; // ptr -> int
2067 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2068 if (SrcTy->isInteger()) { // Casting from integral
2070 return SIToFP; // sint -> FP
2072 return UIToFP; // uint -> FP
2073 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2074 if (DestBits < SrcBits) {
2075 return FPTrunc; // FP -> smaller FP
2076 } else if (DestBits > SrcBits) {
2077 return FPExt; // FP -> larger FP
2079 return BitCast; // same size, no-op cast
2081 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2082 assert(DestBits == PTy->getBitWidth() &&
2083 "Casting vector to floating point of different width");
2084 return BitCast; // same size, no-op cast
2086 assert(0 && "Casting pointer or non-first class to float");
2088 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2089 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2090 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2091 "Casting vector to vector of different widths");
2092 return BitCast; // vector -> vector
2093 } else if (DestPTy->getBitWidth() == SrcBits) {
2094 return BitCast; // float/int -> vector
2096 assert(!"Illegal cast to vector (wrong type or size)");
2098 } else if (isa<PointerType>(DestTy)) {
2099 if (isa<PointerType>(SrcTy)) {
2100 return BitCast; // ptr -> ptr
2101 } else if (SrcTy->isInteger()) {
2102 return IntToPtr; // int -> ptr
2104 assert(!"Casting pointer to other than pointer or int");
2107 assert(!"Casting to type that is not first-class");
2110 // If we fall through to here we probably hit an assertion cast above
2111 // and assertions are not turned on. Anything we return is an error, so
2112 // BitCast is as good a choice as any.
2116 //===----------------------------------------------------------------------===//
2117 // CastInst SubClass Constructors
2118 //===----------------------------------------------------------------------===//
2120 /// Check that the construction parameters for a CastInst are correct. This
2121 /// could be broken out into the separate constructors but it is useful to have
2122 /// it in one place and to eliminate the redundant code for getting the sizes
2123 /// of the types involved.
2125 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2127 // Check for type sanity on the arguments
2128 const Type *SrcTy = S->getType();
2129 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2132 // Get the size of the types in bits, we'll need this later
2133 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2134 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2136 // Switch on the opcode provided
2138 default: return false; // This is an input error
2139 case Instruction::Trunc:
2140 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2141 case Instruction::ZExt:
2142 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2143 case Instruction::SExt:
2144 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2145 case Instruction::FPTrunc:
2146 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2147 SrcBitSize > DstBitSize;
2148 case Instruction::FPExt:
2149 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2150 SrcBitSize < DstBitSize;
2151 case Instruction::UIToFP:
2152 case Instruction::SIToFP:
2153 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2154 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2155 return SVTy->getElementType()->isInteger() &&
2156 DVTy->getElementType()->isFloatingPoint() &&
2157 SVTy->getNumElements() == DVTy->getNumElements();
2160 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2161 case Instruction::FPToUI:
2162 case Instruction::FPToSI:
2163 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2164 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2165 return SVTy->getElementType()->isFloatingPoint() &&
2166 DVTy->getElementType()->isInteger() &&
2167 SVTy->getNumElements() == DVTy->getNumElements();
2170 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2171 case Instruction::PtrToInt:
2172 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2173 case Instruction::IntToPtr:
2174 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2175 case Instruction::BitCast:
2176 // BitCast implies a no-op cast of type only. No bits change.
2177 // However, you can't cast pointers to anything but pointers.
2178 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2181 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2182 // these cases, the cast is okay if the source and destination bit widths
2184 return SrcBitSize == DstBitSize;
2188 TruncInst::TruncInst(
2189 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2190 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2191 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2194 TruncInst::TruncInst(
2195 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2196 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2197 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2201 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2202 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2203 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2207 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2208 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2209 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2212 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2213 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2214 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2218 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2219 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2220 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2223 FPTruncInst::FPTruncInst(
2224 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2225 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2226 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2229 FPTruncInst::FPTruncInst(
2230 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2231 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2232 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2235 FPExtInst::FPExtInst(
2236 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2237 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2238 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2241 FPExtInst::FPExtInst(
2242 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2243 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2244 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2247 UIToFPInst::UIToFPInst(
2248 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2249 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2250 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2253 UIToFPInst::UIToFPInst(
2254 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2255 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2256 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2259 SIToFPInst::SIToFPInst(
2260 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2261 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2262 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2265 SIToFPInst::SIToFPInst(
2266 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2267 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2268 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2271 FPToUIInst::FPToUIInst(
2272 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2273 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2274 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2277 FPToUIInst::FPToUIInst(
2278 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2279 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2280 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2283 FPToSIInst::FPToSIInst(
2284 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2285 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2286 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2289 FPToSIInst::FPToSIInst(
2290 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2291 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2292 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2295 PtrToIntInst::PtrToIntInst(
2296 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2297 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2298 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2301 PtrToIntInst::PtrToIntInst(
2302 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2303 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2304 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2307 IntToPtrInst::IntToPtrInst(
2308 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2309 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2310 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2313 IntToPtrInst::IntToPtrInst(
2314 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2315 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2316 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2319 BitCastInst::BitCastInst(
2320 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2321 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2322 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2325 BitCastInst::BitCastInst(
2326 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2327 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2328 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2331 //===----------------------------------------------------------------------===//
2333 //===----------------------------------------------------------------------===//
2335 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2336 Value *LHS, Value *RHS, const std::string &Name,
2337 Instruction *InsertBefore)
2338 : Instruction(ty, op,
2339 OperandTraits<CmpInst>::op_begin(this),
2340 OperandTraits<CmpInst>::operands(this),
2342 Op<0>().init(LHS, this);
2343 Op<1>().init(RHS, this);
2344 SubclassData = predicate;
2348 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2349 Value *LHS, Value *RHS, const std::string &Name,
2350 BasicBlock *InsertAtEnd)
2351 : Instruction(ty, op,
2352 OperandTraits<CmpInst>::op_begin(this),
2353 OperandTraits<CmpInst>::operands(this),
2355 Op<0>().init(LHS, this);
2356 Op<1>().init(RHS, this);
2357 SubclassData = predicate;
2362 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2363 const std::string &Name, Instruction *InsertBefore) {
2364 if (Op == Instruction::ICmp) {
2365 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2368 if (Op == Instruction::FCmp) {
2369 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2372 if (Op == Instruction::VICmp) {
2373 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2376 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2381 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2382 const std::string &Name, BasicBlock *InsertAtEnd) {
2383 if (Op == Instruction::ICmp) {
2384 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2387 if (Op == Instruction::FCmp) {
2388 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2391 if (Op == Instruction::VICmp) {
2392 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2395 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2399 void CmpInst::swapOperands() {
2400 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2403 cast<FCmpInst>(this)->swapOperands();
2406 bool CmpInst::isCommutative() {
2407 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2408 return IC->isCommutative();
2409 return cast<FCmpInst>(this)->isCommutative();
2412 bool CmpInst::isEquality() {
2413 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2414 return IC->isEquality();
2415 return cast<FCmpInst>(this)->isEquality();
2419 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2422 assert(!"Unknown icmp predicate!");
2423 case ICMP_EQ: return ICMP_NE;
2424 case ICMP_NE: return ICMP_EQ;
2425 case ICMP_UGT: return ICMP_ULE;
2426 case ICMP_ULT: return ICMP_UGE;
2427 case ICMP_UGE: return ICMP_ULT;
2428 case ICMP_ULE: return ICMP_UGT;
2429 case ICMP_SGT: return ICMP_SLE;
2430 case ICMP_SLT: return ICMP_SGE;
2431 case ICMP_SGE: return ICMP_SLT;
2432 case ICMP_SLE: return ICMP_SGT;
2436 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2438 default: assert(! "Unknown icmp predicate!");
2439 case ICMP_EQ: case ICMP_NE:
2441 case ICMP_SGT: return ICMP_SLT;
2442 case ICMP_SLT: return ICMP_SGT;
2443 case ICMP_SGE: return ICMP_SLE;
2444 case ICMP_SLE: return ICMP_SGE;
2445 case ICMP_UGT: return ICMP_ULT;
2446 case ICMP_ULT: return ICMP_UGT;
2447 case ICMP_UGE: return ICMP_ULE;
2448 case ICMP_ULE: return ICMP_UGE;
2452 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2454 default: assert(! "Unknown icmp predicate!");
2455 case ICMP_EQ: case ICMP_NE:
2456 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2458 case ICMP_UGT: return ICMP_SGT;
2459 case ICMP_ULT: return ICMP_SLT;
2460 case ICMP_UGE: return ICMP_SGE;
2461 case ICMP_ULE: return ICMP_SLE;
2465 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2467 default: assert(! "Unknown icmp predicate!");
2468 case ICMP_EQ: case ICMP_NE:
2469 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2471 case ICMP_SGT: return ICMP_UGT;
2472 case ICMP_SLT: return ICMP_ULT;
2473 case ICMP_SGE: return ICMP_UGE;
2474 case ICMP_SLE: return ICMP_ULE;
2478 bool ICmpInst::isSignedPredicate(Predicate pred) {
2480 default: assert(! "Unknown icmp predicate!");
2481 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2483 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2484 case ICMP_UGE: case ICMP_ULE:
2489 /// Initialize a set of values that all satisfy the condition with C.
2492 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2495 uint32_t BitWidth = C.getBitWidth();
2497 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2498 case ICmpInst::ICMP_EQ: Upper++; break;
2499 case ICmpInst::ICMP_NE: Lower++; break;
2500 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2501 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2502 case ICmpInst::ICMP_UGT:
2503 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2505 case ICmpInst::ICMP_SGT:
2506 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2508 case ICmpInst::ICMP_ULE:
2509 Lower = APInt::getMinValue(BitWidth); Upper++;
2511 case ICmpInst::ICMP_SLE:
2512 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2514 case ICmpInst::ICMP_UGE:
2515 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2517 case ICmpInst::ICMP_SGE:
2518 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2521 return ConstantRange(Lower, Upper);
2524 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2527 assert(!"Unknown icmp predicate!");
2528 case FCMP_OEQ: return FCMP_UNE;
2529 case FCMP_ONE: return FCMP_UEQ;
2530 case FCMP_OGT: return FCMP_ULE;
2531 case FCMP_OLT: return FCMP_UGE;
2532 case FCMP_OGE: return FCMP_ULT;
2533 case FCMP_OLE: return FCMP_UGT;
2534 case FCMP_UEQ: return FCMP_ONE;
2535 case FCMP_UNE: return FCMP_OEQ;
2536 case FCMP_UGT: return FCMP_OLE;
2537 case FCMP_ULT: return FCMP_OGE;
2538 case FCMP_UGE: return FCMP_OLT;
2539 case FCMP_ULE: return FCMP_OGT;
2540 case FCMP_ORD: return FCMP_UNO;
2541 case FCMP_UNO: return FCMP_ORD;
2542 case FCMP_TRUE: return FCMP_FALSE;
2543 case FCMP_FALSE: return FCMP_TRUE;
2547 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2549 default: assert(!"Unknown fcmp predicate!");
2550 case FCMP_FALSE: case FCMP_TRUE:
2551 case FCMP_OEQ: case FCMP_ONE:
2552 case FCMP_UEQ: case FCMP_UNE:
2553 case FCMP_ORD: case FCMP_UNO:
2555 case FCMP_OGT: return FCMP_OLT;
2556 case FCMP_OLT: return FCMP_OGT;
2557 case FCMP_OGE: return FCMP_OLE;
2558 case FCMP_OLE: return FCMP_OGE;
2559 case FCMP_UGT: return FCMP_ULT;
2560 case FCMP_ULT: return FCMP_UGT;
2561 case FCMP_UGE: return FCMP_ULE;
2562 case FCMP_ULE: return FCMP_UGE;
2566 bool CmpInst::isUnsigned(unsigned short predicate) {
2567 switch (predicate) {
2568 default: return false;
2569 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2570 case ICmpInst::ICMP_UGE: return true;
2574 bool CmpInst::isSigned(unsigned short predicate){
2575 switch (predicate) {
2576 default: return false;
2577 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2578 case ICmpInst::ICMP_SGE: return true;
2582 bool CmpInst::isOrdered(unsigned short predicate) {
2583 switch (predicate) {
2584 default: return false;
2585 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2586 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2587 case FCmpInst::FCMP_ORD: return true;
2591 bool CmpInst::isUnordered(unsigned short predicate) {
2592 switch (predicate) {
2593 default: return false;
2594 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2595 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2596 case FCmpInst::FCMP_UNO: return true;
2600 //===----------------------------------------------------------------------===//
2601 // SwitchInst Implementation
2602 //===----------------------------------------------------------------------===//
2604 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2605 assert(Value && Default);
2606 ReservedSpace = 2+NumCases*2;
2608 OperandList = allocHungoffUses(ReservedSpace);
2610 OperandList[0].init(Value, this);
2611 OperandList[1].init(Default, this);
2614 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2615 /// switch on and a default destination. The number of additional cases can
2616 /// be specified here to make memory allocation more efficient. This
2617 /// constructor can also autoinsert before another instruction.
2618 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2619 Instruction *InsertBefore)
2620 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2621 init(Value, Default, NumCases);
2624 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2625 /// switch on and a default destination. The number of additional cases can
2626 /// be specified here to make memory allocation more efficient. This
2627 /// constructor also autoinserts at the end of the specified BasicBlock.
2628 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2629 BasicBlock *InsertAtEnd)
2630 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2631 init(Value, Default, NumCases);
2634 SwitchInst::SwitchInst(const SwitchInst &SI)
2635 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2636 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2637 Use *OL = OperandList, *InOL = SI.OperandList;
2638 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2639 OL[i].init(InOL[i], this);
2640 OL[i+1].init(InOL[i+1], this);
2644 SwitchInst::~SwitchInst() {
2645 dropHungoffUses(OperandList);
2649 /// addCase - Add an entry to the switch instruction...
2651 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2652 unsigned OpNo = NumOperands;
2653 if (OpNo+2 > ReservedSpace)
2654 resizeOperands(0); // Get more space!
2655 // Initialize some new operands.
2656 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2657 NumOperands = OpNo+2;
2658 OperandList[OpNo].init(OnVal, this);
2659 OperandList[OpNo+1].init(Dest, this);
2662 /// removeCase - This method removes the specified successor from the switch
2663 /// instruction. Note that this cannot be used to remove the default
2664 /// destination (successor #0).
2666 void SwitchInst::removeCase(unsigned idx) {
2667 assert(idx != 0 && "Cannot remove the default case!");
2668 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2670 unsigned NumOps = getNumOperands();
2671 Use *OL = OperandList;
2673 // Move everything after this operand down.
2675 // FIXME: we could just swap with the end of the list, then erase. However,
2676 // client might not expect this to happen. The code as it is thrashes the
2677 // use/def lists, which is kinda lame.
2678 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2680 OL[i-2+1] = OL[i+1];
2683 // Nuke the last value.
2684 OL[NumOps-2].set(0);
2685 OL[NumOps-2+1].set(0);
2686 NumOperands = NumOps-2;
2689 /// resizeOperands - resize operands - This adjusts the length of the operands
2690 /// list according to the following behavior:
2691 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2692 /// of operation. This grows the number of ops by 3 times.
2693 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2694 /// 3. If NumOps == NumOperands, trim the reserved space.
2696 void SwitchInst::resizeOperands(unsigned NumOps) {
2697 unsigned e = getNumOperands();
2700 } else if (NumOps*2 > NumOperands) {
2701 // No resize needed.
2702 if (ReservedSpace >= NumOps) return;
2703 } else if (NumOps == NumOperands) {
2704 if (ReservedSpace == NumOps) return;
2709 ReservedSpace = NumOps;
2710 Use *NewOps = allocHungoffUses(NumOps);
2711 Use *OldOps = OperandList;
2712 for (unsigned i = 0; i != e; ++i) {
2713 NewOps[i].init(OldOps[i], this);
2715 OperandList = NewOps;
2716 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2720 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2721 return getSuccessor(idx);
2723 unsigned SwitchInst::getNumSuccessorsV() const {
2724 return getNumSuccessors();
2726 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2727 setSuccessor(idx, B);
2730 //===----------------------------------------------------------------------===//
2731 // GetResultInst Implementation
2732 //===----------------------------------------------------------------------===//
2734 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2735 const std::string &Name,
2736 Instruction *InsertBef)
2737 : UnaryInstruction(cast<StructType>(Aggregate->getType())
2738 ->getElementType(Index),
2739 GetResult, Aggregate, InsertBef),
2741 assert(isValidOperands(Aggregate, Index)
2742 && "Invalid GetResultInst operands!");
2746 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2750 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2751 unsigned NumElements = STy->getNumElements();
2752 if (Index >= NumElements || NumElements == 0)
2755 // getresult aggregate value's element types are restricted to
2756 // avoid nested aggregates.
2757 for (unsigned i = 0; i < NumElements; ++i)
2758 if (!STy->getElementType(i)->isFirstClassType())
2761 // Otherwise, Aggregate is valid.
2767 // Define these methods here so vtables don't get emitted into every translation
2768 // unit that uses these classes.
2770 GetElementPtrInst *GetElementPtrInst::clone() const {
2771 return new(getNumOperands()) GetElementPtrInst(*this);
2774 BinaryOperator *BinaryOperator::clone() const {
2775 return create(getOpcode(), Op<0>(), Op<1>());
2778 FCmpInst* FCmpInst::clone() const {
2779 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2781 ICmpInst* ICmpInst::clone() const {
2782 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2785 VFCmpInst* VFCmpInst::clone() const {
2786 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2788 VICmpInst* VICmpInst::clone() const {
2789 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2792 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2793 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2794 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2795 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2796 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2797 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2798 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2799 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2800 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2801 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2802 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2803 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2804 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2805 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2806 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2807 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2808 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2809 CallInst *CallInst::clone() const { return new(getNumOperands()) CallInst(*this); }
2810 SelectInst *SelectInst::clone() const { return new(getNumOperands()) SelectInst(*this); }
2811 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2813 ExtractElementInst *ExtractElementInst::clone() const {
2814 return new ExtractElementInst(*this);
2816 InsertElementInst *InsertElementInst::clone() const {
2817 return InsertElementInst::Create(*this);
2819 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2820 return new ShuffleVectorInst(*this);
2822 PHINode *PHINode::clone() const { return new PHINode(*this); }
2823 ReturnInst *ReturnInst::clone() const { return new(getNumOperands()) ReturnInst(*this); }
2824 BranchInst *BranchInst::clone() const { return new(getNumOperands()) BranchInst(*this); }
2825 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2826 InvokeInst *InvokeInst::clone() const { return new(getNumOperands()) InvokeInst(*this); }
2827 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2828 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2829 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }