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/ParameterAttributes.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 unsigned CallSite::getCallingConv() const {
31 if (CallInst *CI = dyn_cast<CallInst>(I))
32 return CI->getCallingConv();
34 return cast<InvokeInst>(I)->getCallingConv();
36 void CallSite::setCallingConv(unsigned CC) {
37 if (CallInst *CI = dyn_cast<CallInst>(I))
38 CI->setCallingConv(CC);
40 cast<InvokeInst>(I)->setCallingConv(CC);
42 const ParamAttrsList* CallSite::getParamAttrs() const {
43 if (CallInst *CI = dyn_cast<CallInst>(I))
44 return CI->getParamAttrs();
46 return cast<InvokeInst>(I)->getParamAttrs();
48 void CallSite::setParamAttrs(const ParamAttrsList *PAL) {
49 if (CallInst *CI = dyn_cast<CallInst>(I))
50 CI->setParamAttrs(PAL);
52 cast<InvokeInst>(I)->setParamAttrs(PAL);
54 bool CallSite::paramHasAttr(uint16_t i, unsigned attr) const {
55 if (CallInst *CI = dyn_cast<CallInst>(I))
56 return CI->paramHasAttr(i, (ParameterAttributes)attr);
58 return cast<InvokeInst>(I)->paramHasAttr(i, (ParameterAttributes)attr);
60 bool CallSite::doesNotAccessMemory() const {
61 if (CallInst *CI = dyn_cast<CallInst>(I))
62 return CI->doesNotAccessMemory();
64 return cast<InvokeInst>(I)->doesNotAccessMemory();
66 bool CallSite::onlyReadsMemory() const {
67 if (CallInst *CI = dyn_cast<CallInst>(I))
68 return CI->onlyReadsMemory();
70 return cast<InvokeInst>(I)->onlyReadsMemory();
72 bool CallSite::doesNotThrow() const {
73 if (CallInst *CI = dyn_cast<CallInst>(I))
74 return CI->doesNotThrow();
76 return cast<InvokeInst>(I)->doesNotThrow();
78 void CallSite::setDoesNotThrow(bool doesNotThrow) {
79 if (CallInst *CI = dyn_cast<CallInst>(I))
80 CI->setDoesNotThrow(doesNotThrow);
82 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
85 //===----------------------------------------------------------------------===//
86 // TerminatorInst Class
87 //===----------------------------------------------------------------------===//
89 // Out of line virtual method, so the vtable, etc has a home.
90 TerminatorInst::~TerminatorInst() {
93 // Out of line virtual method, so the vtable, etc has a home.
94 UnaryInstruction::~UnaryInstruction() {
98 //===----------------------------------------------------------------------===//
100 //===----------------------------------------------------------------------===//
102 PHINode::PHINode(const PHINode &PN)
103 : Instruction(PN.getType(), Instruction::PHI,
104 new Use[PN.getNumOperands()], PN.getNumOperands()),
105 ReservedSpace(PN.getNumOperands()) {
106 Use *OL = OperandList;
107 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
108 OL[i].init(PN.getOperand(i), this);
109 OL[i+1].init(PN.getOperand(i+1), this);
113 PHINode::~PHINode() {
114 delete [] OperandList;
117 // removeIncomingValue - Remove an incoming value. This is useful if a
118 // predecessor basic block is deleted.
119 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
120 unsigned NumOps = getNumOperands();
121 Use *OL = OperandList;
122 assert(Idx*2 < NumOps && "BB not in PHI node!");
123 Value *Removed = OL[Idx*2];
125 // Move everything after this operand down.
127 // FIXME: we could just swap with the end of the list, then erase. However,
128 // client might not expect this to happen. The code as it is thrashes the
129 // use/def lists, which is kinda lame.
130 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
135 // Nuke the last value.
137 OL[NumOps-2+1].set(0);
138 NumOperands = NumOps-2;
140 // If the PHI node is dead, because it has zero entries, nuke it now.
141 if (NumOps == 2 && DeletePHIIfEmpty) {
142 // If anyone is using this PHI, make them use a dummy value instead...
143 replaceAllUsesWith(UndefValue::get(getType()));
149 /// resizeOperands - resize operands - This adjusts the length of the operands
150 /// list according to the following behavior:
151 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
152 /// of operation. This grows the number of ops by 1.5 times.
153 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
154 /// 3. If NumOps == NumOperands, trim the reserved space.
156 void PHINode::resizeOperands(unsigned NumOps) {
158 NumOps = (getNumOperands())*3/2;
159 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
160 } else if (NumOps*2 > NumOperands) {
162 if (ReservedSpace >= NumOps) return;
163 } else if (NumOps == NumOperands) {
164 if (ReservedSpace == NumOps) return;
169 ReservedSpace = NumOps;
170 Use *NewOps = new Use[NumOps];
171 Use *OldOps = OperandList;
172 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
173 NewOps[i].init(OldOps[i], this);
177 OperandList = NewOps;
180 /// hasConstantValue - If the specified PHI node always merges together the same
181 /// value, return the value, otherwise return null.
183 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
184 // If the PHI node only has one incoming value, eliminate the PHI node...
185 if (getNumIncomingValues() == 1)
186 if (getIncomingValue(0) != this) // not X = phi X
187 return getIncomingValue(0);
189 return UndefValue::get(getType()); // Self cycle is dead.
191 // Otherwise if all of the incoming values are the same for the PHI, replace
192 // the PHI node with the incoming value.
195 bool HasUndefInput = false;
196 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
197 if (isa<UndefValue>(getIncomingValue(i)))
198 HasUndefInput = true;
199 else if (getIncomingValue(i) != this) // Not the PHI node itself...
200 if (InVal && getIncomingValue(i) != InVal)
201 return 0; // Not the same, bail out.
203 InVal = getIncomingValue(i);
205 // The only case that could cause InVal to be null is if we have a PHI node
206 // that only has entries for itself. In this case, there is no entry into the
207 // loop, so kill the PHI.
209 if (InVal == 0) InVal = UndefValue::get(getType());
211 // If we have a PHI node like phi(X, undef, X), where X is defined by some
212 // instruction, we cannot always return X as the result of the PHI node. Only
213 // do this if X is not an instruction (thus it must dominate the PHI block),
214 // or if the client is prepared to deal with this possibility.
215 if (HasUndefInput && !AllowNonDominatingInstruction)
216 if (Instruction *IV = dyn_cast<Instruction>(InVal))
217 // If it's in the entry block, it dominates everything.
218 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
220 return 0; // Cannot guarantee that InVal dominates this PHINode.
222 // All of the incoming values are the same, return the value now.
227 //===----------------------------------------------------------------------===//
228 // CallInst Implementation
229 //===----------------------------------------------------------------------===//
231 CallInst::~CallInst() {
232 delete [] OperandList;
234 ParamAttrs->dropRef();
237 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
239 NumOperands = NumParams+1;
240 Use *OL = OperandList = new Use[NumParams+1];
241 OL[0].init(Func, this);
243 const FunctionType *FTy =
244 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
245 FTy = FTy; // silence warning.
247 assert((NumParams == FTy->getNumParams() ||
248 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
249 "Calling a function with bad signature!");
250 for (unsigned i = 0; i != NumParams; ++i) {
251 assert((i >= FTy->getNumParams() ||
252 FTy->getParamType(i) == Params[i]->getType()) &&
253 "Calling a function with a bad signature!");
254 OL[i+1].init(Params[i], this);
258 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
261 Use *OL = OperandList = new Use[3];
262 OL[0].init(Func, this);
263 OL[1].init(Actual1, this);
264 OL[2].init(Actual2, this);
266 const FunctionType *FTy =
267 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
268 FTy = FTy; // silence warning.
270 assert((FTy->getNumParams() == 2 ||
271 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
272 "Calling a function with bad signature");
273 assert((0 >= FTy->getNumParams() ||
274 FTy->getParamType(0) == Actual1->getType()) &&
275 "Calling a function with a bad signature!");
276 assert((1 >= FTy->getNumParams() ||
277 FTy->getParamType(1) == Actual2->getType()) &&
278 "Calling a function with a bad signature!");
281 void CallInst::init(Value *Func, Value *Actual) {
284 Use *OL = OperandList = new Use[2];
285 OL[0].init(Func, this);
286 OL[1].init(Actual, this);
288 const FunctionType *FTy =
289 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
290 FTy = FTy; // silence warning.
292 assert((FTy->getNumParams() == 1 ||
293 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
294 "Calling a function with bad signature");
295 assert((0 == FTy->getNumParams() ||
296 FTy->getParamType(0) == Actual->getType()) &&
297 "Calling a function with a bad signature!");
300 void CallInst::init(Value *Func) {
303 Use *OL = OperandList = new Use[1];
304 OL[0].init(Func, this);
306 const FunctionType *FTy =
307 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
308 FTy = FTy; // silence warning.
310 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
313 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
314 Instruction *InsertBefore)
315 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
316 ->getElementType())->getReturnType(),
317 Instruction::Call, 0, 0, InsertBefore) {
322 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
323 BasicBlock *InsertAtEnd)
324 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
325 ->getElementType())->getReturnType(),
326 Instruction::Call, 0, 0, InsertAtEnd) {
330 CallInst::CallInst(Value *Func, const std::string &Name,
331 Instruction *InsertBefore)
332 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
333 ->getElementType())->getReturnType(),
334 Instruction::Call, 0, 0, InsertBefore) {
339 CallInst::CallInst(Value *Func, const std::string &Name,
340 BasicBlock *InsertAtEnd)
341 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
342 ->getElementType())->getReturnType(),
343 Instruction::Call, 0, 0, InsertAtEnd) {
348 CallInst::CallInst(const CallInst &CI)
349 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
350 CI.getNumOperands()),
352 setParamAttrs(CI.getParamAttrs());
353 SubclassData = CI.SubclassData;
354 Use *OL = OperandList;
355 Use *InOL = CI.OperandList;
356 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
357 OL[i].init(InOL[i], this);
360 void CallInst::setParamAttrs(const ParamAttrsList *newAttrs) {
361 if (ParamAttrs == newAttrs)
365 ParamAttrs->dropRef();
370 ParamAttrs = newAttrs;
373 bool CallInst::paramHasAttr(uint16_t i, unsigned attr) const {
374 if (ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr))
376 if (const Function *F = getCalledFunction())
377 return F->paramHasAttr(i, (ParameterAttributes)attr);
381 /// @brief Determine if the call does not access memory.
382 bool CallInst::doesNotAccessMemory() const {
383 return paramHasAttr(0, ParamAttr::ReadNone);
386 /// @brief Determine if the call does not access or only reads memory.
387 bool CallInst::onlyReadsMemory() const {
388 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
391 /// @brief Determine if the call cannot return.
392 bool CallInst::doesNotReturn() const {
393 return paramHasAttr(0, ParamAttr::NoReturn);
396 /// @brief Determine if the call cannot unwind.
397 bool CallInst::doesNotThrow() const {
398 return paramHasAttr(0, ParamAttr::NoUnwind);
401 /// @brief Determine if the call returns a structure.
402 bool CallInst::isStructReturn() const {
403 // Be friendly and also check the callee.
404 return paramHasAttr(1, ParamAttr::StructRet);
407 /// @brief Determine if any call argument is an aggregate passed by value.
408 bool CallInst::hasByValArgument() const {
409 if (ParamAttrs && ParamAttrs->hasAttrSomewhere(ParamAttr::ByVal))
411 // Be consistent with other methods and check the callee too.
412 if (const Function *F = getCalledFunction())
413 if (const ParamAttrsList *PAL = F->getParamAttrs())
414 return PAL->hasAttrSomewhere(ParamAttr::ByVal);
418 void CallInst::setDoesNotThrow(bool doesNotThrow) {
419 const ParamAttrsList *PAL = getParamAttrs();
421 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
423 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
428 //===----------------------------------------------------------------------===//
429 // InvokeInst Implementation
430 //===----------------------------------------------------------------------===//
432 InvokeInst::~InvokeInst() {
433 delete [] OperandList;
435 ParamAttrs->dropRef();
438 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
439 Value* const *Args, unsigned NumArgs) {
441 NumOperands = 3+NumArgs;
442 Use *OL = OperandList = new Use[3+NumArgs];
443 OL[0].init(Fn, this);
444 OL[1].init(IfNormal, this);
445 OL[2].init(IfException, this);
446 const FunctionType *FTy =
447 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
448 FTy = FTy; // silence warning.
450 assert((NumArgs == FTy->getNumParams()) ||
451 (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
452 "Calling a function with bad signature");
454 for (unsigned i = 0, e = NumArgs; i != e; i++) {
455 assert((i >= FTy->getNumParams() ||
456 FTy->getParamType(i) == Args[i]->getType()) &&
457 "Invoking a function with a bad signature!");
459 OL[i+3].init(Args[i], this);
463 InvokeInst::InvokeInst(const InvokeInst &II)
464 : TerminatorInst(II.getType(), Instruction::Invoke,
465 new Use[II.getNumOperands()], II.getNumOperands()),
467 setParamAttrs(II.getParamAttrs());
468 SubclassData = II.SubclassData;
469 Use *OL = OperandList, *InOL = II.OperandList;
470 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
471 OL[i].init(InOL[i], this);
474 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
475 return getSuccessor(idx);
477 unsigned InvokeInst::getNumSuccessorsV() const {
478 return getNumSuccessors();
480 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
481 return setSuccessor(idx, B);
484 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
485 if (ParamAttrs == newAttrs)
489 ParamAttrs->dropRef();
494 ParamAttrs = newAttrs;
497 bool InvokeInst::paramHasAttr(uint16_t i, unsigned attr) const {
498 if (ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr))
500 if (const Function *F = getCalledFunction())
501 return F->paramHasAttr(i, (ParameterAttributes)attr);
506 /// @brief Determine if the call does not access memory.
507 bool InvokeInst::doesNotAccessMemory() const {
508 return paramHasAttr(0, ParamAttr::ReadNone);
511 /// @brief Determine if the call does not access or only reads memory.
512 bool InvokeInst::onlyReadsMemory() const {
513 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
516 /// @brief Determine if the call cannot return.
517 bool InvokeInst::doesNotReturn() const {
518 return paramHasAttr(0, ParamAttr::NoReturn);
521 /// @brief Determine if the call cannot unwind.
522 bool InvokeInst::doesNotThrow() const {
523 return paramHasAttr(0, ParamAttr::NoUnwind);
526 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
527 const ParamAttrsList *PAL = getParamAttrs();
529 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
531 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
535 /// @brief Determine if the call returns a structure.
536 bool InvokeInst::isStructReturn() const {
537 // Be friendly and also check the callee.
538 return paramHasAttr(1, ParamAttr::StructRet);
542 //===----------------------------------------------------------------------===//
543 // ReturnInst Implementation
544 //===----------------------------------------------------------------------===//
546 ReturnInst::ReturnInst(const ReturnInst &RI)
547 : TerminatorInst(Type::VoidTy, Instruction::Ret,
548 &RetVal, RI.getNumOperands()) {
549 if (RI.getNumOperands())
550 RetVal.init(RI.RetVal, this);
553 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
554 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
557 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
558 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
561 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
562 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
567 void ReturnInst::init(Value *retVal) {
568 if (retVal && retVal->getType() != Type::VoidTy) {
569 assert(!isa<BasicBlock>(retVal) &&
570 "Cannot return basic block. Probably using the incorrect ctor");
572 RetVal.init(retVal, this);
576 unsigned ReturnInst::getNumSuccessorsV() const {
577 return getNumSuccessors();
580 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
581 // emit the vtable for the class in this translation unit.
582 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
583 assert(0 && "ReturnInst has no successors!");
586 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
587 assert(0 && "ReturnInst has no successors!");
593 //===----------------------------------------------------------------------===//
594 // UnwindInst Implementation
595 //===----------------------------------------------------------------------===//
597 UnwindInst::UnwindInst(Instruction *InsertBefore)
598 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
600 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
601 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
605 unsigned UnwindInst::getNumSuccessorsV() const {
606 return getNumSuccessors();
609 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
610 assert(0 && "UnwindInst has no successors!");
613 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
614 assert(0 && "UnwindInst has no successors!");
619 //===----------------------------------------------------------------------===//
620 // UnreachableInst Implementation
621 //===----------------------------------------------------------------------===//
623 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
624 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
626 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
627 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
630 unsigned UnreachableInst::getNumSuccessorsV() const {
631 return getNumSuccessors();
634 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
635 assert(0 && "UnwindInst has no successors!");
638 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
639 assert(0 && "UnwindInst has no successors!");
644 //===----------------------------------------------------------------------===//
645 // BranchInst Implementation
646 //===----------------------------------------------------------------------===//
648 void BranchInst::AssertOK() {
650 assert(getCondition()->getType() == Type::Int1Ty &&
651 "May only branch on boolean predicates!");
654 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
655 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
656 assert(IfTrue != 0 && "Branch destination may not be null!");
657 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
659 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
660 Instruction *InsertBefore)
661 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
662 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
663 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
664 Ops[2].init(Cond, this);
670 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
671 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
672 assert(IfTrue != 0 && "Branch destination may not be null!");
673 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
676 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
677 BasicBlock *InsertAtEnd)
678 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
679 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
680 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
681 Ops[2].init(Cond, this);
688 BranchInst::BranchInst(const BranchInst &BI) :
689 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
690 OperandList[0].init(BI.getOperand(0), this);
691 if (BI.getNumOperands() != 1) {
692 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
693 OperandList[1].init(BI.getOperand(1), this);
694 OperandList[2].init(BI.getOperand(2), this);
698 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
699 return getSuccessor(idx);
701 unsigned BranchInst::getNumSuccessorsV() const {
702 return getNumSuccessors();
704 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
705 setSuccessor(idx, B);
709 //===----------------------------------------------------------------------===//
710 // AllocationInst Implementation
711 //===----------------------------------------------------------------------===//
713 static Value *getAISize(Value *Amt) {
715 Amt = ConstantInt::get(Type::Int32Ty, 1);
717 assert(!isa<BasicBlock>(Amt) &&
718 "Passed basic block into allocation size parameter! Use other ctor");
719 assert(Amt->getType() == Type::Int32Ty &&
720 "Malloc/Allocation array size is not a 32-bit integer!");
725 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
726 unsigned Align, const std::string &Name,
727 Instruction *InsertBefore)
728 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
729 InsertBefore), Alignment(Align) {
730 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
731 assert(Ty != Type::VoidTy && "Cannot allocate void!");
735 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
736 unsigned Align, const std::string &Name,
737 BasicBlock *InsertAtEnd)
738 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
739 InsertAtEnd), Alignment(Align) {
740 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
741 assert(Ty != Type::VoidTy && "Cannot allocate void!");
745 // Out of line virtual method, so the vtable, etc has a home.
746 AllocationInst::~AllocationInst() {
749 bool AllocationInst::isArrayAllocation() const {
750 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
751 return CI->getZExtValue() != 1;
755 const Type *AllocationInst::getAllocatedType() const {
756 return getType()->getElementType();
759 AllocaInst::AllocaInst(const AllocaInst &AI)
760 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
761 Instruction::Alloca, AI.getAlignment()) {
764 MallocInst::MallocInst(const MallocInst &MI)
765 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
766 Instruction::Malloc, MI.getAlignment()) {
769 //===----------------------------------------------------------------------===//
770 // FreeInst Implementation
771 //===----------------------------------------------------------------------===//
773 void FreeInst::AssertOK() {
774 assert(isa<PointerType>(getOperand(0)->getType()) &&
775 "Can not free something of nonpointer type!");
778 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
779 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
783 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
784 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
789 //===----------------------------------------------------------------------===//
790 // LoadInst Implementation
791 //===----------------------------------------------------------------------===//
793 void LoadInst::AssertOK() {
794 assert(isa<PointerType>(getOperand(0)->getType()) &&
795 "Ptr must have pointer type.");
798 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
799 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
800 Load, Ptr, InsertBef) {
807 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
808 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
809 Load, Ptr, InsertAE) {
816 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
817 Instruction *InsertBef)
818 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
819 Load, Ptr, InsertBef) {
820 setVolatile(isVolatile);
826 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
827 unsigned Align, Instruction *InsertBef)
828 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
829 Load, Ptr, InsertBef) {
830 setVolatile(isVolatile);
836 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
837 unsigned Align, BasicBlock *InsertAE)
838 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
839 Load, Ptr, InsertAE) {
840 setVolatile(isVolatile);
846 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
847 BasicBlock *InsertAE)
848 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
849 Load, Ptr, InsertAE) {
850 setVolatile(isVolatile);
858 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
859 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
860 Load, Ptr, InsertBef) {
864 if (Name && Name[0]) setName(Name);
867 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
868 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
869 Load, Ptr, InsertAE) {
873 if (Name && Name[0]) setName(Name);
876 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
877 Instruction *InsertBef)
878 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
879 Load, Ptr, InsertBef) {
880 setVolatile(isVolatile);
883 if (Name && Name[0]) setName(Name);
886 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
887 BasicBlock *InsertAE)
888 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
889 Load, Ptr, InsertAE) {
890 setVolatile(isVolatile);
893 if (Name && Name[0]) setName(Name);
896 void LoadInst::setAlignment(unsigned Align) {
897 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
898 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
901 //===----------------------------------------------------------------------===//
902 // StoreInst Implementation
903 //===----------------------------------------------------------------------===//
905 void StoreInst::AssertOK() {
906 assert(isa<PointerType>(getOperand(1)->getType()) &&
907 "Ptr must have pointer type!");
908 assert(getOperand(0)->getType() ==
909 cast<PointerType>(getOperand(1)->getType())->getElementType()
910 && "Ptr must be a pointer to Val type!");
914 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
915 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
916 Ops[0].init(val, this);
917 Ops[1].init(addr, this);
923 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
924 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
925 Ops[0].init(val, this);
926 Ops[1].init(addr, this);
932 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
933 Instruction *InsertBefore)
934 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
935 Ops[0].init(val, this);
936 Ops[1].init(addr, this);
937 setVolatile(isVolatile);
942 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
943 unsigned Align, Instruction *InsertBefore)
944 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
945 Ops[0].init(val, this);
946 Ops[1].init(addr, this);
947 setVolatile(isVolatile);
952 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
953 unsigned Align, BasicBlock *InsertAtEnd)
954 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
955 Ops[0].init(val, this);
956 Ops[1].init(addr, this);
957 setVolatile(isVolatile);
962 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
963 BasicBlock *InsertAtEnd)
964 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
965 Ops[0].init(val, this);
966 Ops[1].init(addr, this);
967 setVolatile(isVolatile);
972 void StoreInst::setAlignment(unsigned Align) {
973 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
974 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
977 //===----------------------------------------------------------------------===//
978 // GetElementPtrInst Implementation
979 //===----------------------------------------------------------------------===//
981 static unsigned retrieveAddrSpace(const Value *Val) {
982 return cast<PointerType>(Val->getType())->getAddressSpace();
985 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
986 NumOperands = 1+NumIdx;
987 Use *OL = OperandList = new Use[NumOperands];
988 OL[0].init(Ptr, this);
990 for (unsigned i = 0; i != NumIdx; ++i)
991 OL[i+1].init(Idx[i], this);
994 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
996 Use *OL = OperandList = new Use[2];
997 OL[0].init(Ptr, this);
998 OL[1].init(Idx, this);
1001 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1002 const std::string &Name, Instruction *InBe)
1003 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1004 retrieveAddrSpace(Ptr)),
1005 GetElementPtr, 0, 0, InBe) {
1010 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1011 const std::string &Name, BasicBlock *IAE)
1012 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1013 retrieveAddrSpace(Ptr)),
1014 GetElementPtr, 0, 0, IAE) {
1019 GetElementPtrInst::~GetElementPtrInst() {
1020 delete[] OperandList;
1023 // getIndexedType - Returns the type of the element that would be loaded with
1024 // a load instruction with the specified parameters.
1026 // A null type is returned if the indices are invalid for the specified
1029 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1032 bool AllowCompositeLeaf) {
1033 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
1035 // Handle the special case of the empty set index set...
1037 if (AllowCompositeLeaf ||
1038 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
1039 return cast<PointerType>(Ptr)->getElementType();
1043 unsigned CurIdx = 0;
1044 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1045 if (NumIdx == CurIdx) {
1046 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1047 return 0; // Can't load a whole structure or array!?!?
1050 Value *Index = Idxs[CurIdx++];
1051 if (isa<PointerType>(CT) && CurIdx != 1)
1052 return 0; // Can only index into pointer types at the first index!
1053 if (!CT->indexValid(Index)) return 0;
1054 Ptr = CT->getTypeAtIndex(Index);
1056 // If the new type forwards to another type, then it is in the middle
1057 // of being refined to another type (and hence, may have dropped all
1058 // references to what it was using before). So, use the new forwarded
1060 if (const Type * Ty = Ptr->getForwardedType()) {
1064 return CurIdx == NumIdx ? Ptr : 0;
1067 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1068 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1069 if (!PTy) return 0; // Type isn't a pointer type!
1071 // Check the pointer index.
1072 if (!PTy->indexValid(Idx)) return 0;
1074 return PTy->getElementType();
1078 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1079 /// zeros. If so, the result pointer and the first operand have the same
1080 /// value, just potentially different types.
1081 bool GetElementPtrInst::hasAllZeroIndices() const {
1082 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1083 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1084 if (!CI->isZero()) return false;
1092 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1093 /// constant integers. If so, the result pointer and the first operand have
1094 /// a constant offset between them.
1095 bool GetElementPtrInst::hasAllConstantIndices() const {
1096 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1097 if (!isa<ConstantInt>(getOperand(i)))
1104 //===----------------------------------------------------------------------===//
1105 // ExtractElementInst Implementation
1106 //===----------------------------------------------------------------------===//
1108 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1109 const std::string &Name,
1110 Instruction *InsertBef)
1111 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1112 ExtractElement, Ops, 2, InsertBef) {
1113 assert(isValidOperands(Val, Index) &&
1114 "Invalid extractelement instruction operands!");
1115 Ops[0].init(Val, this);
1116 Ops[1].init(Index, this);
1120 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1121 const std::string &Name,
1122 Instruction *InsertBef)
1123 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1124 ExtractElement, Ops, 2, InsertBef) {
1125 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1126 assert(isValidOperands(Val, Index) &&
1127 "Invalid extractelement instruction operands!");
1128 Ops[0].init(Val, this);
1129 Ops[1].init(Index, this);
1134 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1135 const std::string &Name,
1136 BasicBlock *InsertAE)
1137 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1138 ExtractElement, Ops, 2, InsertAE) {
1139 assert(isValidOperands(Val, Index) &&
1140 "Invalid extractelement instruction operands!");
1142 Ops[0].init(Val, this);
1143 Ops[1].init(Index, this);
1147 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1148 const std::string &Name,
1149 BasicBlock *InsertAE)
1150 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1151 ExtractElement, Ops, 2, InsertAE) {
1152 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1153 assert(isValidOperands(Val, Index) &&
1154 "Invalid extractelement instruction operands!");
1156 Ops[0].init(Val, this);
1157 Ops[1].init(Index, this);
1162 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1163 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1169 //===----------------------------------------------------------------------===//
1170 // InsertElementInst Implementation
1171 //===----------------------------------------------------------------------===//
1173 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1174 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1175 Ops[0].init(IE.Ops[0], this);
1176 Ops[1].init(IE.Ops[1], this);
1177 Ops[2].init(IE.Ops[2], this);
1179 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1180 const std::string &Name,
1181 Instruction *InsertBef)
1182 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1183 assert(isValidOperands(Vec, Elt, Index) &&
1184 "Invalid insertelement instruction operands!");
1185 Ops[0].init(Vec, this);
1186 Ops[1].init(Elt, this);
1187 Ops[2].init(Index, this);
1191 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1192 const std::string &Name,
1193 Instruction *InsertBef)
1194 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1195 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1196 assert(isValidOperands(Vec, Elt, Index) &&
1197 "Invalid insertelement instruction operands!");
1198 Ops[0].init(Vec, this);
1199 Ops[1].init(Elt, this);
1200 Ops[2].init(Index, this);
1205 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1206 const std::string &Name,
1207 BasicBlock *InsertAE)
1208 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1209 assert(isValidOperands(Vec, Elt, Index) &&
1210 "Invalid insertelement instruction operands!");
1212 Ops[0].init(Vec, this);
1213 Ops[1].init(Elt, this);
1214 Ops[2].init(Index, this);
1218 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1219 const std::string &Name,
1220 BasicBlock *InsertAE)
1221 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1222 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1223 assert(isValidOperands(Vec, Elt, Index) &&
1224 "Invalid insertelement instruction operands!");
1226 Ops[0].init(Vec, this);
1227 Ops[1].init(Elt, this);
1228 Ops[2].init(Index, this);
1232 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1233 const Value *Index) {
1234 if (!isa<VectorType>(Vec->getType()))
1235 return false; // First operand of insertelement must be vector type.
1237 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1238 return false;// Second operand of insertelement must be vector element type.
1240 if (Index->getType() != Type::Int32Ty)
1241 return false; // Third operand of insertelement must be uint.
1246 //===----------------------------------------------------------------------===//
1247 // ShuffleVectorInst Implementation
1248 //===----------------------------------------------------------------------===//
1250 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1251 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1252 Ops[0].init(SV.Ops[0], this);
1253 Ops[1].init(SV.Ops[1], this);
1254 Ops[2].init(SV.Ops[2], this);
1257 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1258 const std::string &Name,
1259 Instruction *InsertBefore)
1260 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1261 assert(isValidOperands(V1, V2, Mask) &&
1262 "Invalid shuffle vector instruction operands!");
1263 Ops[0].init(V1, this);
1264 Ops[1].init(V2, this);
1265 Ops[2].init(Mask, this);
1269 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1270 const std::string &Name,
1271 BasicBlock *InsertAtEnd)
1272 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1273 assert(isValidOperands(V1, V2, Mask) &&
1274 "Invalid shuffle vector instruction operands!");
1276 Ops[0].init(V1, this);
1277 Ops[1].init(V2, this);
1278 Ops[2].init(Mask, this);
1282 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1283 const Value *Mask) {
1284 if (!isa<VectorType>(V1->getType())) return false;
1285 if (V1->getType() != V2->getType()) return false;
1286 if (!isa<VectorType>(Mask->getType()) ||
1287 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1288 cast<VectorType>(Mask->getType())->getNumElements() !=
1289 cast<VectorType>(V1->getType())->getNumElements())
1295 //===----------------------------------------------------------------------===//
1296 // BinaryOperator Class
1297 //===----------------------------------------------------------------------===//
1299 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1300 const Type *Ty, const std::string &Name,
1301 Instruction *InsertBefore)
1302 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1303 Ops[0].init(S1, this);
1304 Ops[1].init(S2, this);
1309 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1310 const Type *Ty, const std::string &Name,
1311 BasicBlock *InsertAtEnd)
1312 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1313 Ops[0].init(S1, this);
1314 Ops[1].init(S2, this);
1320 void BinaryOperator::init(BinaryOps iType) {
1321 Value *LHS = getOperand(0), *RHS = getOperand(1);
1322 LHS = LHS; RHS = RHS; // Silence warnings.
1323 assert(LHS->getType() == RHS->getType() &&
1324 "Binary operator operand types must match!");
1329 assert(getType() == LHS->getType() &&
1330 "Arithmetic operation should return same type as operands!");
1331 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1332 isa<VectorType>(getType())) &&
1333 "Tried to create an arithmetic operation on a non-arithmetic type!");
1337 assert(getType() == LHS->getType() &&
1338 "Arithmetic operation should return same type as operands!");
1339 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1340 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1341 "Incorrect operand type (not integer) for S/UDIV");
1344 assert(getType() == LHS->getType() &&
1345 "Arithmetic operation should return same type as operands!");
1346 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1347 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1348 && "Incorrect operand type (not floating point) for FDIV");
1352 assert(getType() == LHS->getType() &&
1353 "Arithmetic operation should return same type as operands!");
1354 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1355 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1356 "Incorrect operand type (not integer) for S/UREM");
1359 assert(getType() == LHS->getType() &&
1360 "Arithmetic operation should return same type as operands!");
1361 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1362 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1363 && "Incorrect operand type (not floating point) for FREM");
1368 assert(getType() == LHS->getType() &&
1369 "Shift operation should return same type as operands!");
1370 assert(getType()->isInteger() &&
1371 "Shift operation requires integer operands");
1375 assert(getType() == LHS->getType() &&
1376 "Logical operation should return same type as operands!");
1377 assert((getType()->isInteger() ||
1378 (isa<VectorType>(getType()) &&
1379 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1380 "Tried to create a logical operation on a non-integral type!");
1388 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1389 const std::string &Name,
1390 Instruction *InsertBefore) {
1391 assert(S1->getType() == S2->getType() &&
1392 "Cannot create binary operator with two operands of differing type!");
1393 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1396 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1397 const std::string &Name,
1398 BasicBlock *InsertAtEnd) {
1399 BinaryOperator *Res = create(Op, S1, S2, Name);
1400 InsertAtEnd->getInstList().push_back(Res);
1404 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1405 Instruction *InsertBefore) {
1406 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1407 return new BinaryOperator(Instruction::Sub,
1409 Op->getType(), Name, InsertBefore);
1412 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1413 BasicBlock *InsertAtEnd) {
1414 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1415 return new BinaryOperator(Instruction::Sub,
1417 Op->getType(), Name, InsertAtEnd);
1420 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1421 Instruction *InsertBefore) {
1423 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1424 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1425 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1427 C = ConstantInt::getAllOnesValue(Op->getType());
1430 return new BinaryOperator(Instruction::Xor, Op, C,
1431 Op->getType(), Name, InsertBefore);
1434 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1435 BasicBlock *InsertAtEnd) {
1437 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1438 // Create a vector of all ones values.
1439 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1441 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1443 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1446 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1447 Op->getType(), Name, InsertAtEnd);
1451 // isConstantAllOnes - Helper function for several functions below
1452 static inline bool isConstantAllOnes(const Value *V) {
1453 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1454 return CI->isAllOnesValue();
1455 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1456 return CV->isAllOnesValue();
1460 bool BinaryOperator::isNeg(const Value *V) {
1461 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1462 if (Bop->getOpcode() == Instruction::Sub)
1463 return Bop->getOperand(0) ==
1464 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1468 bool BinaryOperator::isNot(const Value *V) {
1469 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1470 return (Bop->getOpcode() == Instruction::Xor &&
1471 (isConstantAllOnes(Bop->getOperand(1)) ||
1472 isConstantAllOnes(Bop->getOperand(0))));
1476 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1477 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1478 return cast<BinaryOperator>(BinOp)->getOperand(1);
1481 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1482 return getNegArgument(const_cast<Value*>(BinOp));
1485 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1486 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1487 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1488 Value *Op0 = BO->getOperand(0);
1489 Value *Op1 = BO->getOperand(1);
1490 if (isConstantAllOnes(Op0)) return Op1;
1492 assert(isConstantAllOnes(Op1));
1496 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1497 return getNotArgument(const_cast<Value*>(BinOp));
1501 // swapOperands - Exchange the two operands to this instruction. This
1502 // instruction is safe to use on any binary instruction and does not
1503 // modify the semantics of the instruction. If the instruction is
1504 // order dependent (SetLT f.e.) the opcode is changed.
1506 bool BinaryOperator::swapOperands() {
1507 if (!isCommutative())
1508 return true; // Can't commute operands
1509 std::swap(Ops[0], Ops[1]);
1513 //===----------------------------------------------------------------------===//
1515 //===----------------------------------------------------------------------===//
1517 // Just determine if this cast only deals with integral->integral conversion.
1518 bool CastInst::isIntegerCast() const {
1519 switch (getOpcode()) {
1520 default: return false;
1521 case Instruction::ZExt:
1522 case Instruction::SExt:
1523 case Instruction::Trunc:
1525 case Instruction::BitCast:
1526 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1530 bool CastInst::isLosslessCast() const {
1531 // Only BitCast can be lossless, exit fast if we're not BitCast
1532 if (getOpcode() != Instruction::BitCast)
1535 // Identity cast is always lossless
1536 const Type* SrcTy = getOperand(0)->getType();
1537 const Type* DstTy = getType();
1541 // Pointer to pointer is always lossless.
1542 if (isa<PointerType>(SrcTy))
1543 return isa<PointerType>(DstTy);
1544 return false; // Other types have no identity values
1547 /// This function determines if the CastInst does not require any bits to be
1548 /// changed in order to effect the cast. Essentially, it identifies cases where
1549 /// no code gen is necessary for the cast, hence the name no-op cast. For
1550 /// example, the following are all no-op casts:
1551 /// # bitcast uint %X, int
1552 /// # bitcast uint* %x, sbyte*
1553 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1554 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1555 /// @brief Determine if a cast is a no-op.
1556 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1557 switch (getOpcode()) {
1559 assert(!"Invalid CastOp");
1560 case Instruction::Trunc:
1561 case Instruction::ZExt:
1562 case Instruction::SExt:
1563 case Instruction::FPTrunc:
1564 case Instruction::FPExt:
1565 case Instruction::UIToFP:
1566 case Instruction::SIToFP:
1567 case Instruction::FPToUI:
1568 case Instruction::FPToSI:
1569 return false; // These always modify bits
1570 case Instruction::BitCast:
1571 return true; // BitCast never modifies bits.
1572 case Instruction::PtrToInt:
1573 return IntPtrTy->getPrimitiveSizeInBits() ==
1574 getType()->getPrimitiveSizeInBits();
1575 case Instruction::IntToPtr:
1576 return IntPtrTy->getPrimitiveSizeInBits() ==
1577 getOperand(0)->getType()->getPrimitiveSizeInBits();
1581 /// This function determines if a pair of casts can be eliminated and what
1582 /// opcode should be used in the elimination. This assumes that there are two
1583 /// instructions like this:
1584 /// * %F = firstOpcode SrcTy %x to MidTy
1585 /// * %S = secondOpcode MidTy %F to DstTy
1586 /// The function returns a resultOpcode so these two casts can be replaced with:
1587 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1588 /// If no such cast is permited, the function returns 0.
1589 unsigned CastInst::isEliminableCastPair(
1590 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1591 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1593 // Define the 144 possibilities for these two cast instructions. The values
1594 // in this matrix determine what to do in a given situation and select the
1595 // case in the switch below. The rows correspond to firstOp, the columns
1596 // correspond to secondOp. In looking at the table below, keep in mind
1597 // the following cast properties:
1599 // Size Compare Source Destination
1600 // Operator Src ? Size Type Sign Type Sign
1601 // -------- ------------ ------------------- ---------------------
1602 // TRUNC > Integer Any Integral Any
1603 // ZEXT < Integral Unsigned Integer Any
1604 // SEXT < Integral Signed Integer Any
1605 // FPTOUI n/a FloatPt n/a Integral Unsigned
1606 // FPTOSI n/a FloatPt n/a Integral Signed
1607 // UITOFP n/a Integral Unsigned FloatPt n/a
1608 // SITOFP n/a Integral Signed FloatPt n/a
1609 // FPTRUNC > FloatPt n/a FloatPt n/a
1610 // FPEXT < FloatPt n/a FloatPt n/a
1611 // PTRTOINT n/a Pointer n/a Integral Unsigned
1612 // INTTOPTR n/a Integral Unsigned Pointer n/a
1613 // BITCONVERT = FirstClass n/a FirstClass n/a
1615 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1616 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1617 // into "fptoui double to ulong", but this loses information about the range
1618 // of the produced value (we no longer know the top-part is all zeros).
1619 // Further this conversion is often much more expensive for typical hardware,
1620 // and causes issues when building libgcc. We disallow fptosi+sext for the
1622 const unsigned numCastOps =
1623 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1624 static const uint8_t CastResults[numCastOps][numCastOps] = {
1625 // T F F U S F F P I B -+
1626 // R Z S P P I I T P 2 N T |
1627 // U E E 2 2 2 2 R E I T C +- secondOp
1628 // N X X U S F F N X N 2 V |
1629 // C T T I I P P C T T P T -+
1630 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1631 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1632 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1633 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1634 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1635 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1636 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1637 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1638 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1639 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1640 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1641 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1644 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1645 [secondOp-Instruction::CastOpsBegin];
1648 // categorically disallowed
1651 // allowed, use first cast's opcode
1654 // allowed, use second cast's opcode
1657 // no-op cast in second op implies firstOp as long as the DestTy
1659 if (DstTy->isInteger())
1663 // no-op cast in second op implies firstOp as long as the DestTy
1664 // is floating point
1665 if (DstTy->isFloatingPoint())
1669 // no-op cast in first op implies secondOp as long as the SrcTy
1671 if (SrcTy->isInteger())
1675 // no-op cast in first op implies secondOp as long as the SrcTy
1676 // is a floating point
1677 if (SrcTy->isFloatingPoint())
1681 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1682 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1683 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1684 if (MidSize >= PtrSize)
1685 return Instruction::BitCast;
1689 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1690 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1691 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1692 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1693 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1694 if (SrcSize == DstSize)
1695 return Instruction::BitCast;
1696 else if (SrcSize < DstSize)
1700 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1701 return Instruction::ZExt;
1703 // fpext followed by ftrunc is allowed if the bit size returned to is
1704 // the same as the original, in which case its just a bitcast
1706 return Instruction::BitCast;
1707 return 0; // If the types are not the same we can't eliminate it.
1709 // bitcast followed by ptrtoint is allowed as long as the bitcast
1710 // is a pointer to pointer cast.
1711 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1715 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1716 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1720 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1721 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1722 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1723 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1724 if (SrcSize <= PtrSize && SrcSize == DstSize)
1725 return Instruction::BitCast;
1729 // cast combination can't happen (error in input). This is for all cases
1730 // where the MidTy is not the same for the two cast instructions.
1731 assert(!"Invalid Cast Combination");
1734 assert(!"Error in CastResults table!!!");
1740 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1741 const std::string &Name, Instruction *InsertBefore) {
1742 // Construct and return the appropriate CastInst subclass
1744 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1745 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1746 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1747 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1748 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1749 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1750 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1751 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1752 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1753 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1754 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1755 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1757 assert(!"Invalid opcode provided");
1762 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1763 const std::string &Name, BasicBlock *InsertAtEnd) {
1764 // Construct and return the appropriate CastInst subclass
1766 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1767 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1768 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1769 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1770 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1771 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1772 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1773 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1774 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1775 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1776 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1777 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1779 assert(!"Invalid opcode provided");
1784 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1785 const std::string &Name,
1786 Instruction *InsertBefore) {
1787 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1788 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1789 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1792 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1793 const std::string &Name,
1794 BasicBlock *InsertAtEnd) {
1795 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1796 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1797 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1800 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1801 const std::string &Name,
1802 Instruction *InsertBefore) {
1803 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1804 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1805 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1808 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1809 const std::string &Name,
1810 BasicBlock *InsertAtEnd) {
1811 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1812 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1813 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1816 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1817 const std::string &Name,
1818 Instruction *InsertBefore) {
1819 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1820 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1821 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1824 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1825 const std::string &Name,
1826 BasicBlock *InsertAtEnd) {
1827 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1828 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1829 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1832 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1833 const std::string &Name,
1834 BasicBlock *InsertAtEnd) {
1835 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1836 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1839 if (Ty->isInteger())
1840 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1841 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1844 /// @brief Create a BitCast or a PtrToInt cast instruction
1845 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1846 const std::string &Name,
1847 Instruction *InsertBefore) {
1848 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1849 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1852 if (Ty->isInteger())
1853 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1854 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1857 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1858 bool isSigned, const std::string &Name,
1859 Instruction *InsertBefore) {
1860 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1861 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1862 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1863 Instruction::CastOps opcode =
1864 (SrcBits == DstBits ? Instruction::BitCast :
1865 (SrcBits > DstBits ? Instruction::Trunc :
1866 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1867 return create(opcode, C, Ty, Name, InsertBefore);
1870 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1871 bool isSigned, const std::string &Name,
1872 BasicBlock *InsertAtEnd) {
1873 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1874 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1875 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1876 Instruction::CastOps opcode =
1877 (SrcBits == DstBits ? Instruction::BitCast :
1878 (SrcBits > DstBits ? Instruction::Trunc :
1879 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1880 return create(opcode, C, Ty, Name, InsertAtEnd);
1883 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1884 const std::string &Name,
1885 Instruction *InsertBefore) {
1886 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1888 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1889 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1890 Instruction::CastOps opcode =
1891 (SrcBits == DstBits ? Instruction::BitCast :
1892 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1893 return create(opcode, C, Ty, Name, InsertBefore);
1896 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1897 const std::string &Name,
1898 BasicBlock *InsertAtEnd) {
1899 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1901 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1902 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1903 Instruction::CastOps opcode =
1904 (SrcBits == DstBits ? Instruction::BitCast :
1905 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1906 return create(opcode, C, Ty, Name, InsertAtEnd);
1909 // Check whether it is valid to call getCastOpcode for these types.
1910 // This routine must be kept in sync with getCastOpcode.
1911 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1912 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1915 if (SrcTy == DestTy)
1918 // Get the bit sizes, we'll need these
1919 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1920 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1922 // Run through the possibilities ...
1923 if (DestTy->isInteger()) { // Casting to integral
1924 if (SrcTy->isInteger()) { // Casting from integral
1926 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1928 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1929 // Casting from vector
1930 return DestBits == PTy->getBitWidth();
1931 } else { // Casting from something else
1932 return isa<PointerType>(SrcTy);
1934 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1935 if (SrcTy->isInteger()) { // Casting from integral
1937 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1939 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1940 // Casting from vector
1941 return DestBits == PTy->getBitWidth();
1942 } else { // Casting from something else
1945 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1946 // Casting to vector
1947 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1948 // Casting from vector
1949 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
1950 } else { // Casting from something else
1951 return DestPTy->getBitWidth() == SrcBits;
1953 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
1954 if (isa<PointerType>(SrcTy)) { // Casting from pointer
1956 } else if (SrcTy->isInteger()) { // Casting from integral
1958 } else { // Casting from something else
1961 } else { // Casting to something else
1966 // Provide a way to get a "cast" where the cast opcode is inferred from the
1967 // types and size of the operand. This, basically, is a parallel of the
1968 // logic in the castIsValid function below. This axiom should hold:
1969 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1970 // should not assert in castIsValid. In other words, this produces a "correct"
1971 // casting opcode for the arguments passed to it.
1972 // This routine must be kept in sync with isCastable.
1973 Instruction::CastOps
1974 CastInst::getCastOpcode(
1975 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1976 // Get the bit sizes, we'll need these
1977 const Type *SrcTy = Src->getType();
1978 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1979 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1981 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
1982 "Only first class types are castable!");
1984 // Run through the possibilities ...
1985 if (DestTy->isInteger()) { // Casting to integral
1986 if (SrcTy->isInteger()) { // Casting from integral
1987 if (DestBits < SrcBits)
1988 return Trunc; // int -> smaller int
1989 else if (DestBits > SrcBits) { // its an extension
1991 return SExt; // signed -> SEXT
1993 return ZExt; // unsigned -> ZEXT
1995 return BitCast; // Same size, No-op cast
1997 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1999 return FPToSI; // FP -> sint
2001 return FPToUI; // FP -> uint
2002 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2003 assert(DestBits == PTy->getBitWidth() &&
2004 "Casting vector to integer of different width");
2005 return BitCast; // Same size, no-op cast
2007 assert(isa<PointerType>(SrcTy) &&
2008 "Casting from a value that is not first-class type");
2009 return PtrToInt; // ptr -> int
2011 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2012 if (SrcTy->isInteger()) { // Casting from integral
2014 return SIToFP; // sint -> FP
2016 return UIToFP; // uint -> FP
2017 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2018 if (DestBits < SrcBits) {
2019 return FPTrunc; // FP -> smaller FP
2020 } else if (DestBits > SrcBits) {
2021 return FPExt; // FP -> larger FP
2023 return BitCast; // same size, no-op cast
2025 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2026 assert(DestBits == PTy->getBitWidth() &&
2027 "Casting vector to floating point of different width");
2028 return BitCast; // same size, no-op cast
2030 assert(0 && "Casting pointer or non-first class to float");
2032 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2033 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2034 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2035 "Casting vector to vector of different widths");
2036 return BitCast; // vector -> vector
2037 } else if (DestPTy->getBitWidth() == SrcBits) {
2038 return BitCast; // float/int -> vector
2040 assert(!"Illegal cast to vector (wrong type or size)");
2042 } else if (isa<PointerType>(DestTy)) {
2043 if (isa<PointerType>(SrcTy)) {
2044 return BitCast; // ptr -> ptr
2045 } else if (SrcTy->isInteger()) {
2046 return IntToPtr; // int -> ptr
2048 assert(!"Casting pointer to other than pointer or int");
2051 assert(!"Casting to type that is not first-class");
2054 // If we fall through to here we probably hit an assertion cast above
2055 // and assertions are not turned on. Anything we return is an error, so
2056 // BitCast is as good a choice as any.
2060 //===----------------------------------------------------------------------===//
2061 // CastInst SubClass Constructors
2062 //===----------------------------------------------------------------------===//
2064 /// Check that the construction parameters for a CastInst are correct. This
2065 /// could be broken out into the separate constructors but it is useful to have
2066 /// it in one place and to eliminate the redundant code for getting the sizes
2067 /// of the types involved.
2069 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2071 // Check for type sanity on the arguments
2072 const Type *SrcTy = S->getType();
2073 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2076 // Get the size of the types in bits, we'll need this later
2077 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2078 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2080 // Switch on the opcode provided
2082 default: return false; // This is an input error
2083 case Instruction::Trunc:
2084 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2085 case Instruction::ZExt:
2086 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2087 case Instruction::SExt:
2088 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2089 case Instruction::FPTrunc:
2090 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2091 SrcBitSize > DstBitSize;
2092 case Instruction::FPExt:
2093 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2094 SrcBitSize < DstBitSize;
2095 case Instruction::UIToFP:
2096 case Instruction::SIToFP:
2097 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2098 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2099 return SVTy->getElementType()->isInteger() &&
2100 DVTy->getElementType()->isFloatingPoint() &&
2101 SVTy->getNumElements() == DVTy->getNumElements();
2104 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2105 case Instruction::FPToUI:
2106 case Instruction::FPToSI:
2107 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2108 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2109 return SVTy->getElementType()->isFloatingPoint() &&
2110 DVTy->getElementType()->isInteger() &&
2111 SVTy->getNumElements() == DVTy->getNumElements();
2114 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2115 case Instruction::PtrToInt:
2116 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2117 case Instruction::IntToPtr:
2118 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2119 case Instruction::BitCast:
2120 // BitCast implies a no-op cast of type only. No bits change.
2121 // However, you can't cast pointers to anything but pointers.
2122 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2125 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2126 // these cases, the cast is okay if the source and destination bit widths
2128 return SrcBitSize == DstBitSize;
2132 TruncInst::TruncInst(
2133 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2134 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2135 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2138 TruncInst::TruncInst(
2139 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2140 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2141 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2145 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2146 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2147 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2151 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2152 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2153 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2156 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2157 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2158 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2162 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2163 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2164 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2167 FPTruncInst::FPTruncInst(
2168 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2169 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2170 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2173 FPTruncInst::FPTruncInst(
2174 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2175 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2176 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2179 FPExtInst::FPExtInst(
2180 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2181 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2182 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2185 FPExtInst::FPExtInst(
2186 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2187 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2188 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2191 UIToFPInst::UIToFPInst(
2192 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2193 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2194 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2197 UIToFPInst::UIToFPInst(
2198 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2199 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2200 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2203 SIToFPInst::SIToFPInst(
2204 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2205 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2206 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2209 SIToFPInst::SIToFPInst(
2210 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2211 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2212 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2215 FPToUIInst::FPToUIInst(
2216 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2217 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2218 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2221 FPToUIInst::FPToUIInst(
2222 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2223 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2224 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2227 FPToSIInst::FPToSIInst(
2228 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2229 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2230 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2233 FPToSIInst::FPToSIInst(
2234 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2235 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2236 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2239 PtrToIntInst::PtrToIntInst(
2240 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2241 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2242 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2245 PtrToIntInst::PtrToIntInst(
2246 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2247 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2248 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2251 IntToPtrInst::IntToPtrInst(
2252 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2253 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2254 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2257 IntToPtrInst::IntToPtrInst(
2258 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2259 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2260 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2263 BitCastInst::BitCastInst(
2264 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2265 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2266 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2269 BitCastInst::BitCastInst(
2270 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2271 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2272 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2275 //===----------------------------------------------------------------------===//
2277 //===----------------------------------------------------------------------===//
2279 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2280 const std::string &Name, Instruction *InsertBefore)
2281 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2282 Ops[0].init(LHS, this);
2283 Ops[1].init(RHS, this);
2284 SubclassData = predicate;
2286 if (op == Instruction::ICmp) {
2287 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2288 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2289 "Invalid ICmp predicate value");
2290 const Type* Op0Ty = getOperand(0)->getType();
2291 const Type* Op1Ty = getOperand(1)->getType();
2292 assert(Op0Ty == Op1Ty &&
2293 "Both operands to ICmp instruction are not of the same type!");
2294 // Check that the operands are the right type
2295 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2296 "Invalid operand types for ICmp instruction");
2299 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2300 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2301 "Invalid FCmp predicate value");
2302 const Type* Op0Ty = getOperand(0)->getType();
2303 const Type* Op1Ty = getOperand(1)->getType();
2304 assert(Op0Ty == Op1Ty &&
2305 "Both operands to FCmp instruction are not of the same type!");
2306 // Check that the operands are the right type
2307 assert(Op0Ty->isFloatingPoint() &&
2308 "Invalid operand types for FCmp instruction");
2311 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2312 const std::string &Name, BasicBlock *InsertAtEnd)
2313 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2314 Ops[0].init(LHS, this);
2315 Ops[1].init(RHS, this);
2316 SubclassData = predicate;
2318 if (op == Instruction::ICmp) {
2319 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2320 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2321 "Invalid ICmp predicate value");
2323 const Type* Op0Ty = getOperand(0)->getType();
2324 const Type* Op1Ty = getOperand(1)->getType();
2325 assert(Op0Ty == Op1Ty &&
2326 "Both operands to ICmp instruction are not of the same type!");
2327 // Check that the operands are the right type
2328 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2329 "Invalid operand types for ICmp instruction");
2332 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2333 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2334 "Invalid FCmp predicate value");
2335 const Type* Op0Ty = getOperand(0)->getType();
2336 const Type* Op1Ty = getOperand(1)->getType();
2337 assert(Op0Ty == Op1Ty &&
2338 "Both operands to FCmp instruction are not of the same type!");
2339 // Check that the operands are the right type
2340 assert(Op0Ty->isFloatingPoint() &&
2341 "Invalid operand types for FCmp instruction");
2345 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2346 const std::string &Name, Instruction *InsertBefore) {
2347 if (Op == Instruction::ICmp) {
2348 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2351 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2356 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2357 const std::string &Name, BasicBlock *InsertAtEnd) {
2358 if (Op == Instruction::ICmp) {
2359 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2362 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2366 void CmpInst::swapOperands() {
2367 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2370 cast<FCmpInst>(this)->swapOperands();
2373 bool CmpInst::isCommutative() {
2374 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2375 return IC->isCommutative();
2376 return cast<FCmpInst>(this)->isCommutative();
2379 bool CmpInst::isEquality() {
2380 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2381 return IC->isEquality();
2382 return cast<FCmpInst>(this)->isEquality();
2386 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2389 assert(!"Unknown icmp predicate!");
2390 case ICMP_EQ: return ICMP_NE;
2391 case ICMP_NE: return ICMP_EQ;
2392 case ICMP_UGT: return ICMP_ULE;
2393 case ICMP_ULT: return ICMP_UGE;
2394 case ICMP_UGE: return ICMP_ULT;
2395 case ICMP_ULE: return ICMP_UGT;
2396 case ICMP_SGT: return ICMP_SLE;
2397 case ICMP_SLT: return ICMP_SGE;
2398 case ICMP_SGE: return ICMP_SLT;
2399 case ICMP_SLE: return ICMP_SGT;
2403 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2405 default: assert(! "Unknown icmp predicate!");
2406 case ICMP_EQ: case ICMP_NE:
2408 case ICMP_SGT: return ICMP_SLT;
2409 case ICMP_SLT: return ICMP_SGT;
2410 case ICMP_SGE: return ICMP_SLE;
2411 case ICMP_SLE: return ICMP_SGE;
2412 case ICMP_UGT: return ICMP_ULT;
2413 case ICMP_ULT: return ICMP_UGT;
2414 case ICMP_UGE: return ICMP_ULE;
2415 case ICMP_ULE: return ICMP_UGE;
2419 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2421 default: assert(! "Unknown icmp predicate!");
2422 case ICMP_EQ: case ICMP_NE:
2423 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2425 case ICMP_UGT: return ICMP_SGT;
2426 case ICMP_ULT: return ICMP_SLT;
2427 case ICMP_UGE: return ICMP_SGE;
2428 case ICMP_ULE: return ICMP_SLE;
2432 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2434 default: assert(! "Unknown icmp predicate!");
2435 case ICMP_EQ: case ICMP_NE:
2436 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2438 case ICMP_SGT: return ICMP_UGT;
2439 case ICMP_SLT: return ICMP_ULT;
2440 case ICMP_SGE: return ICMP_UGE;
2441 case ICMP_SLE: return ICMP_ULE;
2445 bool ICmpInst::isSignedPredicate(Predicate pred) {
2447 default: assert(! "Unknown icmp predicate!");
2448 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2450 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2451 case ICMP_UGE: case ICMP_ULE:
2456 /// Initialize a set of values that all satisfy the condition with C.
2459 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2462 uint32_t BitWidth = C.getBitWidth();
2464 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2465 case ICmpInst::ICMP_EQ: Upper++; break;
2466 case ICmpInst::ICMP_NE: Lower++; break;
2467 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2468 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2469 case ICmpInst::ICMP_UGT:
2470 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2472 case ICmpInst::ICMP_SGT:
2473 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2475 case ICmpInst::ICMP_ULE:
2476 Lower = APInt::getMinValue(BitWidth); Upper++;
2478 case ICmpInst::ICMP_SLE:
2479 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2481 case ICmpInst::ICMP_UGE:
2482 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2484 case ICmpInst::ICMP_SGE:
2485 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2488 return ConstantRange(Lower, Upper);
2491 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2494 assert(!"Unknown icmp predicate!");
2495 case FCMP_OEQ: return FCMP_UNE;
2496 case FCMP_ONE: return FCMP_UEQ;
2497 case FCMP_OGT: return FCMP_ULE;
2498 case FCMP_OLT: return FCMP_UGE;
2499 case FCMP_OGE: return FCMP_ULT;
2500 case FCMP_OLE: return FCMP_UGT;
2501 case FCMP_UEQ: return FCMP_ONE;
2502 case FCMP_UNE: return FCMP_OEQ;
2503 case FCMP_UGT: return FCMP_OLE;
2504 case FCMP_ULT: return FCMP_OGE;
2505 case FCMP_UGE: return FCMP_OLT;
2506 case FCMP_ULE: return FCMP_OGT;
2507 case FCMP_ORD: return FCMP_UNO;
2508 case FCMP_UNO: return FCMP_ORD;
2509 case FCMP_TRUE: return FCMP_FALSE;
2510 case FCMP_FALSE: return FCMP_TRUE;
2514 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2516 default: assert(!"Unknown fcmp predicate!");
2517 case FCMP_FALSE: case FCMP_TRUE:
2518 case FCMP_OEQ: case FCMP_ONE:
2519 case FCMP_UEQ: case FCMP_UNE:
2520 case FCMP_ORD: case FCMP_UNO:
2522 case FCMP_OGT: return FCMP_OLT;
2523 case FCMP_OLT: return FCMP_OGT;
2524 case FCMP_OGE: return FCMP_OLE;
2525 case FCMP_OLE: return FCMP_OGE;
2526 case FCMP_UGT: return FCMP_ULT;
2527 case FCMP_ULT: return FCMP_UGT;
2528 case FCMP_UGE: return FCMP_ULE;
2529 case FCMP_ULE: return FCMP_UGE;
2533 bool CmpInst::isUnsigned(unsigned short predicate) {
2534 switch (predicate) {
2535 default: return false;
2536 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2537 case ICmpInst::ICMP_UGE: return true;
2541 bool CmpInst::isSigned(unsigned short predicate){
2542 switch (predicate) {
2543 default: return false;
2544 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2545 case ICmpInst::ICMP_SGE: return true;
2549 bool CmpInst::isOrdered(unsigned short predicate) {
2550 switch (predicate) {
2551 default: return false;
2552 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2553 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2554 case FCmpInst::FCMP_ORD: return true;
2558 bool CmpInst::isUnordered(unsigned short predicate) {
2559 switch (predicate) {
2560 default: return false;
2561 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2562 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2563 case FCmpInst::FCMP_UNO: return true;
2567 //===----------------------------------------------------------------------===//
2568 // SwitchInst Implementation
2569 //===----------------------------------------------------------------------===//
2571 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2572 assert(Value && Default);
2573 ReservedSpace = 2+NumCases*2;
2575 OperandList = new Use[ReservedSpace];
2577 OperandList[0].init(Value, this);
2578 OperandList[1].init(Default, this);
2581 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2582 /// switch on and a default destination. The number of additional cases can
2583 /// be specified here to make memory allocation more efficient. This
2584 /// constructor can also autoinsert before another instruction.
2585 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2586 Instruction *InsertBefore)
2587 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2588 init(Value, Default, NumCases);
2591 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2592 /// switch on and a default destination. The number of additional cases can
2593 /// be specified here to make memory allocation more efficient. This
2594 /// constructor also autoinserts at the end of the specified BasicBlock.
2595 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2596 BasicBlock *InsertAtEnd)
2597 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2598 init(Value, Default, NumCases);
2601 SwitchInst::SwitchInst(const SwitchInst &SI)
2602 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2603 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2604 Use *OL = OperandList, *InOL = SI.OperandList;
2605 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2606 OL[i].init(InOL[i], this);
2607 OL[i+1].init(InOL[i+1], this);
2611 SwitchInst::~SwitchInst() {
2612 delete [] OperandList;
2616 /// addCase - Add an entry to the switch instruction...
2618 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2619 unsigned OpNo = NumOperands;
2620 if (OpNo+2 > ReservedSpace)
2621 resizeOperands(0); // Get more space!
2622 // Initialize some new operands.
2623 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2624 NumOperands = OpNo+2;
2625 OperandList[OpNo].init(OnVal, this);
2626 OperandList[OpNo+1].init(Dest, this);
2629 /// removeCase - This method removes the specified successor from the switch
2630 /// instruction. Note that this cannot be used to remove the default
2631 /// destination (successor #0).
2633 void SwitchInst::removeCase(unsigned idx) {
2634 assert(idx != 0 && "Cannot remove the default case!");
2635 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2637 unsigned NumOps = getNumOperands();
2638 Use *OL = OperandList;
2640 // Move everything after this operand down.
2642 // FIXME: we could just swap with the end of the list, then erase. However,
2643 // client might not expect this to happen. The code as it is thrashes the
2644 // use/def lists, which is kinda lame.
2645 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2647 OL[i-2+1] = OL[i+1];
2650 // Nuke the last value.
2651 OL[NumOps-2].set(0);
2652 OL[NumOps-2+1].set(0);
2653 NumOperands = NumOps-2;
2656 /// resizeOperands - resize operands - This adjusts the length of the operands
2657 /// list according to the following behavior:
2658 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2659 /// of operation. This grows the number of ops by 1.5 times.
2660 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2661 /// 3. If NumOps == NumOperands, trim the reserved space.
2663 void SwitchInst::resizeOperands(unsigned NumOps) {
2665 NumOps = getNumOperands()/2*6;
2666 } else if (NumOps*2 > NumOperands) {
2667 // No resize needed.
2668 if (ReservedSpace >= NumOps) return;
2669 } else if (NumOps == NumOperands) {
2670 if (ReservedSpace == NumOps) return;
2675 ReservedSpace = NumOps;
2676 Use *NewOps = new Use[NumOps];
2677 Use *OldOps = OperandList;
2678 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2679 NewOps[i].init(OldOps[i], this);
2683 OperandList = NewOps;
2687 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2688 return getSuccessor(idx);
2690 unsigned SwitchInst::getNumSuccessorsV() const {
2691 return getNumSuccessors();
2693 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2694 setSuccessor(idx, B);
2698 // Define these methods here so vtables don't get emitted into every translation
2699 // unit that uses these classes.
2701 GetElementPtrInst *GetElementPtrInst::clone() const {
2702 return new GetElementPtrInst(*this);
2705 BinaryOperator *BinaryOperator::clone() const {
2706 return create(getOpcode(), Ops[0], Ops[1]);
2709 FCmpInst* FCmpInst::clone() const {
2710 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2712 ICmpInst* ICmpInst::clone() const {
2713 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2716 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2717 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2718 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2719 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2720 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2721 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2722 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2723 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2724 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2725 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2726 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2727 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2728 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2729 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2730 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2731 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2732 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2733 CallInst *CallInst::clone() const { return new CallInst(*this); }
2734 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2735 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2737 ExtractElementInst *ExtractElementInst::clone() const {
2738 return new ExtractElementInst(*this);
2740 InsertElementInst *InsertElementInst::clone() const {
2741 return new InsertElementInst(*this);
2743 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2744 return new ShuffleVectorInst(*this);
2746 PHINode *PHINode::clone() const { return new PHINode(*this); }
2747 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2748 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2749 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2750 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2751 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2752 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}