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/ParamAttrsList.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 CallSite::CallSite(Instruction *C) {
31 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
34 unsigned CallSite::getCallingConv() const {
35 if (CallInst *CI = dyn_cast<CallInst>(I))
36 return CI->getCallingConv();
38 return cast<InvokeInst>(I)->getCallingConv();
40 void CallSite::setCallingConv(unsigned CC) {
41 if (CallInst *CI = dyn_cast<CallInst>(I))
42 CI->setCallingConv(CC);
44 cast<InvokeInst>(I)->setCallingConv(CC);
46 const ParamAttrsList* CallSite::getParamAttrs() const {
47 if (CallInst *CI = dyn_cast<CallInst>(I))
48 return CI->getParamAttrs();
50 return cast<InvokeInst>(I)->getParamAttrs();
52 void CallSite::setParamAttrs(const ParamAttrsList *PAL) {
53 if (CallInst *CI = dyn_cast<CallInst>(I))
54 CI->setParamAttrs(PAL);
56 cast<InvokeInst>(I)->setParamAttrs(PAL);
58 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
59 if (CallInst *CI = dyn_cast<CallInst>(I))
60 return CI->paramHasAttr(i, attr);
62 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
64 uint16_t CallSite::getParamAlignment(uint16_t i) const {
65 if (CallInst *CI = dyn_cast<CallInst>(I))
66 return CI->getParamAlignment(i);
68 return cast<InvokeInst>(I)->getParamAlignment(i);
71 bool CallSite::doesNotAccessMemory() const {
72 if (CallInst *CI = dyn_cast<CallInst>(I))
73 return CI->doesNotAccessMemory();
75 return cast<InvokeInst>(I)->doesNotAccessMemory();
77 bool CallSite::onlyReadsMemory() const {
78 if (CallInst *CI = dyn_cast<CallInst>(I))
79 return CI->onlyReadsMemory();
81 return cast<InvokeInst>(I)->onlyReadsMemory();
83 bool CallSite::doesNotThrow() const {
84 if (CallInst *CI = dyn_cast<CallInst>(I))
85 return CI->doesNotThrow();
87 return cast<InvokeInst>(I)->doesNotThrow();
89 void CallSite::setDoesNotThrow(bool doesNotThrow) {
90 if (CallInst *CI = dyn_cast<CallInst>(I))
91 CI->setDoesNotThrow(doesNotThrow);
93 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
96 //===----------------------------------------------------------------------===//
97 // TerminatorInst Class
98 //===----------------------------------------------------------------------===//
100 // Out of line virtual method, so the vtable, etc has a home.
101 TerminatorInst::~TerminatorInst() {
104 // Out of line virtual method, so the vtable, etc has a home.
105 UnaryInstruction::~UnaryInstruction() {
109 //===----------------------------------------------------------------------===//
111 //===----------------------------------------------------------------------===//
113 PHINode::PHINode(const PHINode &PN)
114 : Instruction(PN.getType(), Instruction::PHI,
115 new Use[PN.getNumOperands()], PN.getNumOperands()),
116 ReservedSpace(PN.getNumOperands()) {
117 Use *OL = OperandList;
118 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
119 OL[i].init(PN.getOperand(i), this);
120 OL[i+1].init(PN.getOperand(i+1), this);
124 PHINode::~PHINode() {
125 delete [] OperandList;
128 // removeIncomingValue - Remove an incoming value. This is useful if a
129 // predecessor basic block is deleted.
130 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
131 unsigned NumOps = getNumOperands();
132 Use *OL = OperandList;
133 assert(Idx*2 < NumOps && "BB not in PHI node!");
134 Value *Removed = OL[Idx*2];
136 // Move everything after this operand down.
138 // FIXME: we could just swap with the end of the list, then erase. However,
139 // client might not expect this to happen. The code as it is thrashes the
140 // use/def lists, which is kinda lame.
141 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
146 // Nuke the last value.
148 OL[NumOps-2+1].set(0);
149 NumOperands = NumOps-2;
151 // If the PHI node is dead, because it has zero entries, nuke it now.
152 if (NumOps == 2 && DeletePHIIfEmpty) {
153 // If anyone is using this PHI, make them use a dummy value instead...
154 replaceAllUsesWith(UndefValue::get(getType()));
160 /// resizeOperands - resize operands - This adjusts the length of the operands
161 /// list according to the following behavior:
162 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
163 /// of operation. This grows the number of ops by 1.5 times.
164 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
165 /// 3. If NumOps == NumOperands, trim the reserved space.
167 void PHINode::resizeOperands(unsigned NumOps) {
169 NumOps = (getNumOperands())*3/2;
170 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
171 } else if (NumOps*2 > NumOperands) {
173 if (ReservedSpace >= NumOps) return;
174 } else if (NumOps == NumOperands) {
175 if (ReservedSpace == NumOps) return;
180 ReservedSpace = NumOps;
181 Use *NewOps = new Use[NumOps];
182 Use *OldOps = OperandList;
183 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
184 NewOps[i].init(OldOps[i], this);
188 OperandList = NewOps;
191 /// hasConstantValue - If the specified PHI node always merges together the same
192 /// value, return the value, otherwise return null.
194 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
195 // If the PHI node only has one incoming value, eliminate the PHI node...
196 if (getNumIncomingValues() == 1) {
197 if (getIncomingValue(0) != this) // not X = phi X
198 return getIncomingValue(0);
200 return UndefValue::get(getType()); // Self cycle is dead.
203 // Otherwise if all of the incoming values are the same for the PHI, replace
204 // the PHI node with the incoming value.
207 bool HasUndefInput = false;
208 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
209 if (isa<UndefValue>(getIncomingValue(i))) {
210 HasUndefInput = true;
211 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
212 if (InVal && getIncomingValue(i) != InVal)
213 return 0; // Not the same, bail out.
215 InVal = getIncomingValue(i);
218 // The only case that could cause InVal to be null is if we have a PHI node
219 // that only has entries for itself. In this case, there is no entry into the
220 // loop, so kill the PHI.
222 if (InVal == 0) InVal = UndefValue::get(getType());
224 // If we have a PHI node like phi(X, undef, X), where X is defined by some
225 // instruction, we cannot always return X as the result of the PHI node. Only
226 // do this if X is not an instruction (thus it must dominate the PHI block),
227 // or if the client is prepared to deal with this possibility.
228 if (HasUndefInput && !AllowNonDominatingInstruction)
229 if (Instruction *IV = dyn_cast<Instruction>(InVal))
230 // If it's in the entry block, it dominates everything.
231 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
233 return 0; // Cannot guarantee that InVal dominates this PHINode.
235 // All of the incoming values are the same, return the value now.
240 //===----------------------------------------------------------------------===//
241 // CallInst Implementation
242 //===----------------------------------------------------------------------===//
244 CallInst::~CallInst() {
245 delete [] OperandList;
247 ParamAttrs->dropRef();
250 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
252 NumOperands = NumParams+1;
253 Use *OL = OperandList = new Use[NumParams+1];
254 OL[0].init(Func, this);
256 const FunctionType *FTy =
257 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
258 FTy = FTy; // silence warning.
260 assert((NumParams == FTy->getNumParams() ||
261 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
262 "Calling a function with bad signature!");
263 for (unsigned i = 0; i != NumParams; ++i) {
264 assert((i >= FTy->getNumParams() ||
265 FTy->getParamType(i) == Params[i]->getType()) &&
266 "Calling a function with a bad signature!");
267 OL[i+1].init(Params[i], this);
271 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
274 Use *OL = OperandList = new Use[3];
275 OL[0].init(Func, this);
276 OL[1].init(Actual1, this);
277 OL[2].init(Actual2, this);
279 const FunctionType *FTy =
280 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
281 FTy = FTy; // silence warning.
283 assert((FTy->getNumParams() == 2 ||
284 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
285 "Calling a function with bad signature");
286 assert((0 >= FTy->getNumParams() ||
287 FTy->getParamType(0) == Actual1->getType()) &&
288 "Calling a function with a bad signature!");
289 assert((1 >= FTy->getNumParams() ||
290 FTy->getParamType(1) == Actual2->getType()) &&
291 "Calling a function with a bad signature!");
294 void CallInst::init(Value *Func, Value *Actual) {
297 Use *OL = OperandList = new Use[2];
298 OL[0].init(Func, this);
299 OL[1].init(Actual, this);
301 const FunctionType *FTy =
302 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
303 FTy = FTy; // silence warning.
305 assert((FTy->getNumParams() == 1 ||
306 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
307 "Calling a function with bad signature");
308 assert((0 == FTy->getNumParams() ||
309 FTy->getParamType(0) == Actual->getType()) &&
310 "Calling a function with a bad signature!");
313 void CallInst::init(Value *Func) {
316 Use *OL = OperandList = new Use[1];
317 OL[0].init(Func, this);
319 const FunctionType *FTy =
320 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
321 FTy = FTy; // silence warning.
323 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
326 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
327 Instruction *InsertBefore)
328 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
329 ->getElementType())->getReturnType(),
330 Instruction::Call, 0, 0, InsertBefore) {
335 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
336 BasicBlock *InsertAtEnd)
337 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
338 ->getElementType())->getReturnType(),
339 Instruction::Call, 0, 0, InsertAtEnd) {
343 CallInst::CallInst(Value *Func, const std::string &Name,
344 Instruction *InsertBefore)
345 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
346 ->getElementType())->getReturnType(),
347 Instruction::Call, 0, 0, InsertBefore) {
352 CallInst::CallInst(Value *Func, const std::string &Name,
353 BasicBlock *InsertAtEnd)
354 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
355 ->getElementType())->getReturnType(),
356 Instruction::Call, 0, 0, InsertAtEnd) {
361 CallInst::CallInst(const CallInst &CI)
362 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
363 CI.getNumOperands()),
365 setParamAttrs(CI.getParamAttrs());
366 SubclassData = CI.SubclassData;
367 Use *OL = OperandList;
368 Use *InOL = CI.OperandList;
369 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
370 OL[i].init(InOL[i], this);
373 void CallInst::setParamAttrs(const ParamAttrsList *newAttrs) {
374 if (ParamAttrs == newAttrs)
378 ParamAttrs->dropRef();
383 ParamAttrs = newAttrs;
386 bool CallInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
387 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
389 if (const Function *F = getCalledFunction())
390 return F->paramHasAttr(i, attr);
394 uint16_t CallInst::getParamAlignment(uint16_t i) const {
395 if (ParamAttrs && ParamAttrs->getParamAlignment(i))
396 return ParamAttrs->getParamAlignment(i);
397 if (const Function *F = getCalledFunction())
398 return F->getParamAlignment(i);
402 /// @brief Determine if the call does not access memory.
403 bool CallInst::doesNotAccessMemory() const {
404 return paramHasAttr(0, ParamAttr::ReadNone);
407 /// @brief Determine if the call does not access or only reads memory.
408 bool CallInst::onlyReadsMemory() const {
409 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
412 /// @brief Determine if the call cannot return.
413 bool CallInst::doesNotReturn() const {
414 return paramHasAttr(0, ParamAttr::NoReturn);
417 /// @brief Determine if the call cannot unwind.
418 bool CallInst::doesNotThrow() const {
419 return paramHasAttr(0, ParamAttr::NoUnwind);
422 /// @brief Determine if the call returns a structure.
423 bool CallInst::isStructReturn() const {
424 // Be friendly and also check the callee.
425 return paramHasAttr(1, ParamAttr::StructRet);
428 /// @brief Determine if any call argument is an aggregate passed by value.
429 bool CallInst::hasByValArgument() const {
430 if (ParamAttrs && ParamAttrs->hasAttrSomewhere(ParamAttr::ByVal))
432 // Be consistent with other methods and check the callee too.
433 if (const Function *F = getCalledFunction())
434 if (const ParamAttrsList *PAL = F->getParamAttrs())
435 return PAL->hasAttrSomewhere(ParamAttr::ByVal);
439 void CallInst::setDoesNotThrow(bool doesNotThrow) {
440 const ParamAttrsList *PAL = getParamAttrs();
442 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
444 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
449 //===----------------------------------------------------------------------===//
450 // InvokeInst Implementation
451 //===----------------------------------------------------------------------===//
453 InvokeInst::~InvokeInst() {
454 delete [] OperandList;
456 ParamAttrs->dropRef();
459 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
460 Value* const *Args, unsigned NumArgs) {
462 NumOperands = 3+NumArgs;
463 Use *OL = OperandList = new Use[3+NumArgs];
464 OL[0].init(Fn, this);
465 OL[1].init(IfNormal, this);
466 OL[2].init(IfException, this);
467 const FunctionType *FTy =
468 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
469 FTy = FTy; // silence warning.
471 assert(((NumArgs == FTy->getNumParams()) ||
472 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
473 "Calling a function with bad signature");
475 for (unsigned i = 0, e = NumArgs; i != e; i++) {
476 assert((i >= FTy->getNumParams() ||
477 FTy->getParamType(i) == Args[i]->getType()) &&
478 "Invoking a function with a bad signature!");
480 OL[i+3].init(Args[i], this);
484 InvokeInst::InvokeInst(const InvokeInst &II)
485 : TerminatorInst(II.getType(), Instruction::Invoke,
486 new Use[II.getNumOperands()], II.getNumOperands()),
488 setParamAttrs(II.getParamAttrs());
489 SubclassData = II.SubclassData;
490 Use *OL = OperandList, *InOL = II.OperandList;
491 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
492 OL[i].init(InOL[i], this);
495 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
496 return getSuccessor(idx);
498 unsigned InvokeInst::getNumSuccessorsV() const {
499 return getNumSuccessors();
501 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
502 return setSuccessor(idx, B);
505 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
506 if (ParamAttrs == newAttrs)
510 ParamAttrs->dropRef();
515 ParamAttrs = newAttrs;
518 bool InvokeInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
519 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
521 if (const Function *F = getCalledFunction())
522 return F->paramHasAttr(i, attr);
526 uint16_t InvokeInst::getParamAlignment(uint16_t i) const {
527 if (ParamAttrs && ParamAttrs->getParamAlignment(i))
528 return ParamAttrs->getParamAlignment(i);
529 if (const Function *F = getCalledFunction())
530 return F->getParamAlignment(i);
534 /// @brief Determine if the call does not access memory.
535 bool InvokeInst::doesNotAccessMemory() const {
536 return paramHasAttr(0, ParamAttr::ReadNone);
539 /// @brief Determine if the call does not access or only reads memory.
540 bool InvokeInst::onlyReadsMemory() const {
541 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
544 /// @brief Determine if the call cannot return.
545 bool InvokeInst::doesNotReturn() const {
546 return paramHasAttr(0, ParamAttr::NoReturn);
549 /// @brief Determine if the call cannot unwind.
550 bool InvokeInst::doesNotThrow() const {
551 return paramHasAttr(0, ParamAttr::NoUnwind);
554 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
555 const ParamAttrsList *PAL = getParamAttrs();
557 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
559 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
563 /// @brief Determine if the call returns a structure.
564 bool InvokeInst::isStructReturn() const {
565 // Be friendly and also check the callee.
566 return paramHasAttr(1, ParamAttr::StructRet);
570 //===----------------------------------------------------------------------===//
571 // ReturnInst Implementation
572 //===----------------------------------------------------------------------===//
574 ReturnInst::ReturnInst(const ReturnInst &RI)
575 : TerminatorInst(Type::VoidTy, Instruction::Ret,
576 OperandList, RI.getNumOperands()) {
577 unsigned N = RI.getNumOperands();
578 Use *OL = OperandList = new Use[N];
579 for (unsigned i = 0; i < N; ++i)
580 OL[i].init(RI.getOperand(i), this);
583 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
584 : TerminatorInst(Type::VoidTy, Instruction::Ret, OperandList, 0, InsertBefore) {
587 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
588 : TerminatorInst(Type::VoidTy, Instruction::Ret, OperandList, 0, InsertAtEnd) {
591 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
592 : TerminatorInst(Type::VoidTy, Instruction::Ret, OperandList, 0, InsertAtEnd) {
595 ReturnInst::ReturnInst(const std::vector<Value *> &retVals, Instruction *InsertBefore)
596 : TerminatorInst(Type::VoidTy, Instruction::Ret, OperandList, retVals.size(), InsertBefore) {
599 ReturnInst::ReturnInst(const std::vector<Value *> &retVals, BasicBlock *InsertAtEnd)
600 : TerminatorInst(Type::VoidTy, Instruction::Ret, OperandList, retVals.size(), InsertAtEnd) {
603 ReturnInst::ReturnInst(const std::vector<Value *> &retVals)
604 : TerminatorInst(Type::VoidTy, Instruction::Ret, OperandList, retVals.size()) {
608 void ReturnInst::init(Value *retVal) {
609 if (retVal && retVal->getType() != Type::VoidTy) {
610 assert(!isa<BasicBlock>(retVal) &&
611 "Cannot return basic block. Probably using the incorrect ctor");
613 Use *OL = OperandList = new Use[1];
614 OL[0].init(retVal, this);
618 void ReturnInst::init(const std::vector<Value *> &retVals) {
622 NumOperands = retVals.size();
623 if (NumOperands == 1) {
624 Value *V = retVals[0];
625 if (V->getType() == Type::VoidTy)
629 Use *OL = OperandList = new Use[NumOperands];
630 for (unsigned i = 0; i < NumOperands; ++i) {
631 Value *V = retVals[i];
632 assert(!isa<BasicBlock>(V) &&
633 "Cannot return basic block. Probably using the incorrect ctor");
638 Value *ReturnInst::getReturnValue(unsigned n) const {
640 return OperandList[n];
645 unsigned ReturnInst::getNumSuccessorsV() const {
646 return getNumSuccessors();
649 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
650 // emit the vtable for the class in this translation unit.
651 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
652 assert(0 && "ReturnInst has no successors!");
655 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
656 assert(0 && "ReturnInst has no successors!");
661 ReturnInst::~ReturnInst() {
663 delete [] OperandList;
666 //===----------------------------------------------------------------------===//
667 // UnwindInst Implementation
668 //===----------------------------------------------------------------------===//
670 UnwindInst::UnwindInst(Instruction *InsertBefore)
671 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
673 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
674 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
678 unsigned UnwindInst::getNumSuccessorsV() const {
679 return getNumSuccessors();
682 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
683 assert(0 && "UnwindInst has no successors!");
686 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
687 assert(0 && "UnwindInst has no successors!");
692 //===----------------------------------------------------------------------===//
693 // UnreachableInst Implementation
694 //===----------------------------------------------------------------------===//
696 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
697 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
699 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
700 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
703 unsigned UnreachableInst::getNumSuccessorsV() const {
704 return getNumSuccessors();
707 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
708 assert(0 && "UnwindInst has no successors!");
711 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
712 assert(0 && "UnwindInst has no successors!");
717 //===----------------------------------------------------------------------===//
718 // BranchInst Implementation
719 //===----------------------------------------------------------------------===//
721 void BranchInst::AssertOK() {
723 assert(getCondition()->getType() == Type::Int1Ty &&
724 "May only branch on boolean predicates!");
727 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
728 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
729 assert(IfTrue != 0 && "Branch destination may not be null!");
730 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
732 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
733 Instruction *InsertBefore)
734 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
735 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
736 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
737 Ops[2].init(Cond, this);
743 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
744 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
745 assert(IfTrue != 0 && "Branch destination may not be null!");
746 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
749 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
750 BasicBlock *InsertAtEnd)
751 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
752 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
753 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
754 Ops[2].init(Cond, this);
761 BranchInst::BranchInst(const BranchInst &BI) :
762 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
763 OperandList[0].init(BI.getOperand(0), this);
764 if (BI.getNumOperands() != 1) {
765 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
766 OperandList[1].init(BI.getOperand(1), this);
767 OperandList[2].init(BI.getOperand(2), this);
771 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
772 return getSuccessor(idx);
774 unsigned BranchInst::getNumSuccessorsV() const {
775 return getNumSuccessors();
777 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
778 setSuccessor(idx, B);
782 //===----------------------------------------------------------------------===//
783 // AllocationInst Implementation
784 //===----------------------------------------------------------------------===//
786 static Value *getAISize(Value *Amt) {
788 Amt = ConstantInt::get(Type::Int32Ty, 1);
790 assert(!isa<BasicBlock>(Amt) &&
791 "Passed basic block into allocation size parameter! Use other ctor");
792 assert(Amt->getType() == Type::Int32Ty &&
793 "Malloc/Allocation array size is not a 32-bit integer!");
798 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
799 unsigned Align, const std::string &Name,
800 Instruction *InsertBefore)
801 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
802 InsertBefore), Alignment(Align) {
803 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
804 assert(Ty != Type::VoidTy && "Cannot allocate void!");
808 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
809 unsigned Align, const std::string &Name,
810 BasicBlock *InsertAtEnd)
811 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
812 InsertAtEnd), Alignment(Align) {
813 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
814 assert(Ty != Type::VoidTy && "Cannot allocate void!");
818 // Out of line virtual method, so the vtable, etc has a home.
819 AllocationInst::~AllocationInst() {
822 bool AllocationInst::isArrayAllocation() const {
823 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
824 return CI->getZExtValue() != 1;
828 const Type *AllocationInst::getAllocatedType() const {
829 return getType()->getElementType();
832 AllocaInst::AllocaInst(const AllocaInst &AI)
833 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
834 Instruction::Alloca, AI.getAlignment()) {
837 MallocInst::MallocInst(const MallocInst &MI)
838 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
839 Instruction::Malloc, MI.getAlignment()) {
842 //===----------------------------------------------------------------------===//
843 // FreeInst Implementation
844 //===----------------------------------------------------------------------===//
846 void FreeInst::AssertOK() {
847 assert(isa<PointerType>(getOperand(0)->getType()) &&
848 "Can not free something of nonpointer type!");
851 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
852 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
856 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
857 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
862 //===----------------------------------------------------------------------===//
863 // LoadInst Implementation
864 //===----------------------------------------------------------------------===//
866 void LoadInst::AssertOK() {
867 assert(isa<PointerType>(getOperand(0)->getType()) &&
868 "Ptr must have pointer type.");
871 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
872 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
873 Load, Ptr, InsertBef) {
880 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
881 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
882 Load, Ptr, InsertAE) {
889 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
890 Instruction *InsertBef)
891 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
892 Load, Ptr, InsertBef) {
893 setVolatile(isVolatile);
899 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
900 unsigned Align, Instruction *InsertBef)
901 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
902 Load, Ptr, InsertBef) {
903 setVolatile(isVolatile);
909 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
910 unsigned Align, BasicBlock *InsertAE)
911 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
912 Load, Ptr, InsertAE) {
913 setVolatile(isVolatile);
919 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
920 BasicBlock *InsertAE)
921 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
922 Load, Ptr, InsertAE) {
923 setVolatile(isVolatile);
931 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
932 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
933 Load, Ptr, InsertBef) {
937 if (Name && Name[0]) setName(Name);
940 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
941 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
942 Load, Ptr, InsertAE) {
946 if (Name && Name[0]) setName(Name);
949 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
950 Instruction *InsertBef)
951 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
952 Load, Ptr, InsertBef) {
953 setVolatile(isVolatile);
956 if (Name && Name[0]) setName(Name);
959 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
960 BasicBlock *InsertAE)
961 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
962 Load, Ptr, InsertAE) {
963 setVolatile(isVolatile);
966 if (Name && Name[0]) setName(Name);
969 void LoadInst::setAlignment(unsigned Align) {
970 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
971 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
974 //===----------------------------------------------------------------------===//
975 // StoreInst Implementation
976 //===----------------------------------------------------------------------===//
978 void StoreInst::AssertOK() {
979 assert(isa<PointerType>(getOperand(1)->getType()) &&
980 "Ptr must have pointer type!");
981 assert(getOperand(0)->getType() ==
982 cast<PointerType>(getOperand(1)->getType())->getElementType()
983 && "Ptr must be a pointer to Val type!");
987 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
988 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
989 Ops[0].init(val, this);
990 Ops[1].init(addr, this);
996 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
997 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
998 Ops[0].init(val, this);
999 Ops[1].init(addr, this);
1005 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1006 Instruction *InsertBefore)
1007 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
1008 Ops[0].init(val, this);
1009 Ops[1].init(addr, this);
1010 setVolatile(isVolatile);
1015 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1016 unsigned Align, Instruction *InsertBefore)
1017 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
1018 Ops[0].init(val, this);
1019 Ops[1].init(addr, this);
1020 setVolatile(isVolatile);
1021 setAlignment(Align);
1025 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1026 unsigned Align, BasicBlock *InsertAtEnd)
1027 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
1028 Ops[0].init(val, this);
1029 Ops[1].init(addr, this);
1030 setVolatile(isVolatile);
1031 setAlignment(Align);
1035 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1036 BasicBlock *InsertAtEnd)
1037 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
1038 Ops[0].init(val, this);
1039 Ops[1].init(addr, this);
1040 setVolatile(isVolatile);
1045 void StoreInst::setAlignment(unsigned Align) {
1046 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1047 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1050 //===----------------------------------------------------------------------===//
1051 // GetElementPtrInst Implementation
1052 //===----------------------------------------------------------------------===//
1054 static unsigned retrieveAddrSpace(const Value *Val) {
1055 return cast<PointerType>(Val->getType())->getAddressSpace();
1058 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
1059 NumOperands = 1+NumIdx;
1060 Use *OL = OperandList = new Use[NumOperands];
1061 OL[0].init(Ptr, this);
1063 for (unsigned i = 0; i != NumIdx; ++i)
1064 OL[i+1].init(Idx[i], this);
1067 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
1069 Use *OL = OperandList = new Use[2];
1070 OL[0].init(Ptr, this);
1071 OL[1].init(Idx, this);
1074 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1075 const std::string &Name, Instruction *InBe)
1076 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1077 retrieveAddrSpace(Ptr)),
1078 GetElementPtr, 0, 0, InBe) {
1083 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1084 const std::string &Name, BasicBlock *IAE)
1085 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1086 retrieveAddrSpace(Ptr)),
1087 GetElementPtr, 0, 0, IAE) {
1092 GetElementPtrInst::~GetElementPtrInst() {
1093 delete[] OperandList;
1096 // getIndexedType - Returns the type of the element that would be loaded with
1097 // a load instruction with the specified parameters.
1099 // A null type is returned if the indices are invalid for the specified
1102 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1105 bool AllowCompositeLeaf) {
1106 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
1108 // Handle the special case of the empty set index set...
1110 if (AllowCompositeLeaf ||
1111 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
1112 return cast<PointerType>(Ptr)->getElementType();
1117 unsigned CurIdx = 0;
1118 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1119 if (NumIdx == CurIdx) {
1120 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1121 return 0; // Can't load a whole structure or array!?!?
1124 Value *Index = Idxs[CurIdx++];
1125 if (isa<PointerType>(CT) && CurIdx != 1)
1126 return 0; // Can only index into pointer types at the first index!
1127 if (!CT->indexValid(Index)) return 0;
1128 Ptr = CT->getTypeAtIndex(Index);
1130 // If the new type forwards to another type, then it is in the middle
1131 // of being refined to another type (and hence, may have dropped all
1132 // references to what it was using before). So, use the new forwarded
1134 if (const Type * Ty = Ptr->getForwardedType()) {
1138 return CurIdx == NumIdx ? Ptr : 0;
1141 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1142 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1143 if (!PTy) return 0; // Type isn't a pointer type!
1145 // Check the pointer index.
1146 if (!PTy->indexValid(Idx)) return 0;
1148 return PTy->getElementType();
1152 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1153 /// zeros. If so, the result pointer and the first operand have the same
1154 /// value, just potentially different types.
1155 bool GetElementPtrInst::hasAllZeroIndices() const {
1156 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1157 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1158 if (!CI->isZero()) return false;
1166 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1167 /// constant integers. If so, the result pointer and the first operand have
1168 /// a constant offset between them.
1169 bool GetElementPtrInst::hasAllConstantIndices() const {
1170 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1171 if (!isa<ConstantInt>(getOperand(i)))
1178 //===----------------------------------------------------------------------===//
1179 // ExtractElementInst Implementation
1180 //===----------------------------------------------------------------------===//
1182 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1183 const std::string &Name,
1184 Instruction *InsertBef)
1185 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1186 ExtractElement, Ops, 2, InsertBef) {
1187 assert(isValidOperands(Val, Index) &&
1188 "Invalid extractelement instruction operands!");
1189 Ops[0].init(Val, this);
1190 Ops[1].init(Index, this);
1194 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1195 const std::string &Name,
1196 Instruction *InsertBef)
1197 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1198 ExtractElement, Ops, 2, InsertBef) {
1199 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1200 assert(isValidOperands(Val, Index) &&
1201 "Invalid extractelement instruction operands!");
1202 Ops[0].init(Val, this);
1203 Ops[1].init(Index, this);
1208 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1209 const std::string &Name,
1210 BasicBlock *InsertAE)
1211 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1212 ExtractElement, Ops, 2, InsertAE) {
1213 assert(isValidOperands(Val, Index) &&
1214 "Invalid extractelement instruction operands!");
1216 Ops[0].init(Val, this);
1217 Ops[1].init(Index, this);
1221 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1222 const std::string &Name,
1223 BasicBlock *InsertAE)
1224 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1225 ExtractElement, Ops, 2, InsertAE) {
1226 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1227 assert(isValidOperands(Val, Index) &&
1228 "Invalid extractelement instruction operands!");
1230 Ops[0].init(Val, this);
1231 Ops[1].init(Index, this);
1236 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1237 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1243 //===----------------------------------------------------------------------===//
1244 // InsertElementInst Implementation
1245 //===----------------------------------------------------------------------===//
1247 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1248 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1249 Ops[0].init(IE.Ops[0], this);
1250 Ops[1].init(IE.Ops[1], this);
1251 Ops[2].init(IE.Ops[2], this);
1253 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1254 const std::string &Name,
1255 Instruction *InsertBef)
1256 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1257 assert(isValidOperands(Vec, Elt, Index) &&
1258 "Invalid insertelement instruction operands!");
1259 Ops[0].init(Vec, this);
1260 Ops[1].init(Elt, this);
1261 Ops[2].init(Index, this);
1265 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1266 const std::string &Name,
1267 Instruction *InsertBef)
1268 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1269 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1270 assert(isValidOperands(Vec, Elt, Index) &&
1271 "Invalid insertelement instruction operands!");
1272 Ops[0].init(Vec, this);
1273 Ops[1].init(Elt, this);
1274 Ops[2].init(Index, this);
1279 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1280 const std::string &Name,
1281 BasicBlock *InsertAE)
1282 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1283 assert(isValidOperands(Vec, Elt, Index) &&
1284 "Invalid insertelement instruction operands!");
1286 Ops[0].init(Vec, this);
1287 Ops[1].init(Elt, this);
1288 Ops[2].init(Index, this);
1292 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1293 const std::string &Name,
1294 BasicBlock *InsertAE)
1295 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1296 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1297 assert(isValidOperands(Vec, Elt, Index) &&
1298 "Invalid insertelement instruction operands!");
1300 Ops[0].init(Vec, this);
1301 Ops[1].init(Elt, this);
1302 Ops[2].init(Index, this);
1306 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1307 const Value *Index) {
1308 if (!isa<VectorType>(Vec->getType()))
1309 return false; // First operand of insertelement must be vector type.
1311 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1312 return false;// Second operand of insertelement must be vector element type.
1314 if (Index->getType() != Type::Int32Ty)
1315 return false; // Third operand of insertelement must be uint.
1320 //===----------------------------------------------------------------------===//
1321 // ShuffleVectorInst Implementation
1322 //===----------------------------------------------------------------------===//
1324 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1325 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1326 Ops[0].init(SV.Ops[0], this);
1327 Ops[1].init(SV.Ops[1], this);
1328 Ops[2].init(SV.Ops[2], this);
1331 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1332 const std::string &Name,
1333 Instruction *InsertBefore)
1334 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1335 assert(isValidOperands(V1, V2, Mask) &&
1336 "Invalid shuffle vector instruction operands!");
1337 Ops[0].init(V1, this);
1338 Ops[1].init(V2, this);
1339 Ops[2].init(Mask, this);
1343 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1344 const std::string &Name,
1345 BasicBlock *InsertAtEnd)
1346 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1347 assert(isValidOperands(V1, V2, Mask) &&
1348 "Invalid shuffle vector instruction operands!");
1350 Ops[0].init(V1, this);
1351 Ops[1].init(V2, this);
1352 Ops[2].init(Mask, this);
1356 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1357 const Value *Mask) {
1358 if (!isa<VectorType>(V1->getType())) return false;
1359 if (V1->getType() != V2->getType()) return false;
1360 if (!isa<VectorType>(Mask->getType()) ||
1361 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1362 cast<VectorType>(Mask->getType())->getNumElements() !=
1363 cast<VectorType>(V1->getType())->getNumElements())
1369 //===----------------------------------------------------------------------===//
1370 // BinaryOperator Class
1371 //===----------------------------------------------------------------------===//
1373 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1374 const Type *Ty, const std::string &Name,
1375 Instruction *InsertBefore)
1376 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1377 Ops[0].init(S1, this);
1378 Ops[1].init(S2, this);
1383 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1384 const Type *Ty, const std::string &Name,
1385 BasicBlock *InsertAtEnd)
1386 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1387 Ops[0].init(S1, this);
1388 Ops[1].init(S2, this);
1394 void BinaryOperator::init(BinaryOps iType) {
1395 Value *LHS = getOperand(0), *RHS = getOperand(1);
1396 LHS = LHS; RHS = RHS; // Silence warnings.
1397 assert(LHS->getType() == RHS->getType() &&
1398 "Binary operator operand types must match!");
1403 assert(getType() == LHS->getType() &&
1404 "Arithmetic operation should return same type as operands!");
1405 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1406 isa<VectorType>(getType())) &&
1407 "Tried to create an arithmetic operation on a non-arithmetic type!");
1411 assert(getType() == LHS->getType() &&
1412 "Arithmetic operation should return same type as operands!");
1413 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1414 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1415 "Incorrect operand type (not integer) for S/UDIV");
1418 assert(getType() == LHS->getType() &&
1419 "Arithmetic operation should return same type as operands!");
1420 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1421 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1422 && "Incorrect operand type (not floating point) for FDIV");
1426 assert(getType() == LHS->getType() &&
1427 "Arithmetic operation should return same type as operands!");
1428 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1429 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1430 "Incorrect operand type (not integer) for S/UREM");
1433 assert(getType() == LHS->getType() &&
1434 "Arithmetic operation should return same type as operands!");
1435 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1436 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1437 && "Incorrect operand type (not floating point) for FREM");
1442 assert(getType() == LHS->getType() &&
1443 "Shift operation should return same type as operands!");
1444 assert(getType()->isInteger() &&
1445 "Shift operation requires integer operands");
1449 assert(getType() == LHS->getType() &&
1450 "Logical operation should return same type as operands!");
1451 assert((getType()->isInteger() ||
1452 (isa<VectorType>(getType()) &&
1453 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1454 "Tried to create a logical operation on a non-integral type!");
1462 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1463 const std::string &Name,
1464 Instruction *InsertBefore) {
1465 assert(S1->getType() == S2->getType() &&
1466 "Cannot create binary operator with two operands of differing type!");
1467 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1470 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1471 const std::string &Name,
1472 BasicBlock *InsertAtEnd) {
1473 BinaryOperator *Res = create(Op, S1, S2, Name);
1474 InsertAtEnd->getInstList().push_back(Res);
1478 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1479 Instruction *InsertBefore) {
1480 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1481 return new BinaryOperator(Instruction::Sub,
1483 Op->getType(), Name, InsertBefore);
1486 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1487 BasicBlock *InsertAtEnd) {
1488 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1489 return new BinaryOperator(Instruction::Sub,
1491 Op->getType(), Name, InsertAtEnd);
1494 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1495 Instruction *InsertBefore) {
1497 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1498 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1499 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1501 C = ConstantInt::getAllOnesValue(Op->getType());
1504 return new BinaryOperator(Instruction::Xor, Op, C,
1505 Op->getType(), Name, InsertBefore);
1508 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1509 BasicBlock *InsertAtEnd) {
1511 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1512 // Create a vector of all ones values.
1513 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1515 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1517 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1520 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1521 Op->getType(), Name, InsertAtEnd);
1525 // isConstantAllOnes - Helper function for several functions below
1526 static inline bool isConstantAllOnes(const Value *V) {
1527 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1528 return CI->isAllOnesValue();
1529 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1530 return CV->isAllOnesValue();
1534 bool BinaryOperator::isNeg(const Value *V) {
1535 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1536 if (Bop->getOpcode() == Instruction::Sub)
1537 return Bop->getOperand(0) ==
1538 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1542 bool BinaryOperator::isNot(const Value *V) {
1543 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1544 return (Bop->getOpcode() == Instruction::Xor &&
1545 (isConstantAllOnes(Bop->getOperand(1)) ||
1546 isConstantAllOnes(Bop->getOperand(0))));
1550 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1551 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1552 return cast<BinaryOperator>(BinOp)->getOperand(1);
1555 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1556 return getNegArgument(const_cast<Value*>(BinOp));
1559 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1560 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1561 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1562 Value *Op0 = BO->getOperand(0);
1563 Value *Op1 = BO->getOperand(1);
1564 if (isConstantAllOnes(Op0)) return Op1;
1566 assert(isConstantAllOnes(Op1));
1570 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1571 return getNotArgument(const_cast<Value*>(BinOp));
1575 // swapOperands - Exchange the two operands to this instruction. This
1576 // instruction is safe to use on any binary instruction and does not
1577 // modify the semantics of the instruction. If the instruction is
1578 // order dependent (SetLT f.e.) the opcode is changed.
1580 bool BinaryOperator::swapOperands() {
1581 if (!isCommutative())
1582 return true; // Can't commute operands
1583 std::swap(Ops[0], Ops[1]);
1587 //===----------------------------------------------------------------------===//
1589 //===----------------------------------------------------------------------===//
1591 // Just determine if this cast only deals with integral->integral conversion.
1592 bool CastInst::isIntegerCast() const {
1593 switch (getOpcode()) {
1594 default: return false;
1595 case Instruction::ZExt:
1596 case Instruction::SExt:
1597 case Instruction::Trunc:
1599 case Instruction::BitCast:
1600 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1604 bool CastInst::isLosslessCast() const {
1605 // Only BitCast can be lossless, exit fast if we're not BitCast
1606 if (getOpcode() != Instruction::BitCast)
1609 // Identity cast is always lossless
1610 const Type* SrcTy = getOperand(0)->getType();
1611 const Type* DstTy = getType();
1615 // Pointer to pointer is always lossless.
1616 if (isa<PointerType>(SrcTy))
1617 return isa<PointerType>(DstTy);
1618 return false; // Other types have no identity values
1621 /// This function determines if the CastInst does not require any bits to be
1622 /// changed in order to effect the cast. Essentially, it identifies cases where
1623 /// no code gen is necessary for the cast, hence the name no-op cast. For
1624 /// example, the following are all no-op casts:
1625 /// # bitcast uint %X, int
1626 /// # bitcast uint* %x, sbyte*
1627 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1628 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1629 /// @brief Determine if a cast is a no-op.
1630 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1631 switch (getOpcode()) {
1633 assert(!"Invalid CastOp");
1634 case Instruction::Trunc:
1635 case Instruction::ZExt:
1636 case Instruction::SExt:
1637 case Instruction::FPTrunc:
1638 case Instruction::FPExt:
1639 case Instruction::UIToFP:
1640 case Instruction::SIToFP:
1641 case Instruction::FPToUI:
1642 case Instruction::FPToSI:
1643 return false; // These always modify bits
1644 case Instruction::BitCast:
1645 return true; // BitCast never modifies bits.
1646 case Instruction::PtrToInt:
1647 return IntPtrTy->getPrimitiveSizeInBits() ==
1648 getType()->getPrimitiveSizeInBits();
1649 case Instruction::IntToPtr:
1650 return IntPtrTy->getPrimitiveSizeInBits() ==
1651 getOperand(0)->getType()->getPrimitiveSizeInBits();
1655 /// This function determines if a pair of casts can be eliminated and what
1656 /// opcode should be used in the elimination. This assumes that there are two
1657 /// instructions like this:
1658 /// * %F = firstOpcode SrcTy %x to MidTy
1659 /// * %S = secondOpcode MidTy %F to DstTy
1660 /// The function returns a resultOpcode so these two casts can be replaced with:
1661 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1662 /// If no such cast is permited, the function returns 0.
1663 unsigned CastInst::isEliminableCastPair(
1664 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1665 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1667 // Define the 144 possibilities for these two cast instructions. The values
1668 // in this matrix determine what to do in a given situation and select the
1669 // case in the switch below. The rows correspond to firstOp, the columns
1670 // correspond to secondOp. In looking at the table below, keep in mind
1671 // the following cast properties:
1673 // Size Compare Source Destination
1674 // Operator Src ? Size Type Sign Type Sign
1675 // -------- ------------ ------------------- ---------------------
1676 // TRUNC > Integer Any Integral Any
1677 // ZEXT < Integral Unsigned Integer Any
1678 // SEXT < Integral Signed Integer Any
1679 // FPTOUI n/a FloatPt n/a Integral Unsigned
1680 // FPTOSI n/a FloatPt n/a Integral Signed
1681 // UITOFP n/a Integral Unsigned FloatPt n/a
1682 // SITOFP n/a Integral Signed FloatPt n/a
1683 // FPTRUNC > FloatPt n/a FloatPt n/a
1684 // FPEXT < FloatPt n/a FloatPt n/a
1685 // PTRTOINT n/a Pointer n/a Integral Unsigned
1686 // INTTOPTR n/a Integral Unsigned Pointer n/a
1687 // BITCONVERT = FirstClass n/a FirstClass n/a
1689 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1690 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1691 // into "fptoui double to ulong", but this loses information about the range
1692 // of the produced value (we no longer know the top-part is all zeros).
1693 // Further this conversion is often much more expensive for typical hardware,
1694 // and causes issues when building libgcc. We disallow fptosi+sext for the
1696 const unsigned numCastOps =
1697 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1698 static const uint8_t CastResults[numCastOps][numCastOps] = {
1699 // T F F U S F F P I B -+
1700 // R Z S P P I I T P 2 N T |
1701 // U E E 2 2 2 2 R E I T C +- secondOp
1702 // N X X U S F F N X N 2 V |
1703 // C T T I I P P C T T P T -+
1704 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1705 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1706 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1707 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1708 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1709 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1710 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1711 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1712 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1713 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1714 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1715 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1718 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1719 [secondOp-Instruction::CastOpsBegin];
1722 // categorically disallowed
1725 // allowed, use first cast's opcode
1728 // allowed, use second cast's opcode
1731 // no-op cast in second op implies firstOp as long as the DestTy
1733 if (DstTy->isInteger())
1737 // no-op cast in second op implies firstOp as long as the DestTy
1738 // is floating point
1739 if (DstTy->isFloatingPoint())
1743 // no-op cast in first op implies secondOp as long as the SrcTy
1745 if (SrcTy->isInteger())
1749 // no-op cast in first op implies secondOp as long as the SrcTy
1750 // is a floating point
1751 if (SrcTy->isFloatingPoint())
1755 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1756 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1757 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1758 if (MidSize >= PtrSize)
1759 return Instruction::BitCast;
1763 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1764 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1765 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1766 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1767 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1768 if (SrcSize == DstSize)
1769 return Instruction::BitCast;
1770 else if (SrcSize < DstSize)
1774 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1775 return Instruction::ZExt;
1777 // fpext followed by ftrunc is allowed if the bit size returned to is
1778 // the same as the original, in which case its just a bitcast
1780 return Instruction::BitCast;
1781 return 0; // If the types are not the same we can't eliminate it.
1783 // bitcast followed by ptrtoint is allowed as long as the bitcast
1784 // is a pointer to pointer cast.
1785 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1789 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1790 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1794 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1795 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1796 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1797 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1798 if (SrcSize <= PtrSize && SrcSize == DstSize)
1799 return Instruction::BitCast;
1803 // cast combination can't happen (error in input). This is for all cases
1804 // where the MidTy is not the same for the two cast instructions.
1805 assert(!"Invalid Cast Combination");
1808 assert(!"Error in CastResults table!!!");
1814 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1815 const std::string &Name, Instruction *InsertBefore) {
1816 // Construct and return the appropriate CastInst subclass
1818 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1819 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1820 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1821 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1822 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1823 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1824 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1825 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1826 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1827 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1828 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1829 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1831 assert(!"Invalid opcode provided");
1836 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1837 const std::string &Name, BasicBlock *InsertAtEnd) {
1838 // Construct and return the appropriate CastInst subclass
1840 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1841 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1842 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1843 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1844 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1845 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1846 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1847 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1848 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1849 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1850 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1851 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1853 assert(!"Invalid opcode provided");
1858 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1859 const std::string &Name,
1860 Instruction *InsertBefore) {
1861 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1862 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1863 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1866 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1867 const std::string &Name,
1868 BasicBlock *InsertAtEnd) {
1869 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1870 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1871 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1874 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1875 const std::string &Name,
1876 Instruction *InsertBefore) {
1877 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1878 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1879 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1882 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1883 const std::string &Name,
1884 BasicBlock *InsertAtEnd) {
1885 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1886 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1887 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1890 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1891 const std::string &Name,
1892 Instruction *InsertBefore) {
1893 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1894 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1895 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1898 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1899 const std::string &Name,
1900 BasicBlock *InsertAtEnd) {
1901 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1902 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1903 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1906 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1907 const std::string &Name,
1908 BasicBlock *InsertAtEnd) {
1909 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1910 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1913 if (Ty->isInteger())
1914 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1915 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1918 /// @brief Create a BitCast or a PtrToInt cast instruction
1919 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1920 const std::string &Name,
1921 Instruction *InsertBefore) {
1922 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1923 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1926 if (Ty->isInteger())
1927 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1928 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1931 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1932 bool isSigned, const std::string &Name,
1933 Instruction *InsertBefore) {
1934 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1935 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1936 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1937 Instruction::CastOps opcode =
1938 (SrcBits == DstBits ? Instruction::BitCast :
1939 (SrcBits > DstBits ? Instruction::Trunc :
1940 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1941 return create(opcode, C, Ty, Name, InsertBefore);
1944 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1945 bool isSigned, const std::string &Name,
1946 BasicBlock *InsertAtEnd) {
1947 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1948 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1949 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1950 Instruction::CastOps opcode =
1951 (SrcBits == DstBits ? Instruction::BitCast :
1952 (SrcBits > DstBits ? Instruction::Trunc :
1953 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1954 return create(opcode, C, Ty, Name, InsertAtEnd);
1957 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1958 const std::string &Name,
1959 Instruction *InsertBefore) {
1960 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1962 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1963 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1964 Instruction::CastOps opcode =
1965 (SrcBits == DstBits ? Instruction::BitCast :
1966 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1967 return create(opcode, C, Ty, Name, InsertBefore);
1970 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1971 const std::string &Name,
1972 BasicBlock *InsertAtEnd) {
1973 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1975 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1976 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1977 Instruction::CastOps opcode =
1978 (SrcBits == DstBits ? Instruction::BitCast :
1979 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1980 return create(opcode, C, Ty, Name, InsertAtEnd);
1983 // Check whether it is valid to call getCastOpcode for these types.
1984 // This routine must be kept in sync with getCastOpcode.
1985 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1986 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1989 if (SrcTy == DestTy)
1992 // Get the bit sizes, we'll need these
1993 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1994 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1996 // Run through the possibilities ...
1997 if (DestTy->isInteger()) { // Casting to integral
1998 if (SrcTy->isInteger()) { // Casting from integral
2000 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2002 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2003 // Casting from vector
2004 return DestBits == PTy->getBitWidth();
2005 } else { // Casting from something else
2006 return isa<PointerType>(SrcTy);
2008 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2009 if (SrcTy->isInteger()) { // Casting from integral
2011 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2013 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2014 // Casting from vector
2015 return DestBits == PTy->getBitWidth();
2016 } else { // Casting from something else
2019 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2020 // Casting to vector
2021 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2022 // Casting from vector
2023 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2024 } else { // Casting from something else
2025 return DestPTy->getBitWidth() == SrcBits;
2027 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2028 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2030 } else if (SrcTy->isInteger()) { // Casting from integral
2032 } else { // Casting from something else
2035 } else { // Casting to something else
2040 // Provide a way to get a "cast" where the cast opcode is inferred from the
2041 // types and size of the operand. This, basically, is a parallel of the
2042 // logic in the castIsValid function below. This axiom should hold:
2043 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2044 // should not assert in castIsValid. In other words, this produces a "correct"
2045 // casting opcode for the arguments passed to it.
2046 // This routine must be kept in sync with isCastable.
2047 Instruction::CastOps
2048 CastInst::getCastOpcode(
2049 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2050 // Get the bit sizes, we'll need these
2051 const Type *SrcTy = Src->getType();
2052 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2053 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2055 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2056 "Only first class types are castable!");
2058 // Run through the possibilities ...
2059 if (DestTy->isInteger()) { // Casting to integral
2060 if (SrcTy->isInteger()) { // Casting from integral
2061 if (DestBits < SrcBits)
2062 return Trunc; // int -> smaller int
2063 else if (DestBits > SrcBits) { // its an extension
2065 return SExt; // signed -> SEXT
2067 return ZExt; // unsigned -> ZEXT
2069 return BitCast; // Same size, No-op cast
2071 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2073 return FPToSI; // FP -> sint
2075 return FPToUI; // FP -> uint
2076 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2077 assert(DestBits == PTy->getBitWidth() &&
2078 "Casting vector to integer of different width");
2079 return BitCast; // Same size, no-op cast
2081 assert(isa<PointerType>(SrcTy) &&
2082 "Casting from a value that is not first-class type");
2083 return PtrToInt; // ptr -> int
2085 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2086 if (SrcTy->isInteger()) { // Casting from integral
2088 return SIToFP; // sint -> FP
2090 return UIToFP; // uint -> FP
2091 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2092 if (DestBits < SrcBits) {
2093 return FPTrunc; // FP -> smaller FP
2094 } else if (DestBits > SrcBits) {
2095 return FPExt; // FP -> larger FP
2097 return BitCast; // same size, no-op cast
2099 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2100 assert(DestBits == PTy->getBitWidth() &&
2101 "Casting vector to floating point of different width");
2102 return BitCast; // same size, no-op cast
2104 assert(0 && "Casting pointer or non-first class to float");
2106 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2107 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2108 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2109 "Casting vector to vector of different widths");
2110 return BitCast; // vector -> vector
2111 } else if (DestPTy->getBitWidth() == SrcBits) {
2112 return BitCast; // float/int -> vector
2114 assert(!"Illegal cast to vector (wrong type or size)");
2116 } else if (isa<PointerType>(DestTy)) {
2117 if (isa<PointerType>(SrcTy)) {
2118 return BitCast; // ptr -> ptr
2119 } else if (SrcTy->isInteger()) {
2120 return IntToPtr; // int -> ptr
2122 assert(!"Casting pointer to other than pointer or int");
2125 assert(!"Casting to type that is not first-class");
2128 // If we fall through to here we probably hit an assertion cast above
2129 // and assertions are not turned on. Anything we return is an error, so
2130 // BitCast is as good a choice as any.
2134 //===----------------------------------------------------------------------===//
2135 // CastInst SubClass Constructors
2136 //===----------------------------------------------------------------------===//
2138 /// Check that the construction parameters for a CastInst are correct. This
2139 /// could be broken out into the separate constructors but it is useful to have
2140 /// it in one place and to eliminate the redundant code for getting the sizes
2141 /// of the types involved.
2143 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2145 // Check for type sanity on the arguments
2146 const Type *SrcTy = S->getType();
2147 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2150 // Get the size of the types in bits, we'll need this later
2151 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2152 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2154 // Switch on the opcode provided
2156 default: return false; // This is an input error
2157 case Instruction::Trunc:
2158 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2159 case Instruction::ZExt:
2160 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2161 case Instruction::SExt:
2162 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2163 case Instruction::FPTrunc:
2164 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2165 SrcBitSize > DstBitSize;
2166 case Instruction::FPExt:
2167 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2168 SrcBitSize < DstBitSize;
2169 case Instruction::UIToFP:
2170 case Instruction::SIToFP:
2171 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2172 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2173 return SVTy->getElementType()->isInteger() &&
2174 DVTy->getElementType()->isFloatingPoint() &&
2175 SVTy->getNumElements() == DVTy->getNumElements();
2178 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2179 case Instruction::FPToUI:
2180 case Instruction::FPToSI:
2181 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2182 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2183 return SVTy->getElementType()->isFloatingPoint() &&
2184 DVTy->getElementType()->isInteger() &&
2185 SVTy->getNumElements() == DVTy->getNumElements();
2188 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2189 case Instruction::PtrToInt:
2190 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2191 case Instruction::IntToPtr:
2192 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2193 case Instruction::BitCast:
2194 // BitCast implies a no-op cast of type only. No bits change.
2195 // However, you can't cast pointers to anything but pointers.
2196 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2199 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2200 // these cases, the cast is okay if the source and destination bit widths
2202 return SrcBitSize == DstBitSize;
2206 TruncInst::TruncInst(
2207 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2208 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2209 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2212 TruncInst::TruncInst(
2213 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2214 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2215 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2219 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2220 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2221 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2225 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2226 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2227 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2230 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2231 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2232 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2236 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2237 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2238 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2241 FPTruncInst::FPTruncInst(
2242 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2243 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2244 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2247 FPTruncInst::FPTruncInst(
2248 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2249 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2250 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2253 FPExtInst::FPExtInst(
2254 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2255 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2256 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2259 FPExtInst::FPExtInst(
2260 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2261 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2262 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2265 UIToFPInst::UIToFPInst(
2266 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2267 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2268 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2271 UIToFPInst::UIToFPInst(
2272 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2273 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2274 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2277 SIToFPInst::SIToFPInst(
2278 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2279 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2280 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2283 SIToFPInst::SIToFPInst(
2284 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2285 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2286 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2289 FPToUIInst::FPToUIInst(
2290 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2291 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2292 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2295 FPToUIInst::FPToUIInst(
2296 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2297 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2298 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2301 FPToSIInst::FPToSIInst(
2302 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2303 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2304 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2307 FPToSIInst::FPToSIInst(
2308 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2309 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2310 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2313 PtrToIntInst::PtrToIntInst(
2314 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2315 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2316 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2319 PtrToIntInst::PtrToIntInst(
2320 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2321 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2322 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2325 IntToPtrInst::IntToPtrInst(
2326 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2327 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2328 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2331 IntToPtrInst::IntToPtrInst(
2332 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2333 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2334 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2337 BitCastInst::BitCastInst(
2338 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2339 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2340 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2343 BitCastInst::BitCastInst(
2344 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2345 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2346 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2349 //===----------------------------------------------------------------------===//
2351 //===----------------------------------------------------------------------===//
2353 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2354 const std::string &Name, Instruction *InsertBefore)
2355 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2356 Ops[0].init(LHS, this);
2357 Ops[1].init(RHS, this);
2358 SubclassData = predicate;
2360 if (op == Instruction::ICmp) {
2361 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2362 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2363 "Invalid ICmp predicate value");
2364 const Type* Op0Ty = getOperand(0)->getType();
2365 const Type* Op1Ty = getOperand(1)->getType();
2366 assert(Op0Ty == Op1Ty &&
2367 "Both operands to ICmp instruction are not of the same type!");
2368 // Check that the operands are the right type
2369 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2370 "Invalid operand types for ICmp instruction");
2373 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2374 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2375 "Invalid FCmp predicate value");
2376 const Type* Op0Ty = getOperand(0)->getType();
2377 const Type* Op1Ty = getOperand(1)->getType();
2378 assert(Op0Ty == Op1Ty &&
2379 "Both operands to FCmp instruction are not of the same type!");
2380 // Check that the operands are the right type
2381 assert(Op0Ty->isFloatingPoint() &&
2382 "Invalid operand types for FCmp instruction");
2385 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2386 const std::string &Name, BasicBlock *InsertAtEnd)
2387 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2388 Ops[0].init(LHS, this);
2389 Ops[1].init(RHS, this);
2390 SubclassData = predicate;
2392 if (op == Instruction::ICmp) {
2393 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2394 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2395 "Invalid ICmp predicate value");
2397 const Type* Op0Ty = getOperand(0)->getType();
2398 const Type* Op1Ty = getOperand(1)->getType();
2399 assert(Op0Ty == Op1Ty &&
2400 "Both operands to ICmp instruction are not of the same type!");
2401 // Check that the operands are the right type
2402 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2403 "Invalid operand types for ICmp instruction");
2406 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2407 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2408 "Invalid FCmp predicate value");
2409 const Type* Op0Ty = getOperand(0)->getType();
2410 const Type* Op1Ty = getOperand(1)->getType();
2411 assert(Op0Ty == Op1Ty &&
2412 "Both operands to FCmp instruction are not of the same type!");
2413 // Check that the operands are the right type
2414 assert(Op0Ty->isFloatingPoint() &&
2415 "Invalid operand types for FCmp instruction");
2419 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2420 const std::string &Name, Instruction *InsertBefore) {
2421 if (Op == Instruction::ICmp) {
2422 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2425 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2430 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2431 const std::string &Name, BasicBlock *InsertAtEnd) {
2432 if (Op == Instruction::ICmp) {
2433 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2436 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2440 void CmpInst::swapOperands() {
2441 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2444 cast<FCmpInst>(this)->swapOperands();
2447 bool CmpInst::isCommutative() {
2448 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2449 return IC->isCommutative();
2450 return cast<FCmpInst>(this)->isCommutative();
2453 bool CmpInst::isEquality() {
2454 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2455 return IC->isEquality();
2456 return cast<FCmpInst>(this)->isEquality();
2460 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2463 assert(!"Unknown icmp predicate!");
2464 case ICMP_EQ: return ICMP_NE;
2465 case ICMP_NE: return ICMP_EQ;
2466 case ICMP_UGT: return ICMP_ULE;
2467 case ICMP_ULT: return ICMP_UGE;
2468 case ICMP_UGE: return ICMP_ULT;
2469 case ICMP_ULE: return ICMP_UGT;
2470 case ICMP_SGT: return ICMP_SLE;
2471 case ICMP_SLT: return ICMP_SGE;
2472 case ICMP_SGE: return ICMP_SLT;
2473 case ICMP_SLE: return ICMP_SGT;
2477 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2479 default: assert(! "Unknown icmp predicate!");
2480 case ICMP_EQ: case ICMP_NE:
2482 case ICMP_SGT: return ICMP_SLT;
2483 case ICMP_SLT: return ICMP_SGT;
2484 case ICMP_SGE: return ICMP_SLE;
2485 case ICMP_SLE: return ICMP_SGE;
2486 case ICMP_UGT: return ICMP_ULT;
2487 case ICMP_ULT: return ICMP_UGT;
2488 case ICMP_UGE: return ICMP_ULE;
2489 case ICMP_ULE: return ICMP_UGE;
2493 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2495 default: assert(! "Unknown icmp predicate!");
2496 case ICMP_EQ: case ICMP_NE:
2497 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2499 case ICMP_UGT: return ICMP_SGT;
2500 case ICMP_ULT: return ICMP_SLT;
2501 case ICMP_UGE: return ICMP_SGE;
2502 case ICMP_ULE: return ICMP_SLE;
2506 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2508 default: assert(! "Unknown icmp predicate!");
2509 case ICMP_EQ: case ICMP_NE:
2510 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2512 case ICMP_SGT: return ICMP_UGT;
2513 case ICMP_SLT: return ICMP_ULT;
2514 case ICMP_SGE: return ICMP_UGE;
2515 case ICMP_SLE: return ICMP_ULE;
2519 bool ICmpInst::isSignedPredicate(Predicate pred) {
2521 default: assert(! "Unknown icmp predicate!");
2522 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2524 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2525 case ICMP_UGE: case ICMP_ULE:
2530 /// Initialize a set of values that all satisfy the condition with C.
2533 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2536 uint32_t BitWidth = C.getBitWidth();
2538 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2539 case ICmpInst::ICMP_EQ: Upper++; break;
2540 case ICmpInst::ICMP_NE: Lower++; break;
2541 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2542 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2543 case ICmpInst::ICMP_UGT:
2544 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2546 case ICmpInst::ICMP_SGT:
2547 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2549 case ICmpInst::ICMP_ULE:
2550 Lower = APInt::getMinValue(BitWidth); Upper++;
2552 case ICmpInst::ICMP_SLE:
2553 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2555 case ICmpInst::ICMP_UGE:
2556 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2558 case ICmpInst::ICMP_SGE:
2559 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2562 return ConstantRange(Lower, Upper);
2565 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2568 assert(!"Unknown icmp predicate!");
2569 case FCMP_OEQ: return FCMP_UNE;
2570 case FCMP_ONE: return FCMP_UEQ;
2571 case FCMP_OGT: return FCMP_ULE;
2572 case FCMP_OLT: return FCMP_UGE;
2573 case FCMP_OGE: return FCMP_ULT;
2574 case FCMP_OLE: return FCMP_UGT;
2575 case FCMP_UEQ: return FCMP_ONE;
2576 case FCMP_UNE: return FCMP_OEQ;
2577 case FCMP_UGT: return FCMP_OLE;
2578 case FCMP_ULT: return FCMP_OGE;
2579 case FCMP_UGE: return FCMP_OLT;
2580 case FCMP_ULE: return FCMP_OGT;
2581 case FCMP_ORD: return FCMP_UNO;
2582 case FCMP_UNO: return FCMP_ORD;
2583 case FCMP_TRUE: return FCMP_FALSE;
2584 case FCMP_FALSE: return FCMP_TRUE;
2588 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2590 default: assert(!"Unknown fcmp predicate!");
2591 case FCMP_FALSE: case FCMP_TRUE:
2592 case FCMP_OEQ: case FCMP_ONE:
2593 case FCMP_UEQ: case FCMP_UNE:
2594 case FCMP_ORD: case FCMP_UNO:
2596 case FCMP_OGT: return FCMP_OLT;
2597 case FCMP_OLT: return FCMP_OGT;
2598 case FCMP_OGE: return FCMP_OLE;
2599 case FCMP_OLE: return FCMP_OGE;
2600 case FCMP_UGT: return FCMP_ULT;
2601 case FCMP_ULT: return FCMP_UGT;
2602 case FCMP_UGE: return FCMP_ULE;
2603 case FCMP_ULE: return FCMP_UGE;
2607 bool CmpInst::isUnsigned(unsigned short predicate) {
2608 switch (predicate) {
2609 default: return false;
2610 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2611 case ICmpInst::ICMP_UGE: return true;
2615 bool CmpInst::isSigned(unsigned short predicate){
2616 switch (predicate) {
2617 default: return false;
2618 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2619 case ICmpInst::ICMP_SGE: return true;
2623 bool CmpInst::isOrdered(unsigned short predicate) {
2624 switch (predicate) {
2625 default: return false;
2626 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2627 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2628 case FCmpInst::FCMP_ORD: return true;
2632 bool CmpInst::isUnordered(unsigned short predicate) {
2633 switch (predicate) {
2634 default: return false;
2635 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2636 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2637 case FCmpInst::FCMP_UNO: return true;
2641 //===----------------------------------------------------------------------===//
2642 // SwitchInst Implementation
2643 //===----------------------------------------------------------------------===//
2645 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2646 assert(Value && Default);
2647 ReservedSpace = 2+NumCases*2;
2649 OperandList = new Use[ReservedSpace];
2651 OperandList[0].init(Value, this);
2652 OperandList[1].init(Default, this);
2655 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2656 /// switch on and a default destination. The number of additional cases can
2657 /// be specified here to make memory allocation more efficient. This
2658 /// constructor can also autoinsert before another instruction.
2659 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2660 Instruction *InsertBefore)
2661 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2662 init(Value, Default, NumCases);
2665 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2666 /// switch on and a default destination. The number of additional cases can
2667 /// be specified here to make memory allocation more efficient. This
2668 /// constructor also autoinserts at the end of the specified BasicBlock.
2669 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2670 BasicBlock *InsertAtEnd)
2671 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2672 init(Value, Default, NumCases);
2675 SwitchInst::SwitchInst(const SwitchInst &SI)
2676 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2677 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2678 Use *OL = OperandList, *InOL = SI.OperandList;
2679 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2680 OL[i].init(InOL[i], this);
2681 OL[i+1].init(InOL[i+1], this);
2685 SwitchInst::~SwitchInst() {
2686 delete [] OperandList;
2690 /// addCase - Add an entry to the switch instruction...
2692 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2693 unsigned OpNo = NumOperands;
2694 if (OpNo+2 > ReservedSpace)
2695 resizeOperands(0); // Get more space!
2696 // Initialize some new operands.
2697 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2698 NumOperands = OpNo+2;
2699 OperandList[OpNo].init(OnVal, this);
2700 OperandList[OpNo+1].init(Dest, this);
2703 /// removeCase - This method removes the specified successor from the switch
2704 /// instruction. Note that this cannot be used to remove the default
2705 /// destination (successor #0).
2707 void SwitchInst::removeCase(unsigned idx) {
2708 assert(idx != 0 && "Cannot remove the default case!");
2709 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2711 unsigned NumOps = getNumOperands();
2712 Use *OL = OperandList;
2714 // Move everything after this operand down.
2716 // FIXME: we could just swap with the end of the list, then erase. However,
2717 // client might not expect this to happen. The code as it is thrashes the
2718 // use/def lists, which is kinda lame.
2719 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2721 OL[i-2+1] = OL[i+1];
2724 // Nuke the last value.
2725 OL[NumOps-2].set(0);
2726 OL[NumOps-2+1].set(0);
2727 NumOperands = NumOps-2;
2730 /// resizeOperands - resize operands - This adjusts the length of the operands
2731 /// list according to the following behavior:
2732 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2733 /// of operation. This grows the number of ops by 1.5 times.
2734 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2735 /// 3. If NumOps == NumOperands, trim the reserved space.
2737 void SwitchInst::resizeOperands(unsigned NumOps) {
2739 NumOps = getNumOperands()/2*6;
2740 } else if (NumOps*2 > NumOperands) {
2741 // No resize needed.
2742 if (ReservedSpace >= NumOps) return;
2743 } else if (NumOps == NumOperands) {
2744 if (ReservedSpace == NumOps) return;
2749 ReservedSpace = NumOps;
2750 Use *NewOps = new Use[NumOps];
2751 Use *OldOps = OperandList;
2752 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2753 NewOps[i].init(OldOps[i], this);
2757 OperandList = NewOps;
2761 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2762 return getSuccessor(idx);
2764 unsigned SwitchInst::getNumSuccessorsV() const {
2765 return getNumSuccessors();
2767 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2768 setSuccessor(idx, B);
2771 //===----------------------------------------------------------------------===//
2772 // GetResultInst Implementation
2773 //===----------------------------------------------------------------------===//
2775 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2776 const std::string &Name,
2777 Instruction *InsertBef)
2778 : Instruction(cast<StructType>(Aggregate->getType())->getElementType(Index),
2779 GetResult, &Aggr, 1, InsertBef) {
2780 assert(isValidOperands(Aggregate, Index) && "Invalid GetResultInst operands!");
2781 Aggr.init(Aggregate, this);
2786 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2790 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2791 unsigned NumElements = STy->getNumElements();
2792 if (Index >= NumElements)
2795 // getresult aggregate value's element types are restricted to
2796 // avoid nested aggregates.
2797 for (unsigned i = 0; i < NumElements; ++i)
2798 if (!STy->getElementType(i)->isFirstClassType())
2801 // Otherwise, Aggregate is valid.
2807 // Define these methods here so vtables don't get emitted into every translation
2808 // unit that uses these classes.
2810 GetElementPtrInst *GetElementPtrInst::clone() const {
2811 return new GetElementPtrInst(*this);
2814 BinaryOperator *BinaryOperator::clone() const {
2815 return create(getOpcode(), Ops[0], Ops[1]);
2818 FCmpInst* FCmpInst::clone() const {
2819 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2821 ICmpInst* ICmpInst::clone() const {
2822 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2825 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2826 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2827 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2828 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2829 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2830 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2831 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2832 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2833 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2834 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2835 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2836 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2837 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2838 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2839 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2840 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2841 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2842 CallInst *CallInst::clone() const { return new CallInst(*this); }
2843 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2844 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2846 ExtractElementInst *ExtractElementInst::clone() const {
2847 return new ExtractElementInst(*this);
2849 InsertElementInst *InsertElementInst::clone() const {
2850 return new InsertElementInst(*this);
2852 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2853 return new ShuffleVectorInst(*this);
2855 PHINode *PHINode::clone() const { return new PHINode(*this); }
2856 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2857 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2858 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2859 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2860 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2861 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2862 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }