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 uint %X, int
1609 /// # bitcast uint* %x, sbyte*
1610 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1611 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1612 /// @brief Determine if a cast is a no-op.
1613 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1614 switch (getOpcode()) {
1616 assert(!"Invalid CastOp");
1617 case Instruction::Trunc:
1618 case Instruction::ZExt:
1619 case Instruction::SExt:
1620 case Instruction::FPTrunc:
1621 case Instruction::FPExt:
1622 case Instruction::UIToFP:
1623 case Instruction::SIToFP:
1624 case Instruction::FPToUI:
1625 case Instruction::FPToSI:
1626 return false; // These always modify bits
1627 case Instruction::BitCast:
1628 return true; // BitCast never modifies bits.
1629 case Instruction::PtrToInt:
1630 return IntPtrTy->getPrimitiveSizeInBits() ==
1631 getType()->getPrimitiveSizeInBits();
1632 case Instruction::IntToPtr:
1633 return IntPtrTy->getPrimitiveSizeInBits() ==
1634 getOperand(0)->getType()->getPrimitiveSizeInBits();
1638 /// This function determines if a pair of casts can be eliminated and what
1639 /// opcode should be used in the elimination. This assumes that there are two
1640 /// instructions like this:
1641 /// * %F = firstOpcode SrcTy %x to MidTy
1642 /// * %S = secondOpcode MidTy %F to DstTy
1643 /// The function returns a resultOpcode so these two casts can be replaced with:
1644 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1645 /// If no such cast is permited, the function returns 0.
1646 unsigned CastInst::isEliminableCastPair(
1647 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1648 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1650 // Define the 144 possibilities for these two cast instructions. The values
1651 // in this matrix determine what to do in a given situation and select the
1652 // case in the switch below. The rows correspond to firstOp, the columns
1653 // correspond to secondOp. In looking at the table below, keep in mind
1654 // the following cast properties:
1656 // Size Compare Source Destination
1657 // Operator Src ? Size Type Sign Type Sign
1658 // -------- ------------ ------------------- ---------------------
1659 // TRUNC > Integer Any Integral Any
1660 // ZEXT < Integral Unsigned Integer Any
1661 // SEXT < Integral Signed Integer Any
1662 // FPTOUI n/a FloatPt n/a Integral Unsigned
1663 // FPTOSI n/a FloatPt n/a Integral Signed
1664 // UITOFP n/a Integral Unsigned FloatPt n/a
1665 // SITOFP n/a Integral Signed FloatPt n/a
1666 // FPTRUNC > FloatPt n/a FloatPt n/a
1667 // FPEXT < FloatPt n/a FloatPt n/a
1668 // PTRTOINT n/a Pointer n/a Integral Unsigned
1669 // INTTOPTR n/a Integral Unsigned Pointer n/a
1670 // BITCONVERT = FirstClass n/a FirstClass n/a
1672 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1673 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1674 // into "fptoui double to ulong", but this loses information about the range
1675 // of the produced value (we no longer know the top-part is all zeros).
1676 // Further this conversion is often much more expensive for typical hardware,
1677 // and causes issues when building libgcc. We disallow fptosi+sext for the
1679 const unsigned numCastOps =
1680 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1681 static const uint8_t CastResults[numCastOps][numCastOps] = {
1682 // T F F U S F F P I B -+
1683 // R Z S P P I I T P 2 N T |
1684 // U E E 2 2 2 2 R E I T C +- secondOp
1685 // N X X U S F F N X N 2 V |
1686 // C T T I I P P C T T P T -+
1687 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1688 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1689 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1690 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1691 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1692 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1693 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1694 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1695 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1696 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1697 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1698 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1701 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1702 [secondOp-Instruction::CastOpsBegin];
1705 // categorically disallowed
1708 // allowed, use first cast's opcode
1711 // allowed, use second cast's opcode
1714 // no-op cast in second op implies firstOp as long as the DestTy
1716 if (DstTy->isInteger())
1720 // no-op cast in second op implies firstOp as long as the DestTy
1721 // is floating point
1722 if (DstTy->isFloatingPoint())
1726 // no-op cast in first op implies secondOp as long as the SrcTy
1728 if (SrcTy->isInteger())
1732 // no-op cast in first op implies secondOp as long as the SrcTy
1733 // is a floating point
1734 if (SrcTy->isFloatingPoint())
1738 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1739 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1740 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1741 if (MidSize >= PtrSize)
1742 return Instruction::BitCast;
1746 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1747 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1748 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1749 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1750 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1751 if (SrcSize == DstSize)
1752 return Instruction::BitCast;
1753 else if (SrcSize < DstSize)
1757 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1758 return Instruction::ZExt;
1760 // fpext followed by ftrunc is allowed if the bit size returned to is
1761 // the same as the original, in which case its just a bitcast
1763 return Instruction::BitCast;
1764 return 0; // If the types are not the same we can't eliminate it.
1766 // bitcast followed by ptrtoint is allowed as long as the bitcast
1767 // is a pointer to pointer cast.
1768 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1772 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1773 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1777 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1778 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1779 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1780 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1781 if (SrcSize <= PtrSize && SrcSize == DstSize)
1782 return Instruction::BitCast;
1786 // cast combination can't happen (error in input). This is for all cases
1787 // where the MidTy is not the same for the two cast instructions.
1788 assert(!"Invalid Cast Combination");
1791 assert(!"Error in CastResults table!!!");
1797 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1798 const std::string &Name, Instruction *InsertBefore) {
1799 // Construct and return the appropriate CastInst subclass
1801 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1802 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1803 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1804 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1805 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1806 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1807 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1808 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1809 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1810 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1811 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1812 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1814 assert(!"Invalid opcode provided");
1819 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1820 const std::string &Name, BasicBlock *InsertAtEnd) {
1821 // Construct and return the appropriate CastInst subclass
1823 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1824 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1825 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1826 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1827 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1828 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1829 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1830 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1831 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1832 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1833 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1834 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1836 assert(!"Invalid opcode provided");
1841 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1842 const std::string &Name,
1843 Instruction *InsertBefore) {
1844 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1845 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1846 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1849 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1850 const std::string &Name,
1851 BasicBlock *InsertAtEnd) {
1852 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1853 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1854 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1857 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1858 const std::string &Name,
1859 Instruction *InsertBefore) {
1860 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1861 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1862 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1865 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1866 const std::string &Name,
1867 BasicBlock *InsertAtEnd) {
1868 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1869 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1870 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1873 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1874 const std::string &Name,
1875 Instruction *InsertBefore) {
1876 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1877 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1878 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1881 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1882 const std::string &Name,
1883 BasicBlock *InsertAtEnd) {
1884 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1885 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1886 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1889 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1890 const std::string &Name,
1891 BasicBlock *InsertAtEnd) {
1892 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1893 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1896 if (Ty->isInteger())
1897 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1898 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1901 /// @brief Create a BitCast or a PtrToInt cast instruction
1902 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1903 const std::string &Name,
1904 Instruction *InsertBefore) {
1905 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1906 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1909 if (Ty->isInteger())
1910 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1911 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1914 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1915 bool isSigned, const std::string &Name,
1916 Instruction *InsertBefore) {
1917 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1918 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1919 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1920 Instruction::CastOps opcode =
1921 (SrcBits == DstBits ? Instruction::BitCast :
1922 (SrcBits > DstBits ? Instruction::Trunc :
1923 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1924 return create(opcode, C, Ty, Name, InsertBefore);
1927 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1928 bool isSigned, const std::string &Name,
1929 BasicBlock *InsertAtEnd) {
1930 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1931 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1932 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1933 Instruction::CastOps opcode =
1934 (SrcBits == DstBits ? Instruction::BitCast :
1935 (SrcBits > DstBits ? Instruction::Trunc :
1936 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1937 return create(opcode, C, Ty, Name, InsertAtEnd);
1940 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1941 const std::string &Name,
1942 Instruction *InsertBefore) {
1943 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1945 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1946 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1947 Instruction::CastOps opcode =
1948 (SrcBits == DstBits ? Instruction::BitCast :
1949 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1950 return create(opcode, C, Ty, Name, InsertBefore);
1953 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1954 const std::string &Name,
1955 BasicBlock *InsertAtEnd) {
1956 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1958 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1959 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1960 Instruction::CastOps opcode =
1961 (SrcBits == DstBits ? Instruction::BitCast :
1962 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1963 return create(opcode, C, Ty, Name, InsertAtEnd);
1966 // Check whether it is valid to call getCastOpcode for these types.
1967 // This routine must be kept in sync with getCastOpcode.
1968 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1969 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1972 if (SrcTy == DestTy)
1975 // Get the bit sizes, we'll need these
1976 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1977 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1979 // Run through the possibilities ...
1980 if (DestTy->isInteger()) { // Casting to integral
1981 if (SrcTy->isInteger()) { // Casting from integral
1983 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1985 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1986 // Casting from vector
1987 return DestBits == PTy->getBitWidth();
1988 } else { // Casting from something else
1989 return isa<PointerType>(SrcTy);
1991 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1992 if (SrcTy->isInteger()) { // Casting from integral
1994 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1996 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1997 // Casting from vector
1998 return DestBits == PTy->getBitWidth();
1999 } else { // Casting from something else
2002 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2003 // Casting to vector
2004 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2005 // Casting from vector
2006 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2007 } else { // Casting from something else
2008 return DestPTy->getBitWidth() == SrcBits;
2010 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2011 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2013 } else if (SrcTy->isInteger()) { // Casting from integral
2015 } else { // Casting from something else
2018 } else { // Casting to something else
2023 // Provide a way to get a "cast" where the cast opcode is inferred from the
2024 // types and size of the operand. This, basically, is a parallel of the
2025 // logic in the castIsValid function below. This axiom should hold:
2026 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2027 // should not assert in castIsValid. In other words, this produces a "correct"
2028 // casting opcode for the arguments passed to it.
2029 // This routine must be kept in sync with isCastable.
2030 Instruction::CastOps
2031 CastInst::getCastOpcode(
2032 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2033 // Get the bit sizes, we'll need these
2034 const Type *SrcTy = Src->getType();
2035 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2036 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2038 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2039 "Only first class types are castable!");
2041 // Run through the possibilities ...
2042 if (DestTy->isInteger()) { // Casting to integral
2043 if (SrcTy->isInteger()) { // Casting from integral
2044 if (DestBits < SrcBits)
2045 return Trunc; // int -> smaller int
2046 else if (DestBits > SrcBits) { // its an extension
2048 return SExt; // signed -> SEXT
2050 return ZExt; // unsigned -> ZEXT
2052 return BitCast; // Same size, No-op cast
2054 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2056 return FPToSI; // FP -> sint
2058 return FPToUI; // FP -> uint
2059 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2060 assert(DestBits == PTy->getBitWidth() &&
2061 "Casting vector to integer of different width");
2062 return BitCast; // Same size, no-op cast
2064 assert(isa<PointerType>(SrcTy) &&
2065 "Casting from a value that is not first-class type");
2066 return PtrToInt; // ptr -> int
2068 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2069 if (SrcTy->isInteger()) { // Casting from integral
2071 return SIToFP; // sint -> FP
2073 return UIToFP; // uint -> FP
2074 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2075 if (DestBits < SrcBits) {
2076 return FPTrunc; // FP -> smaller FP
2077 } else if (DestBits > SrcBits) {
2078 return FPExt; // FP -> larger FP
2080 return BitCast; // same size, no-op cast
2082 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2083 assert(DestBits == PTy->getBitWidth() &&
2084 "Casting vector to floating point of different width");
2085 return BitCast; // same size, no-op cast
2087 assert(0 && "Casting pointer or non-first class to float");
2089 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2090 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2091 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2092 "Casting vector to vector of different widths");
2093 return BitCast; // vector -> vector
2094 } else if (DestPTy->getBitWidth() == SrcBits) {
2095 return BitCast; // float/int -> vector
2097 assert(!"Illegal cast to vector (wrong type or size)");
2099 } else if (isa<PointerType>(DestTy)) {
2100 if (isa<PointerType>(SrcTy)) {
2101 return BitCast; // ptr -> ptr
2102 } else if (SrcTy->isInteger()) {
2103 return IntToPtr; // int -> ptr
2105 assert(!"Casting pointer to other than pointer or int");
2108 assert(!"Casting to type that is not first-class");
2111 // If we fall through to here we probably hit an assertion cast above
2112 // and assertions are not turned on. Anything we return is an error, so
2113 // BitCast is as good a choice as any.
2117 //===----------------------------------------------------------------------===//
2118 // CastInst SubClass Constructors
2119 //===----------------------------------------------------------------------===//
2121 /// Check that the construction parameters for a CastInst are correct. This
2122 /// could be broken out into the separate constructors but it is useful to have
2123 /// it in one place and to eliminate the redundant code for getting the sizes
2124 /// of the types involved.
2126 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2128 // Check for type sanity on the arguments
2129 const Type *SrcTy = S->getType();
2130 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2133 // Get the size of the types in bits, we'll need this later
2134 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2135 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2137 // Switch on the opcode provided
2139 default: return false; // This is an input error
2140 case Instruction::Trunc:
2141 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2142 case Instruction::ZExt:
2143 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2144 case Instruction::SExt:
2145 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2146 case Instruction::FPTrunc:
2147 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2148 SrcBitSize > DstBitSize;
2149 case Instruction::FPExt:
2150 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2151 SrcBitSize < DstBitSize;
2152 case Instruction::UIToFP:
2153 case Instruction::SIToFP:
2154 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2155 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2156 return SVTy->getElementType()->isInteger() &&
2157 DVTy->getElementType()->isFloatingPoint() &&
2158 SVTy->getNumElements() == DVTy->getNumElements();
2161 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2162 case Instruction::FPToUI:
2163 case Instruction::FPToSI:
2164 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2165 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2166 return SVTy->getElementType()->isFloatingPoint() &&
2167 DVTy->getElementType()->isInteger() &&
2168 SVTy->getNumElements() == DVTy->getNumElements();
2171 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2172 case Instruction::PtrToInt:
2173 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2174 case Instruction::IntToPtr:
2175 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2176 case Instruction::BitCast:
2177 // BitCast implies a no-op cast of type only. No bits change.
2178 // However, you can't cast pointers to anything but pointers.
2179 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2182 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2183 // these cases, the cast is okay if the source and destination bit widths
2185 return SrcBitSize == DstBitSize;
2189 TruncInst::TruncInst(
2190 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2191 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2192 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2195 TruncInst::TruncInst(
2196 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2197 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2198 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2202 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2203 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2204 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2208 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2209 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2210 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2213 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2214 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2215 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2219 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2220 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2221 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2224 FPTruncInst::FPTruncInst(
2225 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2226 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2227 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2230 FPTruncInst::FPTruncInst(
2231 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2232 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2233 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2236 FPExtInst::FPExtInst(
2237 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2238 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2239 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2242 FPExtInst::FPExtInst(
2243 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2244 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2245 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2248 UIToFPInst::UIToFPInst(
2249 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2250 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2251 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2254 UIToFPInst::UIToFPInst(
2255 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2256 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2257 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2260 SIToFPInst::SIToFPInst(
2261 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2262 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2263 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2266 SIToFPInst::SIToFPInst(
2267 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2268 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2269 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2272 FPToUIInst::FPToUIInst(
2273 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2274 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2275 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2278 FPToUIInst::FPToUIInst(
2279 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2280 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2281 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2284 FPToSIInst::FPToSIInst(
2285 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2286 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2287 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2290 FPToSIInst::FPToSIInst(
2291 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2292 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2293 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2296 PtrToIntInst::PtrToIntInst(
2297 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2298 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2299 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2302 PtrToIntInst::PtrToIntInst(
2303 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2304 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2305 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2308 IntToPtrInst::IntToPtrInst(
2309 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2310 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2311 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2314 IntToPtrInst::IntToPtrInst(
2315 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2316 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2317 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2320 BitCastInst::BitCastInst(
2321 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2322 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2323 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2326 BitCastInst::BitCastInst(
2327 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2328 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2329 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2332 //===----------------------------------------------------------------------===//
2334 //===----------------------------------------------------------------------===//
2336 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2337 const std::string &Name, Instruction *InsertBefore)
2338 : Instruction(Type::Int1Ty, 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;
2346 if (op == Instruction::ICmp) {
2347 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2348 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2349 "Invalid ICmp predicate value");
2350 const Type* Op0Ty = getOperand(0)->getType();
2351 const Type* Op1Ty = getOperand(1)->getType();
2352 assert(Op0Ty == Op1Ty &&
2353 "Both operands to ICmp instruction are not of the same type!");
2354 // Check that the operands are the right type
2355 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2356 "Invalid operand types for ICmp instruction");
2359 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2360 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2361 "Invalid FCmp predicate value");
2362 const Type* Op0Ty = getOperand(0)->getType();
2363 const Type* Op1Ty = getOperand(1)->getType();
2364 assert(Op0Ty == Op1Ty &&
2365 "Both operands to FCmp instruction are not of the same type!");
2366 // Check that the operands are the right type
2367 assert(Op0Ty->isFloatingPoint() &&
2368 "Invalid operand types for FCmp instruction");
2371 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2372 const std::string &Name, BasicBlock *InsertAtEnd)
2373 : Instruction(Type::Int1Ty, op,
2374 OperandTraits<CmpInst>::op_begin(this),
2375 OperandTraits<CmpInst>::operands(this),
2377 Op<0>().init(LHS, this);
2378 Op<1>().init(RHS, this);
2379 SubclassData = predicate;
2381 if (op == Instruction::ICmp) {
2382 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2383 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2384 "Invalid ICmp predicate value");
2386 const Type* Op0Ty = getOperand(0)->getType();
2387 const Type* Op1Ty = getOperand(1)->getType();
2388 assert(Op0Ty == Op1Ty &&
2389 "Both operands to ICmp instruction are not of the same type!");
2390 // Check that the operands are the right type
2391 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2392 "Invalid operand types for ICmp instruction");
2395 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2396 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2397 "Invalid FCmp predicate value");
2398 const Type* Op0Ty = getOperand(0)->getType();
2399 const Type* Op1Ty = getOperand(1)->getType();
2400 assert(Op0Ty == Op1Ty &&
2401 "Both operands to FCmp instruction are not of the same type!");
2402 // Check that the operands are the right type
2403 assert(Op0Ty->isFloatingPoint() &&
2404 "Invalid operand types for FCmp instruction");
2408 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2409 const std::string &Name, Instruction *InsertBefore) {
2410 if (Op == Instruction::ICmp) {
2411 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2414 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2419 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2420 const std::string &Name, BasicBlock *InsertAtEnd) {
2421 if (Op == Instruction::ICmp) {
2422 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2425 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2429 void CmpInst::swapOperands() {
2430 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2433 cast<FCmpInst>(this)->swapOperands();
2436 bool CmpInst::isCommutative() {
2437 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2438 return IC->isCommutative();
2439 return cast<FCmpInst>(this)->isCommutative();
2442 bool CmpInst::isEquality() {
2443 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2444 return IC->isEquality();
2445 return cast<FCmpInst>(this)->isEquality();
2449 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2452 assert(!"Unknown icmp predicate!");
2453 case ICMP_EQ: return ICMP_NE;
2454 case ICMP_NE: return ICMP_EQ;
2455 case ICMP_UGT: return ICMP_ULE;
2456 case ICMP_ULT: return ICMP_UGE;
2457 case ICMP_UGE: return ICMP_ULT;
2458 case ICMP_ULE: return ICMP_UGT;
2459 case ICMP_SGT: return ICMP_SLE;
2460 case ICMP_SLT: return ICMP_SGE;
2461 case ICMP_SGE: return ICMP_SLT;
2462 case ICMP_SLE: return ICMP_SGT;
2466 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2468 default: assert(! "Unknown icmp predicate!");
2469 case ICMP_EQ: case ICMP_NE:
2471 case ICMP_SGT: return ICMP_SLT;
2472 case ICMP_SLT: return ICMP_SGT;
2473 case ICMP_SGE: return ICMP_SLE;
2474 case ICMP_SLE: return ICMP_SGE;
2475 case ICMP_UGT: return ICMP_ULT;
2476 case ICMP_ULT: return ICMP_UGT;
2477 case ICMP_UGE: return ICMP_ULE;
2478 case ICMP_ULE: return ICMP_UGE;
2482 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2484 default: assert(! "Unknown icmp predicate!");
2485 case ICMP_EQ: case ICMP_NE:
2486 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2488 case ICMP_UGT: return ICMP_SGT;
2489 case ICMP_ULT: return ICMP_SLT;
2490 case ICMP_UGE: return ICMP_SGE;
2491 case ICMP_ULE: return ICMP_SLE;
2495 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2497 default: assert(! "Unknown icmp predicate!");
2498 case ICMP_EQ: case ICMP_NE:
2499 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2501 case ICMP_SGT: return ICMP_UGT;
2502 case ICMP_SLT: return ICMP_ULT;
2503 case ICMP_SGE: return ICMP_UGE;
2504 case ICMP_SLE: return ICMP_ULE;
2508 bool ICmpInst::isSignedPredicate(Predicate pred) {
2510 default: assert(! "Unknown icmp predicate!");
2511 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2513 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2514 case ICMP_UGE: case ICMP_ULE:
2519 /// Initialize a set of values that all satisfy the condition with C.
2522 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2525 uint32_t BitWidth = C.getBitWidth();
2527 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2528 case ICmpInst::ICMP_EQ: Upper++; break;
2529 case ICmpInst::ICMP_NE: Lower++; break;
2530 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2531 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2532 case ICmpInst::ICMP_UGT:
2533 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2535 case ICmpInst::ICMP_SGT:
2536 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2538 case ICmpInst::ICMP_ULE:
2539 Lower = APInt::getMinValue(BitWidth); Upper++;
2541 case ICmpInst::ICMP_SLE:
2542 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2544 case ICmpInst::ICMP_UGE:
2545 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2547 case ICmpInst::ICMP_SGE:
2548 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2551 return ConstantRange(Lower, Upper);
2554 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2557 assert(!"Unknown icmp predicate!");
2558 case FCMP_OEQ: return FCMP_UNE;
2559 case FCMP_ONE: return FCMP_UEQ;
2560 case FCMP_OGT: return FCMP_ULE;
2561 case FCMP_OLT: return FCMP_UGE;
2562 case FCMP_OGE: return FCMP_ULT;
2563 case FCMP_OLE: return FCMP_UGT;
2564 case FCMP_UEQ: return FCMP_ONE;
2565 case FCMP_UNE: return FCMP_OEQ;
2566 case FCMP_UGT: return FCMP_OLE;
2567 case FCMP_ULT: return FCMP_OGE;
2568 case FCMP_UGE: return FCMP_OLT;
2569 case FCMP_ULE: return FCMP_OGT;
2570 case FCMP_ORD: return FCMP_UNO;
2571 case FCMP_UNO: return FCMP_ORD;
2572 case FCMP_TRUE: return FCMP_FALSE;
2573 case FCMP_FALSE: return FCMP_TRUE;
2577 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2579 default: assert(!"Unknown fcmp predicate!");
2580 case FCMP_FALSE: case FCMP_TRUE:
2581 case FCMP_OEQ: case FCMP_ONE:
2582 case FCMP_UEQ: case FCMP_UNE:
2583 case FCMP_ORD: case FCMP_UNO:
2585 case FCMP_OGT: return FCMP_OLT;
2586 case FCMP_OLT: return FCMP_OGT;
2587 case FCMP_OGE: return FCMP_OLE;
2588 case FCMP_OLE: return FCMP_OGE;
2589 case FCMP_UGT: return FCMP_ULT;
2590 case FCMP_ULT: return FCMP_UGT;
2591 case FCMP_UGE: return FCMP_ULE;
2592 case FCMP_ULE: return FCMP_UGE;
2596 bool CmpInst::isUnsigned(unsigned short predicate) {
2597 switch (predicate) {
2598 default: return false;
2599 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2600 case ICmpInst::ICMP_UGE: return true;
2604 bool CmpInst::isSigned(unsigned short predicate){
2605 switch (predicate) {
2606 default: return false;
2607 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2608 case ICmpInst::ICMP_SGE: return true;
2612 bool CmpInst::isOrdered(unsigned short predicate) {
2613 switch (predicate) {
2614 default: return false;
2615 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2616 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2617 case FCmpInst::FCMP_ORD: return true;
2621 bool CmpInst::isUnordered(unsigned short predicate) {
2622 switch (predicate) {
2623 default: return false;
2624 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2625 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2626 case FCmpInst::FCMP_UNO: return true;
2630 //===----------------------------------------------------------------------===//
2631 // SwitchInst Implementation
2632 //===----------------------------------------------------------------------===//
2634 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2635 assert(Value && Default);
2636 ReservedSpace = 2+NumCases*2;
2638 OperandList = allocHungoffUses(ReservedSpace);
2640 OperandList[0].init(Value, this);
2641 OperandList[1].init(Default, this);
2644 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2645 /// switch on and a default destination. The number of additional cases can
2646 /// be specified here to make memory allocation more efficient. This
2647 /// constructor can also autoinsert before another instruction.
2648 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2649 Instruction *InsertBefore)
2650 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2651 init(Value, Default, NumCases);
2654 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2655 /// switch on and a default destination. The number of additional cases can
2656 /// be specified here to make memory allocation more efficient. This
2657 /// constructor also autoinserts at the end of the specified BasicBlock.
2658 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2659 BasicBlock *InsertAtEnd)
2660 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2661 init(Value, Default, NumCases);
2664 SwitchInst::SwitchInst(const SwitchInst &SI)
2665 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2666 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2667 Use *OL = OperandList, *InOL = SI.OperandList;
2668 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2669 OL[i].init(InOL[i], this);
2670 OL[i+1].init(InOL[i+1], this);
2674 SwitchInst::~SwitchInst() {
2675 dropHungoffUses(OperandList);
2679 /// addCase - Add an entry to the switch instruction...
2681 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2682 unsigned OpNo = NumOperands;
2683 if (OpNo+2 > ReservedSpace)
2684 resizeOperands(0); // Get more space!
2685 // Initialize some new operands.
2686 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2687 NumOperands = OpNo+2;
2688 OperandList[OpNo].init(OnVal, this);
2689 OperandList[OpNo+1].init(Dest, this);
2692 /// removeCase - This method removes the specified successor from the switch
2693 /// instruction. Note that this cannot be used to remove the default
2694 /// destination (successor #0).
2696 void SwitchInst::removeCase(unsigned idx) {
2697 assert(idx != 0 && "Cannot remove the default case!");
2698 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2700 unsigned NumOps = getNumOperands();
2701 Use *OL = OperandList;
2703 // Move everything after this operand down.
2705 // FIXME: we could just swap with the end of the list, then erase. However,
2706 // client might not expect this to happen. The code as it is thrashes the
2707 // use/def lists, which is kinda lame.
2708 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2710 OL[i-2+1] = OL[i+1];
2713 // Nuke the last value.
2714 OL[NumOps-2].set(0);
2715 OL[NumOps-2+1].set(0);
2716 NumOperands = NumOps-2;
2719 /// resizeOperands - resize operands - This adjusts the length of the operands
2720 /// list according to the following behavior:
2721 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2722 /// of operation. This grows the number of ops by 3 times.
2723 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2724 /// 3. If NumOps == NumOperands, trim the reserved space.
2726 void SwitchInst::resizeOperands(unsigned NumOps) {
2727 unsigned e = getNumOperands();
2730 } else if (NumOps*2 > NumOperands) {
2731 // No resize needed.
2732 if (ReservedSpace >= NumOps) return;
2733 } else if (NumOps == NumOperands) {
2734 if (ReservedSpace == NumOps) return;
2739 ReservedSpace = NumOps;
2740 Use *NewOps = allocHungoffUses(NumOps);
2741 Use *OldOps = OperandList;
2742 for (unsigned i = 0; i != e; ++i) {
2743 NewOps[i].init(OldOps[i], this);
2745 OperandList = NewOps;
2746 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2750 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2751 return getSuccessor(idx);
2753 unsigned SwitchInst::getNumSuccessorsV() const {
2754 return getNumSuccessors();
2756 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2757 setSuccessor(idx, B);
2760 //===----------------------------------------------------------------------===//
2761 // GetResultInst Implementation
2762 //===----------------------------------------------------------------------===//
2764 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2765 const std::string &Name,
2766 Instruction *InsertBef)
2767 : Instruction(cast<StructType>(Aggregate->getType())->getElementType(Index),
2769 OperandTraits<GetResultInst>::op_begin(this),
2770 OperandTraits<GetResultInst>::operands(this),
2772 assert(isValidOperands(Aggregate, Index) && "Invalid GetResultInst operands!");
2773 Op<0>().init(Aggregate, this);
2778 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2782 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2783 unsigned NumElements = STy->getNumElements();
2784 if (Index >= NumElements || NumElements == 0)
2787 // getresult aggregate value's element types are restricted to
2788 // avoid nested aggregates.
2789 for (unsigned i = 0; i < NumElements; ++i)
2790 if (!STy->getElementType(i)->isFirstClassType())
2793 // Otherwise, Aggregate is valid.
2799 // Define these methods here so vtables don't get emitted into every translation
2800 // unit that uses these classes.
2802 GetElementPtrInst *GetElementPtrInst::clone() const {
2803 return new(getNumOperands()) GetElementPtrInst(*this);
2806 BinaryOperator *BinaryOperator::clone() const {
2807 return create(getOpcode(), Op<0>(), Op<1>());
2810 FCmpInst* FCmpInst::clone() const {
2811 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2813 ICmpInst* ICmpInst::clone() const {
2814 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2817 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2818 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2819 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2820 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2821 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2822 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2823 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2824 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2825 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2826 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2827 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2828 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2829 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2830 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2831 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2832 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2833 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2834 CallInst *CallInst::clone() const { return new(getNumOperands()) CallInst(*this); }
2835 SelectInst *SelectInst::clone() const { return new(getNumOperands()) SelectInst(*this); }
2836 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2838 ExtractElementInst *ExtractElementInst::clone() const {
2839 return new ExtractElementInst(*this);
2841 InsertElementInst *InsertElementInst::clone() const {
2842 return InsertElementInst::Create(*this);
2844 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2845 return new ShuffleVectorInst(*this);
2847 PHINode *PHINode::clone() const { return new PHINode(*this); }
2848 ReturnInst *ReturnInst::clone() const { return new(getNumOperands()) ReturnInst(*this); }
2849 BranchInst *BranchInst::clone() const { return new(getNumOperands()) BranchInst(*this); }
2850 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2851 InvokeInst *InvokeInst::clone() const { return new(getNumOperands()) InvokeInst(*this); }
2852 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2853 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2854 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }