1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/ParameterAttributes.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 unsigned CallSite::getCallingConv() const {
31 if (CallInst *CI = dyn_cast<CallInst>(I))
32 return CI->getCallingConv();
34 return cast<InvokeInst>(I)->getCallingConv();
36 void CallSite::setCallingConv(unsigned CC) {
37 if (CallInst *CI = dyn_cast<CallInst>(I))
38 CI->setCallingConv(CC);
40 cast<InvokeInst>(I)->setCallingConv(CC);
42 const ParamAttrsList* CallSite::getParamAttrs() const {
43 if (CallInst *CI = dyn_cast<CallInst>(I))
44 return CI->getParamAttrs();
46 return cast<InvokeInst>(I)->getParamAttrs();
48 void CallSite::setParamAttrs(const ParamAttrsList *PAL) {
49 if (CallInst *CI = dyn_cast<CallInst>(I))
50 CI->setParamAttrs(PAL);
52 cast<InvokeInst>(I)->setParamAttrs(PAL);
54 bool CallSite::paramHasAttr(uint16_t i, unsigned attr) const {
55 if (CallInst *CI = dyn_cast<CallInst>(I))
56 return CI->paramHasAttr(i, (ParameterAttributes)attr);
58 return cast<InvokeInst>(I)->paramHasAttr(i, (ParameterAttributes)attr);
60 bool CallSite::doesNotAccessMemory() const {
61 if (CallInst *CI = dyn_cast<CallInst>(I))
62 return CI->doesNotAccessMemory();
64 return cast<InvokeInst>(I)->doesNotAccessMemory();
66 bool CallSite::onlyReadsMemory() const {
67 if (CallInst *CI = dyn_cast<CallInst>(I))
68 return CI->onlyReadsMemory();
70 return cast<InvokeInst>(I)->onlyReadsMemory();
72 bool CallSite::doesNotThrow() const {
73 if (CallInst *CI = dyn_cast<CallInst>(I))
74 return CI->doesNotThrow();
76 return cast<InvokeInst>(I)->doesNotThrow();
78 void CallSite::setDoesNotThrow(bool doesNotThrow) {
79 if (CallInst *CI = dyn_cast<CallInst>(I))
80 CI->setDoesNotThrow(doesNotThrow);
82 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
85 //===----------------------------------------------------------------------===//
86 // TerminatorInst Class
87 //===----------------------------------------------------------------------===//
89 // Out of line virtual method, so the vtable, etc has a home.
90 TerminatorInst::~TerminatorInst() {
93 // Out of line virtual method, so the vtable, etc has a home.
94 UnaryInstruction::~UnaryInstruction() {
98 //===----------------------------------------------------------------------===//
100 //===----------------------------------------------------------------------===//
102 PHINode::PHINode(const PHINode &PN)
103 : Instruction(PN.getType(), Instruction::PHI,
104 new Use[PN.getNumOperands()], PN.getNumOperands()),
105 ReservedSpace(PN.getNumOperands()) {
106 Use *OL = OperandList;
107 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
108 OL[i].init(PN.getOperand(i), this);
109 OL[i+1].init(PN.getOperand(i+1), this);
113 PHINode::~PHINode() {
114 delete [] OperandList;
117 // removeIncomingValue - Remove an incoming value. This is useful if a
118 // predecessor basic block is deleted.
119 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
120 unsigned NumOps = getNumOperands();
121 Use *OL = OperandList;
122 assert(Idx*2 < NumOps && "BB not in PHI node!");
123 Value *Removed = OL[Idx*2];
125 // Move everything after this operand down.
127 // FIXME: we could just swap with the end of the list, then erase. However,
128 // client might not expect this to happen. The code as it is thrashes the
129 // use/def lists, which is kinda lame.
130 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
135 // Nuke the last value.
137 OL[NumOps-2+1].set(0);
138 NumOperands = NumOps-2;
140 // If the PHI node is dead, because it has zero entries, nuke it now.
141 if (NumOps == 2 && DeletePHIIfEmpty) {
142 // If anyone is using this PHI, make them use a dummy value instead...
143 replaceAllUsesWith(UndefValue::get(getType()));
149 /// resizeOperands - resize operands - This adjusts the length of the operands
150 /// list according to the following behavior:
151 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
152 /// of operation. This grows the number of ops by 1.5 times.
153 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
154 /// 3. If NumOps == NumOperands, trim the reserved space.
156 void PHINode::resizeOperands(unsigned NumOps) {
158 NumOps = (getNumOperands())*3/2;
159 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
160 } else if (NumOps*2 > NumOperands) {
162 if (ReservedSpace >= NumOps) return;
163 } else if (NumOps == NumOperands) {
164 if (ReservedSpace == NumOps) return;
169 ReservedSpace = NumOps;
170 Use *NewOps = new Use[NumOps];
171 Use *OldOps = OperandList;
172 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
173 NewOps[i].init(OldOps[i], this);
177 OperandList = NewOps;
180 /// hasConstantValue - If the specified PHI node always merges together the same
181 /// value, return the value, otherwise return null.
183 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
184 // If the PHI node only has one incoming value, eliminate the PHI node...
185 if (getNumIncomingValues() == 1)
186 if (getIncomingValue(0) != this) // not X = phi X
187 return getIncomingValue(0);
189 return UndefValue::get(getType()); // Self cycle is dead.
191 // Otherwise if all of the incoming values are the same for the PHI, replace
192 // the PHI node with the incoming value.
195 bool HasUndefInput = false;
196 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
197 if (isa<UndefValue>(getIncomingValue(i)))
198 HasUndefInput = true;
199 else if (getIncomingValue(i) != this) // Not the PHI node itself...
200 if (InVal && getIncomingValue(i) != InVal)
201 return 0; // Not the same, bail out.
203 InVal = getIncomingValue(i);
205 // The only case that could cause InVal to be null is if we have a PHI node
206 // that only has entries for itself. In this case, there is no entry into the
207 // loop, so kill the PHI.
209 if (InVal == 0) InVal = UndefValue::get(getType());
211 // If we have a PHI node like phi(X, undef, X), where X is defined by some
212 // instruction, we cannot always return X as the result of the PHI node. Only
213 // do this if X is not an instruction (thus it must dominate the PHI block),
214 // or if the client is prepared to deal with this possibility.
215 if (HasUndefInput && !AllowNonDominatingInstruction)
216 if (Instruction *IV = dyn_cast<Instruction>(InVal))
217 // If it's in the entry block, it dominates everything.
218 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
220 return 0; // Cannot guarantee that InVal dominates this PHINode.
222 // All of the incoming values are the same, return the value now.
227 //===----------------------------------------------------------------------===//
228 // CallInst Implementation
229 //===----------------------------------------------------------------------===//
231 CallInst::~CallInst() {
232 delete [] OperandList;
234 ParamAttrs->dropRef();
237 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
239 NumOperands = NumParams+1;
240 Use *OL = OperandList = new Use[NumParams+1];
241 OL[0].init(Func, this);
243 const FunctionType *FTy =
244 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
245 FTy = FTy; // silence warning.
247 assert((NumParams == FTy->getNumParams() ||
248 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
249 "Calling a function with bad signature!");
250 for (unsigned i = 0; i != NumParams; ++i) {
251 assert((i >= FTy->getNumParams() ||
252 FTy->getParamType(i) == Params[i]->getType()) &&
253 "Calling a function with a bad signature!");
254 OL[i+1].init(Params[i], this);
258 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
261 Use *OL = OperandList = new Use[3];
262 OL[0].init(Func, this);
263 OL[1].init(Actual1, this);
264 OL[2].init(Actual2, this);
266 const FunctionType *FTy =
267 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
268 FTy = FTy; // silence warning.
270 assert((FTy->getNumParams() == 2 ||
271 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
272 "Calling a function with bad signature");
273 assert((0 >= FTy->getNumParams() ||
274 FTy->getParamType(0) == Actual1->getType()) &&
275 "Calling a function with a bad signature!");
276 assert((1 >= FTy->getNumParams() ||
277 FTy->getParamType(1) == Actual2->getType()) &&
278 "Calling a function with a bad signature!");
281 void CallInst::init(Value *Func, Value *Actual) {
284 Use *OL = OperandList = new Use[2];
285 OL[0].init(Func, this);
286 OL[1].init(Actual, this);
288 const FunctionType *FTy =
289 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
290 FTy = FTy; // silence warning.
292 assert((FTy->getNumParams() == 1 ||
293 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
294 "Calling a function with bad signature");
295 assert((0 == FTy->getNumParams() ||
296 FTy->getParamType(0) == Actual->getType()) &&
297 "Calling a function with a bad signature!");
300 void CallInst::init(Value *Func) {
303 Use *OL = OperandList = new Use[1];
304 OL[0].init(Func, this);
306 const FunctionType *FTy =
307 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
308 FTy = FTy; // silence warning.
310 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
313 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
314 Instruction *InsertBefore)
315 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
316 ->getElementType())->getReturnType(),
317 Instruction::Call, 0, 0, InsertBefore) {
322 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
323 BasicBlock *InsertAtEnd)
324 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
325 ->getElementType())->getReturnType(),
326 Instruction::Call, 0, 0, InsertAtEnd) {
330 CallInst::CallInst(Value *Func, const std::string &Name,
331 Instruction *InsertBefore)
332 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
333 ->getElementType())->getReturnType(),
334 Instruction::Call, 0, 0, InsertBefore) {
339 CallInst::CallInst(Value *Func, const std::string &Name,
340 BasicBlock *InsertAtEnd)
341 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
342 ->getElementType())->getReturnType(),
343 Instruction::Call, 0, 0, InsertAtEnd) {
348 CallInst::CallInst(const CallInst &CI)
349 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
350 CI.getNumOperands()),
352 setParamAttrs(CI.getParamAttrs());
353 SubclassData = CI.SubclassData;
354 Use *OL = OperandList;
355 Use *InOL = CI.OperandList;
356 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
357 OL[i].init(InOL[i], this);
360 void CallInst::setParamAttrs(const ParamAttrsList *newAttrs) {
361 if (ParamAttrs == newAttrs)
365 ParamAttrs->dropRef();
370 ParamAttrs = newAttrs;
373 bool CallInst::paramHasAttr(uint16_t i, unsigned attr) const {
374 if (ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr))
376 if (const Function *F = getCalledFunction())
377 return F->paramHasAttr(i, (ParameterAttributes)attr);
381 /// @brief Determine if the call does not access memory.
382 bool CallInst::doesNotAccessMemory() const {
383 return paramHasAttr(0, ParamAttr::ReadNone);
386 /// @brief Determine if the call does not access or only reads memory.
387 bool CallInst::onlyReadsMemory() const {
388 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
391 /// @brief Determine if the call cannot return.
392 bool CallInst::doesNotReturn() const {
393 return paramHasAttr(0, ParamAttr::NoReturn);
396 /// @brief Determine if the call cannot unwind.
397 bool CallInst::doesNotThrow() const {
398 return paramHasAttr(0, ParamAttr::NoUnwind);
401 /// @brief Determine if the call returns a structure.
402 bool CallInst::isStructReturn() const {
403 // Be friendly and also check the callee.
404 return paramHasAttr(1, ParamAttr::StructRet);
407 /// @brief Determine if any call argument is an aggregate passed by value.
408 bool CallInst::hasByValArgument() const {
409 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
410 if (paramHasAttr(i, ParamAttr::ByVal))
415 void CallInst::setDoesNotThrow(bool doesNotThrow) {
416 const ParamAttrsList *PAL = getParamAttrs();
418 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
420 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
425 //===----------------------------------------------------------------------===//
426 // InvokeInst Implementation
427 //===----------------------------------------------------------------------===//
429 InvokeInst::~InvokeInst() {
430 delete [] OperandList;
432 ParamAttrs->dropRef();
435 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
436 Value* const *Args, unsigned NumArgs) {
438 NumOperands = 3+NumArgs;
439 Use *OL = OperandList = new Use[3+NumArgs];
440 OL[0].init(Fn, this);
441 OL[1].init(IfNormal, this);
442 OL[2].init(IfException, this);
443 const FunctionType *FTy =
444 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
445 FTy = FTy; // silence warning.
447 assert((NumArgs == FTy->getNumParams()) ||
448 (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
449 "Calling a function with bad signature");
451 for (unsigned i = 0, e = NumArgs; i != e; i++) {
452 assert((i >= FTy->getNumParams() ||
453 FTy->getParamType(i) == Args[i]->getType()) &&
454 "Invoking a function with a bad signature!");
456 OL[i+3].init(Args[i], this);
460 InvokeInst::InvokeInst(const InvokeInst &II)
461 : TerminatorInst(II.getType(), Instruction::Invoke,
462 new Use[II.getNumOperands()], II.getNumOperands()),
464 setParamAttrs(II.getParamAttrs());
465 SubclassData = II.SubclassData;
466 Use *OL = OperandList, *InOL = II.OperandList;
467 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
468 OL[i].init(InOL[i], this);
471 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
472 return getSuccessor(idx);
474 unsigned InvokeInst::getNumSuccessorsV() const {
475 return getNumSuccessors();
477 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
478 return setSuccessor(idx, B);
481 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
482 if (ParamAttrs == newAttrs)
486 ParamAttrs->dropRef();
491 ParamAttrs = newAttrs;
494 bool InvokeInst::paramHasAttr(uint16_t i, unsigned attr) const {
495 if (ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr))
497 if (const Function *F = getCalledFunction())
498 return F->paramHasAttr(i, (ParameterAttributes)attr);
503 /// @brief Determine if the call does not access memory.
504 bool InvokeInst::doesNotAccessMemory() const {
505 return paramHasAttr(0, ParamAttr::ReadNone);
508 /// @brief Determine if the call does not access or only reads memory.
509 bool InvokeInst::onlyReadsMemory() const {
510 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
513 /// @brief Determine if the call cannot return.
514 bool InvokeInst::doesNotReturn() const {
515 return paramHasAttr(0, ParamAttr::NoReturn);
518 /// @brief Determine if the call cannot unwind.
519 bool InvokeInst::doesNotThrow() const {
520 return paramHasAttr(0, ParamAttr::NoUnwind);
523 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
524 const ParamAttrsList *PAL = getParamAttrs();
526 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
528 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
532 /// @brief Determine if the call returns a structure.
533 bool InvokeInst::isStructReturn() const {
534 // Be friendly and also check the callee.
535 return paramHasAttr(1, ParamAttr::StructRet);
539 //===----------------------------------------------------------------------===//
540 // ReturnInst Implementation
541 //===----------------------------------------------------------------------===//
543 ReturnInst::ReturnInst(const ReturnInst &RI)
544 : TerminatorInst(Type::VoidTy, Instruction::Ret,
545 &RetVal, RI.getNumOperands()) {
546 if (RI.getNumOperands())
547 RetVal.init(RI.RetVal, this);
550 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
551 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
554 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
555 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
558 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
559 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
564 void ReturnInst::init(Value *retVal) {
565 if (retVal && retVal->getType() != Type::VoidTy) {
566 assert(!isa<BasicBlock>(retVal) &&
567 "Cannot return basic block. Probably using the incorrect ctor");
569 RetVal.init(retVal, this);
573 unsigned ReturnInst::getNumSuccessorsV() const {
574 return getNumSuccessors();
577 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
578 // emit the vtable for the class in this translation unit.
579 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
580 assert(0 && "ReturnInst has no successors!");
583 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
584 assert(0 && "ReturnInst has no successors!");
590 //===----------------------------------------------------------------------===//
591 // UnwindInst Implementation
592 //===----------------------------------------------------------------------===//
594 UnwindInst::UnwindInst(Instruction *InsertBefore)
595 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
597 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
598 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
602 unsigned UnwindInst::getNumSuccessorsV() const {
603 return getNumSuccessors();
606 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
607 assert(0 && "UnwindInst has no successors!");
610 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
611 assert(0 && "UnwindInst has no successors!");
616 //===----------------------------------------------------------------------===//
617 // UnreachableInst Implementation
618 //===----------------------------------------------------------------------===//
620 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
621 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
623 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
624 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
627 unsigned UnreachableInst::getNumSuccessorsV() const {
628 return getNumSuccessors();
631 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
632 assert(0 && "UnwindInst has no successors!");
635 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
636 assert(0 && "UnwindInst has no successors!");
641 //===----------------------------------------------------------------------===//
642 // BranchInst Implementation
643 //===----------------------------------------------------------------------===//
645 void BranchInst::AssertOK() {
647 assert(getCondition()->getType() == Type::Int1Ty &&
648 "May only branch on boolean predicates!");
651 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
652 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
653 assert(IfTrue != 0 && "Branch destination may not be null!");
654 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
656 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
657 Instruction *InsertBefore)
658 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
659 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
660 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
661 Ops[2].init(Cond, this);
667 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
668 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
669 assert(IfTrue != 0 && "Branch destination may not be null!");
670 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
673 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
674 BasicBlock *InsertAtEnd)
675 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
676 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
677 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
678 Ops[2].init(Cond, this);
685 BranchInst::BranchInst(const BranchInst &BI) :
686 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
687 OperandList[0].init(BI.getOperand(0), this);
688 if (BI.getNumOperands() != 1) {
689 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
690 OperandList[1].init(BI.getOperand(1), this);
691 OperandList[2].init(BI.getOperand(2), this);
695 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
696 return getSuccessor(idx);
698 unsigned BranchInst::getNumSuccessorsV() const {
699 return getNumSuccessors();
701 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
702 setSuccessor(idx, B);
706 //===----------------------------------------------------------------------===//
707 // AllocationInst Implementation
708 //===----------------------------------------------------------------------===//
710 static Value *getAISize(Value *Amt) {
712 Amt = ConstantInt::get(Type::Int32Ty, 1);
714 assert(!isa<BasicBlock>(Amt) &&
715 "Passed basic block into allocation size parameter! Use other ctor");
716 assert(Amt->getType() == Type::Int32Ty &&
717 "Malloc/Allocation array size is not a 32-bit integer!");
722 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
723 unsigned Align, const std::string &Name,
724 Instruction *InsertBefore)
725 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
726 InsertBefore), Alignment(Align) {
727 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
728 assert(Ty != Type::VoidTy && "Cannot allocate void!");
732 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
733 unsigned Align, const std::string &Name,
734 BasicBlock *InsertAtEnd)
735 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
736 InsertAtEnd), Alignment(Align) {
737 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
738 assert(Ty != Type::VoidTy && "Cannot allocate void!");
742 // Out of line virtual method, so the vtable, etc has a home.
743 AllocationInst::~AllocationInst() {
746 bool AllocationInst::isArrayAllocation() const {
747 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
748 return CI->getZExtValue() != 1;
752 const Type *AllocationInst::getAllocatedType() const {
753 return getType()->getElementType();
756 AllocaInst::AllocaInst(const AllocaInst &AI)
757 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
758 Instruction::Alloca, AI.getAlignment()) {
761 MallocInst::MallocInst(const MallocInst &MI)
762 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
763 Instruction::Malloc, MI.getAlignment()) {
766 //===----------------------------------------------------------------------===//
767 // FreeInst Implementation
768 //===----------------------------------------------------------------------===//
770 void FreeInst::AssertOK() {
771 assert(isa<PointerType>(getOperand(0)->getType()) &&
772 "Can not free something of nonpointer type!");
775 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
776 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
780 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
781 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
786 //===----------------------------------------------------------------------===//
787 // LoadInst Implementation
788 //===----------------------------------------------------------------------===//
790 void LoadInst::AssertOK() {
791 assert(isa<PointerType>(getOperand(0)->getType()) &&
792 "Ptr must have pointer type.");
795 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
796 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
797 Load, Ptr, InsertBef) {
804 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
805 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
806 Load, Ptr, InsertAE) {
813 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
814 Instruction *InsertBef)
815 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
816 Load, Ptr, InsertBef) {
817 setVolatile(isVolatile);
823 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
824 unsigned Align, Instruction *InsertBef)
825 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
826 Load, Ptr, InsertBef) {
827 setVolatile(isVolatile);
833 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
834 unsigned Align, BasicBlock *InsertAE)
835 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
836 Load, Ptr, InsertAE) {
837 setVolatile(isVolatile);
843 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
844 BasicBlock *InsertAE)
845 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
846 Load, Ptr, InsertAE) {
847 setVolatile(isVolatile);
855 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
856 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
857 Load, Ptr, InsertBef) {
861 if (Name && Name[0]) setName(Name);
864 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
865 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
866 Load, Ptr, InsertAE) {
870 if (Name && Name[0]) setName(Name);
873 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
874 Instruction *InsertBef)
875 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
876 Load, Ptr, InsertBef) {
877 setVolatile(isVolatile);
880 if (Name && Name[0]) setName(Name);
883 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
884 BasicBlock *InsertAE)
885 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
886 Load, Ptr, InsertAE) {
887 setVolatile(isVolatile);
890 if (Name && Name[0]) setName(Name);
893 void LoadInst::setAlignment(unsigned Align) {
894 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
895 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
898 //===----------------------------------------------------------------------===//
899 // StoreInst Implementation
900 //===----------------------------------------------------------------------===//
902 void StoreInst::AssertOK() {
903 assert(isa<PointerType>(getOperand(1)->getType()) &&
904 "Ptr must have pointer type!");
905 assert(getOperand(0)->getType() ==
906 cast<PointerType>(getOperand(1)->getType())->getElementType()
907 && "Ptr must be a pointer to Val type!");
911 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
912 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
913 Ops[0].init(val, this);
914 Ops[1].init(addr, this);
920 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
921 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
922 Ops[0].init(val, this);
923 Ops[1].init(addr, this);
929 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
930 Instruction *InsertBefore)
931 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
932 Ops[0].init(val, this);
933 Ops[1].init(addr, this);
934 setVolatile(isVolatile);
939 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
940 unsigned Align, Instruction *InsertBefore)
941 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
942 Ops[0].init(val, this);
943 Ops[1].init(addr, this);
944 setVolatile(isVolatile);
949 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
950 unsigned Align, BasicBlock *InsertAtEnd)
951 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
952 Ops[0].init(val, this);
953 Ops[1].init(addr, this);
954 setVolatile(isVolatile);
959 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
960 BasicBlock *InsertAtEnd)
961 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
962 Ops[0].init(val, this);
963 Ops[1].init(addr, this);
964 setVolatile(isVolatile);
969 void StoreInst::setAlignment(unsigned Align) {
970 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
971 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
974 //===----------------------------------------------------------------------===//
975 // GetElementPtrInst Implementation
976 //===----------------------------------------------------------------------===//
978 static unsigned retrieveAddrSpace(const Value *Val) {
979 return cast<PointerType>(Val->getType())->getAddressSpace();
982 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
983 NumOperands = 1+NumIdx;
984 Use *OL = OperandList = new Use[NumOperands];
985 OL[0].init(Ptr, this);
987 for (unsigned i = 0; i != NumIdx; ++i)
988 OL[i+1].init(Idx[i], this);
991 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
993 Use *OL = OperandList = new Use[2];
994 OL[0].init(Ptr, this);
995 OL[1].init(Idx, this);
998 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
999 const std::string &Name, Instruction *InBe)
1000 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1001 retrieveAddrSpace(Ptr)),
1002 GetElementPtr, 0, 0, InBe) {
1007 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1008 const std::string &Name, BasicBlock *IAE)
1009 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1010 retrieveAddrSpace(Ptr)),
1011 GetElementPtr, 0, 0, IAE) {
1016 GetElementPtrInst::~GetElementPtrInst() {
1017 delete[] OperandList;
1020 // getIndexedType - Returns the type of the element that would be loaded with
1021 // a load instruction with the specified parameters.
1023 // A null type is returned if the indices are invalid for the specified
1026 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1029 bool AllowCompositeLeaf) {
1030 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
1032 // Handle the special case of the empty set index set...
1034 if (AllowCompositeLeaf ||
1035 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
1036 return cast<PointerType>(Ptr)->getElementType();
1040 unsigned CurIdx = 0;
1041 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1042 if (NumIdx == CurIdx) {
1043 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1044 return 0; // Can't load a whole structure or array!?!?
1047 Value *Index = Idxs[CurIdx++];
1048 if (isa<PointerType>(CT) && CurIdx != 1)
1049 return 0; // Can only index into pointer types at the first index!
1050 if (!CT->indexValid(Index)) return 0;
1051 Ptr = CT->getTypeAtIndex(Index);
1053 // If the new type forwards to another type, then it is in the middle
1054 // of being refined to another type (and hence, may have dropped all
1055 // references to what it was using before). So, use the new forwarded
1057 if (const Type * Ty = Ptr->getForwardedType()) {
1061 return CurIdx == NumIdx ? Ptr : 0;
1064 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1065 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1066 if (!PTy) return 0; // Type isn't a pointer type!
1068 // Check the pointer index.
1069 if (!PTy->indexValid(Idx)) return 0;
1071 return PTy->getElementType();
1075 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1076 /// zeros. If so, the result pointer and the first operand have the same
1077 /// value, just potentially different types.
1078 bool GetElementPtrInst::hasAllZeroIndices() const {
1079 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1080 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1081 if (!CI->isZero()) return false;
1089 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1090 /// constant integers. If so, the result pointer and the first operand have
1091 /// a constant offset between them.
1092 bool GetElementPtrInst::hasAllConstantIndices() const {
1093 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1094 if (!isa<ConstantInt>(getOperand(i)))
1101 //===----------------------------------------------------------------------===//
1102 // ExtractElementInst Implementation
1103 //===----------------------------------------------------------------------===//
1105 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1106 const std::string &Name,
1107 Instruction *InsertBef)
1108 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1109 ExtractElement, Ops, 2, InsertBef) {
1110 assert(isValidOperands(Val, Index) &&
1111 "Invalid extractelement instruction operands!");
1112 Ops[0].init(Val, this);
1113 Ops[1].init(Index, this);
1117 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1118 const std::string &Name,
1119 Instruction *InsertBef)
1120 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1121 ExtractElement, Ops, 2, InsertBef) {
1122 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1123 assert(isValidOperands(Val, Index) &&
1124 "Invalid extractelement instruction operands!");
1125 Ops[0].init(Val, this);
1126 Ops[1].init(Index, this);
1131 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1132 const std::string &Name,
1133 BasicBlock *InsertAE)
1134 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1135 ExtractElement, Ops, 2, InsertAE) {
1136 assert(isValidOperands(Val, Index) &&
1137 "Invalid extractelement instruction operands!");
1139 Ops[0].init(Val, this);
1140 Ops[1].init(Index, this);
1144 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1145 const std::string &Name,
1146 BasicBlock *InsertAE)
1147 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1148 ExtractElement, Ops, 2, InsertAE) {
1149 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1150 assert(isValidOperands(Val, Index) &&
1151 "Invalid extractelement instruction operands!");
1153 Ops[0].init(Val, this);
1154 Ops[1].init(Index, this);
1159 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1160 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1166 //===----------------------------------------------------------------------===//
1167 // InsertElementInst Implementation
1168 //===----------------------------------------------------------------------===//
1170 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1171 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1172 Ops[0].init(IE.Ops[0], this);
1173 Ops[1].init(IE.Ops[1], this);
1174 Ops[2].init(IE.Ops[2], this);
1176 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1177 const std::string &Name,
1178 Instruction *InsertBef)
1179 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1180 assert(isValidOperands(Vec, Elt, Index) &&
1181 "Invalid insertelement instruction operands!");
1182 Ops[0].init(Vec, this);
1183 Ops[1].init(Elt, this);
1184 Ops[2].init(Index, this);
1188 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1189 const std::string &Name,
1190 Instruction *InsertBef)
1191 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1192 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1193 assert(isValidOperands(Vec, Elt, Index) &&
1194 "Invalid insertelement instruction operands!");
1195 Ops[0].init(Vec, this);
1196 Ops[1].init(Elt, this);
1197 Ops[2].init(Index, this);
1202 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1203 const std::string &Name,
1204 BasicBlock *InsertAE)
1205 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1206 assert(isValidOperands(Vec, Elt, Index) &&
1207 "Invalid insertelement instruction operands!");
1209 Ops[0].init(Vec, this);
1210 Ops[1].init(Elt, this);
1211 Ops[2].init(Index, this);
1215 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1216 const std::string &Name,
1217 BasicBlock *InsertAE)
1218 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1219 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1220 assert(isValidOperands(Vec, Elt, Index) &&
1221 "Invalid insertelement instruction operands!");
1223 Ops[0].init(Vec, this);
1224 Ops[1].init(Elt, this);
1225 Ops[2].init(Index, this);
1229 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1230 const Value *Index) {
1231 if (!isa<VectorType>(Vec->getType()))
1232 return false; // First operand of insertelement must be vector type.
1234 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1235 return false;// Second operand of insertelement must be vector element type.
1237 if (Index->getType() != Type::Int32Ty)
1238 return false; // Third operand of insertelement must be uint.
1243 //===----------------------------------------------------------------------===//
1244 // ShuffleVectorInst Implementation
1245 //===----------------------------------------------------------------------===//
1247 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1248 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1249 Ops[0].init(SV.Ops[0], this);
1250 Ops[1].init(SV.Ops[1], this);
1251 Ops[2].init(SV.Ops[2], this);
1254 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1255 const std::string &Name,
1256 Instruction *InsertBefore)
1257 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1258 assert(isValidOperands(V1, V2, Mask) &&
1259 "Invalid shuffle vector instruction operands!");
1260 Ops[0].init(V1, this);
1261 Ops[1].init(V2, this);
1262 Ops[2].init(Mask, this);
1266 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1267 const std::string &Name,
1268 BasicBlock *InsertAtEnd)
1269 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1270 assert(isValidOperands(V1, V2, Mask) &&
1271 "Invalid shuffle vector instruction operands!");
1273 Ops[0].init(V1, this);
1274 Ops[1].init(V2, this);
1275 Ops[2].init(Mask, this);
1279 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1280 const Value *Mask) {
1281 if (!isa<VectorType>(V1->getType())) return false;
1282 if (V1->getType() != V2->getType()) return false;
1283 if (!isa<VectorType>(Mask->getType()) ||
1284 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1285 cast<VectorType>(Mask->getType())->getNumElements() !=
1286 cast<VectorType>(V1->getType())->getNumElements())
1292 //===----------------------------------------------------------------------===//
1293 // BinaryOperator Class
1294 //===----------------------------------------------------------------------===//
1296 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1297 const Type *Ty, const std::string &Name,
1298 Instruction *InsertBefore)
1299 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1300 Ops[0].init(S1, this);
1301 Ops[1].init(S2, this);
1306 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1307 const Type *Ty, const std::string &Name,
1308 BasicBlock *InsertAtEnd)
1309 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1310 Ops[0].init(S1, this);
1311 Ops[1].init(S2, this);
1317 void BinaryOperator::init(BinaryOps iType) {
1318 Value *LHS = getOperand(0), *RHS = getOperand(1);
1319 LHS = LHS; RHS = RHS; // Silence warnings.
1320 assert(LHS->getType() == RHS->getType() &&
1321 "Binary operator operand types must match!");
1326 assert(getType() == LHS->getType() &&
1327 "Arithmetic operation should return same type as operands!");
1328 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1329 isa<VectorType>(getType())) &&
1330 "Tried to create an arithmetic operation on a non-arithmetic type!");
1334 assert(getType() == LHS->getType() &&
1335 "Arithmetic operation should return same type as operands!");
1336 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1337 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1338 "Incorrect operand type (not integer) for S/UDIV");
1341 assert(getType() == LHS->getType() &&
1342 "Arithmetic operation should return same type as operands!");
1343 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1344 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1345 && "Incorrect operand type (not floating point) for FDIV");
1349 assert(getType() == LHS->getType() &&
1350 "Arithmetic operation should return same type as operands!");
1351 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1352 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1353 "Incorrect operand type (not integer) for S/UREM");
1356 assert(getType() == LHS->getType() &&
1357 "Arithmetic operation should return same type as operands!");
1358 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1359 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1360 && "Incorrect operand type (not floating point) for FREM");
1365 assert(getType() == LHS->getType() &&
1366 "Shift operation should return same type as operands!");
1367 assert(getType()->isInteger() &&
1368 "Shift operation requires integer operands");
1372 assert(getType() == LHS->getType() &&
1373 "Logical operation should return same type as operands!");
1374 assert((getType()->isInteger() ||
1375 (isa<VectorType>(getType()) &&
1376 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1377 "Tried to create a logical operation on a non-integral type!");
1385 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1386 const std::string &Name,
1387 Instruction *InsertBefore) {
1388 assert(S1->getType() == S2->getType() &&
1389 "Cannot create binary operator with two operands of differing type!");
1390 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1393 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1394 const std::string &Name,
1395 BasicBlock *InsertAtEnd) {
1396 BinaryOperator *Res = create(Op, S1, S2, Name);
1397 InsertAtEnd->getInstList().push_back(Res);
1401 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1402 Instruction *InsertBefore) {
1403 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1404 return new BinaryOperator(Instruction::Sub,
1406 Op->getType(), Name, InsertBefore);
1409 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1410 BasicBlock *InsertAtEnd) {
1411 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1412 return new BinaryOperator(Instruction::Sub,
1414 Op->getType(), Name, InsertAtEnd);
1417 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1418 Instruction *InsertBefore) {
1420 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1421 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1422 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1424 C = ConstantInt::getAllOnesValue(Op->getType());
1427 return new BinaryOperator(Instruction::Xor, Op, C,
1428 Op->getType(), Name, InsertBefore);
1431 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1432 BasicBlock *InsertAtEnd) {
1434 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1435 // Create a vector of all ones values.
1436 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1438 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1440 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1443 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1444 Op->getType(), Name, InsertAtEnd);
1448 // isConstantAllOnes - Helper function for several functions below
1449 static inline bool isConstantAllOnes(const Value *V) {
1450 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1451 return CI->isAllOnesValue();
1452 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1453 return CV->isAllOnesValue();
1457 bool BinaryOperator::isNeg(const Value *V) {
1458 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1459 if (Bop->getOpcode() == Instruction::Sub)
1460 return Bop->getOperand(0) ==
1461 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1465 bool BinaryOperator::isNot(const Value *V) {
1466 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1467 return (Bop->getOpcode() == Instruction::Xor &&
1468 (isConstantAllOnes(Bop->getOperand(1)) ||
1469 isConstantAllOnes(Bop->getOperand(0))));
1473 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1474 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1475 return cast<BinaryOperator>(BinOp)->getOperand(1);
1478 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1479 return getNegArgument(const_cast<Value*>(BinOp));
1482 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1483 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1484 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1485 Value *Op0 = BO->getOperand(0);
1486 Value *Op1 = BO->getOperand(1);
1487 if (isConstantAllOnes(Op0)) return Op1;
1489 assert(isConstantAllOnes(Op1));
1493 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1494 return getNotArgument(const_cast<Value*>(BinOp));
1498 // swapOperands - Exchange the two operands to this instruction. This
1499 // instruction is safe to use on any binary instruction and does not
1500 // modify the semantics of the instruction. If the instruction is
1501 // order dependent (SetLT f.e.) the opcode is changed.
1503 bool BinaryOperator::swapOperands() {
1504 if (!isCommutative())
1505 return true; // Can't commute operands
1506 std::swap(Ops[0], Ops[1]);
1510 //===----------------------------------------------------------------------===//
1512 //===----------------------------------------------------------------------===//
1514 // Just determine if this cast only deals with integral->integral conversion.
1515 bool CastInst::isIntegerCast() const {
1516 switch (getOpcode()) {
1517 default: return false;
1518 case Instruction::ZExt:
1519 case Instruction::SExt:
1520 case Instruction::Trunc:
1522 case Instruction::BitCast:
1523 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1527 bool CastInst::isLosslessCast() const {
1528 // Only BitCast can be lossless, exit fast if we're not BitCast
1529 if (getOpcode() != Instruction::BitCast)
1532 // Identity cast is always lossless
1533 const Type* SrcTy = getOperand(0)->getType();
1534 const Type* DstTy = getType();
1538 // Pointer to pointer is always lossless.
1539 if (isa<PointerType>(SrcTy))
1540 return isa<PointerType>(DstTy);
1541 return false; // Other types have no identity values
1544 /// This function determines if the CastInst does not require any bits to be
1545 /// changed in order to effect the cast. Essentially, it identifies cases where
1546 /// no code gen is necessary for the cast, hence the name no-op cast. For
1547 /// example, the following are all no-op casts:
1548 /// # bitcast uint %X, int
1549 /// # bitcast uint* %x, sbyte*
1550 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1551 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1552 /// @brief Determine if a cast is a no-op.
1553 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1554 switch (getOpcode()) {
1556 assert(!"Invalid CastOp");
1557 case Instruction::Trunc:
1558 case Instruction::ZExt:
1559 case Instruction::SExt:
1560 case Instruction::FPTrunc:
1561 case Instruction::FPExt:
1562 case Instruction::UIToFP:
1563 case Instruction::SIToFP:
1564 case Instruction::FPToUI:
1565 case Instruction::FPToSI:
1566 return false; // These always modify bits
1567 case Instruction::BitCast:
1568 return true; // BitCast never modifies bits.
1569 case Instruction::PtrToInt:
1570 return IntPtrTy->getPrimitiveSizeInBits() ==
1571 getType()->getPrimitiveSizeInBits();
1572 case Instruction::IntToPtr:
1573 return IntPtrTy->getPrimitiveSizeInBits() ==
1574 getOperand(0)->getType()->getPrimitiveSizeInBits();
1578 /// This function determines if a pair of casts can be eliminated and what
1579 /// opcode should be used in the elimination. This assumes that there are two
1580 /// instructions like this:
1581 /// * %F = firstOpcode SrcTy %x to MidTy
1582 /// * %S = secondOpcode MidTy %F to DstTy
1583 /// The function returns a resultOpcode so these two casts can be replaced with:
1584 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1585 /// If no such cast is permited, the function returns 0.
1586 unsigned CastInst::isEliminableCastPair(
1587 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1588 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1590 // Define the 144 possibilities for these two cast instructions. The values
1591 // in this matrix determine what to do in a given situation and select the
1592 // case in the switch below. The rows correspond to firstOp, the columns
1593 // correspond to secondOp. In looking at the table below, keep in mind
1594 // the following cast properties:
1596 // Size Compare Source Destination
1597 // Operator Src ? Size Type Sign Type Sign
1598 // -------- ------------ ------------------- ---------------------
1599 // TRUNC > Integer Any Integral Any
1600 // ZEXT < Integral Unsigned Integer Any
1601 // SEXT < Integral Signed Integer Any
1602 // FPTOUI n/a FloatPt n/a Integral Unsigned
1603 // FPTOSI n/a FloatPt n/a Integral Signed
1604 // UITOFP n/a Integral Unsigned FloatPt n/a
1605 // SITOFP n/a Integral Signed FloatPt n/a
1606 // FPTRUNC > FloatPt n/a FloatPt n/a
1607 // FPEXT < FloatPt n/a FloatPt n/a
1608 // PTRTOINT n/a Pointer n/a Integral Unsigned
1609 // INTTOPTR n/a Integral Unsigned Pointer n/a
1610 // BITCONVERT = FirstClass n/a FirstClass n/a
1612 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1613 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1614 // into "fptoui double to ulong", but this loses information about the range
1615 // of the produced value (we no longer know the top-part is all zeros).
1616 // Further this conversion is often much more expensive for typical hardware,
1617 // and causes issues when building libgcc. We disallow fptosi+sext for the
1619 const unsigned numCastOps =
1620 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1621 static const uint8_t CastResults[numCastOps][numCastOps] = {
1622 // T F F U S F F P I B -+
1623 // R Z S P P I I T P 2 N T |
1624 // U E E 2 2 2 2 R E I T C +- secondOp
1625 // N X X U S F F N X N 2 V |
1626 // C T T I I P P C T T P T -+
1627 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1628 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1629 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1630 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1631 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1632 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1633 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1634 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1635 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1636 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1637 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1638 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1641 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1642 [secondOp-Instruction::CastOpsBegin];
1645 // categorically disallowed
1648 // allowed, use first cast's opcode
1651 // allowed, use second cast's opcode
1654 // no-op cast in second op implies firstOp as long as the DestTy
1656 if (DstTy->isInteger())
1660 // no-op cast in second op implies firstOp as long as the DestTy
1661 // is floating point
1662 if (DstTy->isFloatingPoint())
1666 // no-op cast in first op implies secondOp as long as the SrcTy
1668 if (SrcTy->isInteger())
1672 // no-op cast in first op implies secondOp as long as the SrcTy
1673 // is a floating point
1674 if (SrcTy->isFloatingPoint())
1678 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1679 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1680 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1681 if (MidSize >= PtrSize)
1682 return Instruction::BitCast;
1686 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1687 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1688 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1689 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1690 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1691 if (SrcSize == DstSize)
1692 return Instruction::BitCast;
1693 else if (SrcSize < DstSize)
1697 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1698 return Instruction::ZExt;
1700 // fpext followed by ftrunc is allowed if the bit size returned to is
1701 // the same as the original, in which case its just a bitcast
1703 return Instruction::BitCast;
1704 return 0; // If the types are not the same we can't eliminate it.
1706 // bitcast followed by ptrtoint is allowed as long as the bitcast
1707 // is a pointer to pointer cast.
1708 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1712 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1713 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1717 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1718 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1719 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1720 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1721 if (SrcSize <= PtrSize && SrcSize == DstSize)
1722 return Instruction::BitCast;
1726 // cast combination can't happen (error in input). This is for all cases
1727 // where the MidTy is not the same for the two cast instructions.
1728 assert(!"Invalid Cast Combination");
1731 assert(!"Error in CastResults table!!!");
1737 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1738 const std::string &Name, Instruction *InsertBefore) {
1739 // Construct and return the appropriate CastInst subclass
1741 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1742 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1743 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1744 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1745 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1746 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1747 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1748 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1749 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1750 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1751 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1752 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1754 assert(!"Invalid opcode provided");
1759 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1760 const std::string &Name, BasicBlock *InsertAtEnd) {
1761 // Construct and return the appropriate CastInst subclass
1763 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1764 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1765 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1766 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1767 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1768 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1769 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1770 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1771 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1772 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1773 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1774 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1776 assert(!"Invalid opcode provided");
1781 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1782 const std::string &Name,
1783 Instruction *InsertBefore) {
1784 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1785 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1786 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1789 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1790 const std::string &Name,
1791 BasicBlock *InsertAtEnd) {
1792 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1793 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1794 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1797 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1798 const std::string &Name,
1799 Instruction *InsertBefore) {
1800 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1801 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1802 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1805 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1806 const std::string &Name,
1807 BasicBlock *InsertAtEnd) {
1808 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1809 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1810 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1813 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1814 const std::string &Name,
1815 Instruction *InsertBefore) {
1816 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1817 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1818 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1821 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1822 const std::string &Name,
1823 BasicBlock *InsertAtEnd) {
1824 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1825 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1826 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1829 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1830 const std::string &Name,
1831 BasicBlock *InsertAtEnd) {
1832 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1833 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1836 if (Ty->isInteger())
1837 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1838 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1841 /// @brief Create a BitCast or a PtrToInt cast instruction
1842 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1843 const std::string &Name,
1844 Instruction *InsertBefore) {
1845 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1846 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1849 if (Ty->isInteger())
1850 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1851 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1854 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1855 bool isSigned, const std::string &Name,
1856 Instruction *InsertBefore) {
1857 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1858 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1859 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1860 Instruction::CastOps opcode =
1861 (SrcBits == DstBits ? Instruction::BitCast :
1862 (SrcBits > DstBits ? Instruction::Trunc :
1863 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1864 return create(opcode, C, Ty, Name, InsertBefore);
1867 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1868 bool isSigned, const std::string &Name,
1869 BasicBlock *InsertAtEnd) {
1870 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1871 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1872 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1873 Instruction::CastOps opcode =
1874 (SrcBits == DstBits ? Instruction::BitCast :
1875 (SrcBits > DstBits ? Instruction::Trunc :
1876 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1877 return create(opcode, C, Ty, Name, InsertAtEnd);
1880 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1881 const std::string &Name,
1882 Instruction *InsertBefore) {
1883 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1885 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1886 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1887 Instruction::CastOps opcode =
1888 (SrcBits == DstBits ? Instruction::BitCast :
1889 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1890 return create(opcode, C, Ty, Name, InsertBefore);
1893 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1894 const std::string &Name,
1895 BasicBlock *InsertAtEnd) {
1896 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1898 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1899 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1900 Instruction::CastOps opcode =
1901 (SrcBits == DstBits ? Instruction::BitCast :
1902 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1903 return create(opcode, C, Ty, Name, InsertAtEnd);
1906 // Check whether it is valid to call getCastOpcode for these types.
1907 // This routine must be kept in sync with getCastOpcode.
1908 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1909 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1912 if (SrcTy == DestTy)
1915 // Get the bit sizes, we'll need these
1916 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1917 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1919 // Run through the possibilities ...
1920 if (DestTy->isInteger()) { // Casting to integral
1921 if (SrcTy->isInteger()) { // Casting from integral
1923 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1925 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1926 // Casting from vector
1927 return DestBits == PTy->getBitWidth();
1928 } else { // Casting from something else
1929 return isa<PointerType>(SrcTy);
1931 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1932 if (SrcTy->isInteger()) { // Casting from integral
1934 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1936 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1937 // Casting from vector
1938 return DestBits == PTy->getBitWidth();
1939 } else { // Casting from something else
1942 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1943 // Casting to vector
1944 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1945 // Casting from vector
1946 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
1947 } else { // Casting from something else
1948 return DestPTy->getBitWidth() == SrcBits;
1950 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
1951 if (isa<PointerType>(SrcTy)) { // Casting from pointer
1953 } else if (SrcTy->isInteger()) { // Casting from integral
1955 } else { // Casting from something else
1958 } else { // Casting to something else
1963 // Provide a way to get a "cast" where the cast opcode is inferred from the
1964 // types and size of the operand. This, basically, is a parallel of the
1965 // logic in the castIsValid function below. This axiom should hold:
1966 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1967 // should not assert in castIsValid. In other words, this produces a "correct"
1968 // casting opcode for the arguments passed to it.
1969 // This routine must be kept in sync with isCastable.
1970 Instruction::CastOps
1971 CastInst::getCastOpcode(
1972 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1973 // Get the bit sizes, we'll need these
1974 const Type *SrcTy = Src->getType();
1975 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1976 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1978 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
1979 "Only first class types are castable!");
1981 // Run through the possibilities ...
1982 if (DestTy->isInteger()) { // Casting to integral
1983 if (SrcTy->isInteger()) { // Casting from integral
1984 if (DestBits < SrcBits)
1985 return Trunc; // int -> smaller int
1986 else if (DestBits > SrcBits) { // its an extension
1988 return SExt; // signed -> SEXT
1990 return ZExt; // unsigned -> ZEXT
1992 return BitCast; // Same size, No-op cast
1994 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1996 return FPToSI; // FP -> sint
1998 return FPToUI; // FP -> uint
1999 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2000 assert(DestBits == PTy->getBitWidth() &&
2001 "Casting vector to integer of different width");
2002 return BitCast; // Same size, no-op cast
2004 assert(isa<PointerType>(SrcTy) &&
2005 "Casting from a value that is not first-class type");
2006 return PtrToInt; // ptr -> int
2008 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2009 if (SrcTy->isInteger()) { // Casting from integral
2011 return SIToFP; // sint -> FP
2013 return UIToFP; // uint -> FP
2014 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2015 if (DestBits < SrcBits) {
2016 return FPTrunc; // FP -> smaller FP
2017 } else if (DestBits > SrcBits) {
2018 return FPExt; // FP -> larger FP
2020 return BitCast; // same size, no-op cast
2022 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2023 assert(DestBits == PTy->getBitWidth() &&
2024 "Casting vector to floating point of different width");
2025 return BitCast; // same size, no-op cast
2027 assert(0 && "Casting pointer or non-first class to float");
2029 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2030 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2031 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2032 "Casting vector to vector of different widths");
2033 return BitCast; // vector -> vector
2034 } else if (DestPTy->getBitWidth() == SrcBits) {
2035 return BitCast; // float/int -> vector
2037 assert(!"Illegal cast to vector (wrong type or size)");
2039 } else if (isa<PointerType>(DestTy)) {
2040 if (isa<PointerType>(SrcTy)) {
2041 return BitCast; // ptr -> ptr
2042 } else if (SrcTy->isInteger()) {
2043 return IntToPtr; // int -> ptr
2045 assert(!"Casting pointer to other than pointer or int");
2048 assert(!"Casting to type that is not first-class");
2051 // If we fall through to here we probably hit an assertion cast above
2052 // and assertions are not turned on. Anything we return is an error, so
2053 // BitCast is as good a choice as any.
2057 //===----------------------------------------------------------------------===//
2058 // CastInst SubClass Constructors
2059 //===----------------------------------------------------------------------===//
2061 /// Check that the construction parameters for a CastInst are correct. This
2062 /// could be broken out into the separate constructors but it is useful to have
2063 /// it in one place and to eliminate the redundant code for getting the sizes
2064 /// of the types involved.
2066 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2068 // Check for type sanity on the arguments
2069 const Type *SrcTy = S->getType();
2070 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2073 // Get the size of the types in bits, we'll need this later
2074 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2075 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2077 // Switch on the opcode provided
2079 default: return false; // This is an input error
2080 case Instruction::Trunc:
2081 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2082 case Instruction::ZExt:
2083 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2084 case Instruction::SExt:
2085 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2086 case Instruction::FPTrunc:
2087 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2088 SrcBitSize > DstBitSize;
2089 case Instruction::FPExt:
2090 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2091 SrcBitSize < DstBitSize;
2092 case Instruction::UIToFP:
2093 case Instruction::SIToFP:
2094 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2095 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2096 return SVTy->getElementType()->isInteger() &&
2097 DVTy->getElementType()->isFloatingPoint() &&
2098 SVTy->getNumElements() == DVTy->getNumElements();
2101 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2102 case Instruction::FPToUI:
2103 case Instruction::FPToSI:
2104 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2105 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2106 return SVTy->getElementType()->isFloatingPoint() &&
2107 DVTy->getElementType()->isInteger() &&
2108 SVTy->getNumElements() == DVTy->getNumElements();
2111 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2112 case Instruction::PtrToInt:
2113 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2114 case Instruction::IntToPtr:
2115 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2116 case Instruction::BitCast:
2117 // BitCast implies a no-op cast of type only. No bits change.
2118 // However, you can't cast pointers to anything but pointers.
2119 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2122 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2123 // these cases, the cast is okay if the source and destination bit widths
2125 return SrcBitSize == DstBitSize;
2129 TruncInst::TruncInst(
2130 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2131 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2132 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2135 TruncInst::TruncInst(
2136 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2137 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2138 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2142 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2143 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2144 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2148 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2149 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2150 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2153 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2154 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2155 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2159 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2160 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2161 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2164 FPTruncInst::FPTruncInst(
2165 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2166 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2167 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2170 FPTruncInst::FPTruncInst(
2171 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2172 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2173 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2176 FPExtInst::FPExtInst(
2177 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2178 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2179 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2182 FPExtInst::FPExtInst(
2183 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2184 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2185 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2188 UIToFPInst::UIToFPInst(
2189 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2190 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2191 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2194 UIToFPInst::UIToFPInst(
2195 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2196 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2197 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2200 SIToFPInst::SIToFPInst(
2201 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2202 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2203 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2206 SIToFPInst::SIToFPInst(
2207 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2208 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2209 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2212 FPToUIInst::FPToUIInst(
2213 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2214 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2215 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2218 FPToUIInst::FPToUIInst(
2219 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2220 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2221 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2224 FPToSIInst::FPToSIInst(
2225 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2226 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2227 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2230 FPToSIInst::FPToSIInst(
2231 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2232 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2233 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2236 PtrToIntInst::PtrToIntInst(
2237 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2238 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2239 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2242 PtrToIntInst::PtrToIntInst(
2243 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2244 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2245 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2248 IntToPtrInst::IntToPtrInst(
2249 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2250 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2251 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2254 IntToPtrInst::IntToPtrInst(
2255 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2256 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2257 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2260 BitCastInst::BitCastInst(
2261 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2262 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2263 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2266 BitCastInst::BitCastInst(
2267 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2268 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2269 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2272 //===----------------------------------------------------------------------===//
2274 //===----------------------------------------------------------------------===//
2276 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2277 const std::string &Name, Instruction *InsertBefore)
2278 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2279 Ops[0].init(LHS, this);
2280 Ops[1].init(RHS, this);
2281 SubclassData = predicate;
2283 if (op == Instruction::ICmp) {
2284 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2285 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2286 "Invalid ICmp predicate value");
2287 const Type* Op0Ty = getOperand(0)->getType();
2288 const Type* Op1Ty = getOperand(1)->getType();
2289 assert(Op0Ty == Op1Ty &&
2290 "Both operands to ICmp instruction are not of the same type!");
2291 // Check that the operands are the right type
2292 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2293 "Invalid operand types for ICmp instruction");
2296 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2297 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2298 "Invalid FCmp predicate value");
2299 const Type* Op0Ty = getOperand(0)->getType();
2300 const Type* Op1Ty = getOperand(1)->getType();
2301 assert(Op0Ty == Op1Ty &&
2302 "Both operands to FCmp instruction are not of the same type!");
2303 // Check that the operands are the right type
2304 assert(Op0Ty->isFloatingPoint() &&
2305 "Invalid operand types for FCmp instruction");
2308 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2309 const std::string &Name, BasicBlock *InsertAtEnd)
2310 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2311 Ops[0].init(LHS, this);
2312 Ops[1].init(RHS, this);
2313 SubclassData = predicate;
2315 if (op == Instruction::ICmp) {
2316 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2317 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2318 "Invalid ICmp predicate value");
2320 const Type* Op0Ty = getOperand(0)->getType();
2321 const Type* Op1Ty = getOperand(1)->getType();
2322 assert(Op0Ty == Op1Ty &&
2323 "Both operands to ICmp instruction are not of the same type!");
2324 // Check that the operands are the right type
2325 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2326 "Invalid operand types for ICmp instruction");
2329 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2330 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2331 "Invalid FCmp predicate value");
2332 const Type* Op0Ty = getOperand(0)->getType();
2333 const Type* Op1Ty = getOperand(1)->getType();
2334 assert(Op0Ty == Op1Ty &&
2335 "Both operands to FCmp instruction are not of the same type!");
2336 // Check that the operands are the right type
2337 assert(Op0Ty->isFloatingPoint() &&
2338 "Invalid operand types for FCmp instruction");
2342 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2343 const std::string &Name, Instruction *InsertBefore) {
2344 if (Op == Instruction::ICmp) {
2345 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2348 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2353 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2354 const std::string &Name, BasicBlock *InsertAtEnd) {
2355 if (Op == Instruction::ICmp) {
2356 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2359 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2363 void CmpInst::swapOperands() {
2364 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2367 cast<FCmpInst>(this)->swapOperands();
2370 bool CmpInst::isCommutative() {
2371 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2372 return IC->isCommutative();
2373 return cast<FCmpInst>(this)->isCommutative();
2376 bool CmpInst::isEquality() {
2377 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2378 return IC->isEquality();
2379 return cast<FCmpInst>(this)->isEquality();
2383 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2386 assert(!"Unknown icmp predicate!");
2387 case ICMP_EQ: return ICMP_NE;
2388 case ICMP_NE: return ICMP_EQ;
2389 case ICMP_UGT: return ICMP_ULE;
2390 case ICMP_ULT: return ICMP_UGE;
2391 case ICMP_UGE: return ICMP_ULT;
2392 case ICMP_ULE: return ICMP_UGT;
2393 case ICMP_SGT: return ICMP_SLE;
2394 case ICMP_SLT: return ICMP_SGE;
2395 case ICMP_SGE: return ICMP_SLT;
2396 case ICMP_SLE: return ICMP_SGT;
2400 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2402 default: assert(! "Unknown icmp predicate!");
2403 case ICMP_EQ: case ICMP_NE:
2405 case ICMP_SGT: return ICMP_SLT;
2406 case ICMP_SLT: return ICMP_SGT;
2407 case ICMP_SGE: return ICMP_SLE;
2408 case ICMP_SLE: return ICMP_SGE;
2409 case ICMP_UGT: return ICMP_ULT;
2410 case ICMP_ULT: return ICMP_UGT;
2411 case ICMP_UGE: return ICMP_ULE;
2412 case ICMP_ULE: return ICMP_UGE;
2416 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2418 default: assert(! "Unknown icmp predicate!");
2419 case ICMP_EQ: case ICMP_NE:
2420 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2422 case ICMP_UGT: return ICMP_SGT;
2423 case ICMP_ULT: return ICMP_SLT;
2424 case ICMP_UGE: return ICMP_SGE;
2425 case ICMP_ULE: return ICMP_SLE;
2429 bool ICmpInst::isSignedPredicate(Predicate pred) {
2431 default: assert(! "Unknown icmp predicate!");
2432 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2434 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2435 case ICMP_UGE: case ICMP_ULE:
2440 /// Initialize a set of values that all satisfy the condition with C.
2443 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2446 uint32_t BitWidth = C.getBitWidth();
2448 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2449 case ICmpInst::ICMP_EQ: Upper++; break;
2450 case ICmpInst::ICMP_NE: Lower++; break;
2451 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2452 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2453 case ICmpInst::ICMP_UGT:
2454 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2456 case ICmpInst::ICMP_SGT:
2457 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2459 case ICmpInst::ICMP_ULE:
2460 Lower = APInt::getMinValue(BitWidth); Upper++;
2462 case ICmpInst::ICMP_SLE:
2463 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2465 case ICmpInst::ICMP_UGE:
2466 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2468 case ICmpInst::ICMP_SGE:
2469 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2472 return ConstantRange(Lower, Upper);
2475 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2478 assert(!"Unknown icmp predicate!");
2479 case FCMP_OEQ: return FCMP_UNE;
2480 case FCMP_ONE: return FCMP_UEQ;
2481 case FCMP_OGT: return FCMP_ULE;
2482 case FCMP_OLT: return FCMP_UGE;
2483 case FCMP_OGE: return FCMP_ULT;
2484 case FCMP_OLE: return FCMP_UGT;
2485 case FCMP_UEQ: return FCMP_ONE;
2486 case FCMP_UNE: return FCMP_OEQ;
2487 case FCMP_UGT: return FCMP_OLE;
2488 case FCMP_ULT: return FCMP_OGE;
2489 case FCMP_UGE: return FCMP_OLT;
2490 case FCMP_ULE: return FCMP_OGT;
2491 case FCMP_ORD: return FCMP_UNO;
2492 case FCMP_UNO: return FCMP_ORD;
2493 case FCMP_TRUE: return FCMP_FALSE;
2494 case FCMP_FALSE: return FCMP_TRUE;
2498 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2500 default: assert(!"Unknown fcmp predicate!");
2501 case FCMP_FALSE: case FCMP_TRUE:
2502 case FCMP_OEQ: case FCMP_ONE:
2503 case FCMP_UEQ: case FCMP_UNE:
2504 case FCMP_ORD: case FCMP_UNO:
2506 case FCMP_OGT: return FCMP_OLT;
2507 case FCMP_OLT: return FCMP_OGT;
2508 case FCMP_OGE: return FCMP_OLE;
2509 case FCMP_OLE: return FCMP_OGE;
2510 case FCMP_UGT: return FCMP_ULT;
2511 case FCMP_ULT: return FCMP_UGT;
2512 case FCMP_UGE: return FCMP_ULE;
2513 case FCMP_ULE: return FCMP_UGE;
2517 bool CmpInst::isUnsigned(unsigned short predicate) {
2518 switch (predicate) {
2519 default: return false;
2520 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2521 case ICmpInst::ICMP_UGE: return true;
2525 bool CmpInst::isSigned(unsigned short predicate){
2526 switch (predicate) {
2527 default: return false;
2528 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2529 case ICmpInst::ICMP_SGE: return true;
2533 bool CmpInst::isOrdered(unsigned short predicate) {
2534 switch (predicate) {
2535 default: return false;
2536 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2537 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2538 case FCmpInst::FCMP_ORD: return true;
2542 bool CmpInst::isUnordered(unsigned short predicate) {
2543 switch (predicate) {
2544 default: return false;
2545 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2546 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2547 case FCmpInst::FCMP_UNO: return true;
2551 //===----------------------------------------------------------------------===//
2552 // SwitchInst Implementation
2553 //===----------------------------------------------------------------------===//
2555 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2556 assert(Value && Default);
2557 ReservedSpace = 2+NumCases*2;
2559 OperandList = new Use[ReservedSpace];
2561 OperandList[0].init(Value, this);
2562 OperandList[1].init(Default, this);
2565 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2566 /// switch on and a default destination. The number of additional cases can
2567 /// be specified here to make memory allocation more efficient. This
2568 /// constructor can also autoinsert before another instruction.
2569 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2570 Instruction *InsertBefore)
2571 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2572 init(Value, Default, NumCases);
2575 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2576 /// switch on and a default destination. The number of additional cases can
2577 /// be specified here to make memory allocation more efficient. This
2578 /// constructor also autoinserts at the end of the specified BasicBlock.
2579 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2580 BasicBlock *InsertAtEnd)
2581 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2582 init(Value, Default, NumCases);
2585 SwitchInst::SwitchInst(const SwitchInst &SI)
2586 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2587 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2588 Use *OL = OperandList, *InOL = SI.OperandList;
2589 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2590 OL[i].init(InOL[i], this);
2591 OL[i+1].init(InOL[i+1], this);
2595 SwitchInst::~SwitchInst() {
2596 delete [] OperandList;
2600 /// addCase - Add an entry to the switch instruction...
2602 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2603 unsigned OpNo = NumOperands;
2604 if (OpNo+2 > ReservedSpace)
2605 resizeOperands(0); // Get more space!
2606 // Initialize some new operands.
2607 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2608 NumOperands = OpNo+2;
2609 OperandList[OpNo].init(OnVal, this);
2610 OperandList[OpNo+1].init(Dest, this);
2613 /// removeCase - This method removes the specified successor from the switch
2614 /// instruction. Note that this cannot be used to remove the default
2615 /// destination (successor #0).
2617 void SwitchInst::removeCase(unsigned idx) {
2618 assert(idx != 0 && "Cannot remove the default case!");
2619 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2621 unsigned NumOps = getNumOperands();
2622 Use *OL = OperandList;
2624 // Move everything after this operand down.
2626 // FIXME: we could just swap with the end of the list, then erase. However,
2627 // client might not expect this to happen. The code as it is thrashes the
2628 // use/def lists, which is kinda lame.
2629 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2631 OL[i-2+1] = OL[i+1];
2634 // Nuke the last value.
2635 OL[NumOps-2].set(0);
2636 OL[NumOps-2+1].set(0);
2637 NumOperands = NumOps-2;
2640 /// resizeOperands - resize operands - This adjusts the length of the operands
2641 /// list according to the following behavior:
2642 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2643 /// of operation. This grows the number of ops by 1.5 times.
2644 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2645 /// 3. If NumOps == NumOperands, trim the reserved space.
2647 void SwitchInst::resizeOperands(unsigned NumOps) {
2649 NumOps = getNumOperands()/2*6;
2650 } else if (NumOps*2 > NumOperands) {
2651 // No resize needed.
2652 if (ReservedSpace >= NumOps) return;
2653 } else if (NumOps == NumOperands) {
2654 if (ReservedSpace == NumOps) return;
2659 ReservedSpace = NumOps;
2660 Use *NewOps = new Use[NumOps];
2661 Use *OldOps = OperandList;
2662 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2663 NewOps[i].init(OldOps[i], this);
2667 OperandList = NewOps;
2671 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2672 return getSuccessor(idx);
2674 unsigned SwitchInst::getNumSuccessorsV() const {
2675 return getNumSuccessors();
2677 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2678 setSuccessor(idx, B);
2682 // Define these methods here so vtables don't get emitted into every translation
2683 // unit that uses these classes.
2685 GetElementPtrInst *GetElementPtrInst::clone() const {
2686 return new GetElementPtrInst(*this);
2689 BinaryOperator *BinaryOperator::clone() const {
2690 return create(getOpcode(), Ops[0], Ops[1]);
2693 FCmpInst* FCmpInst::clone() const {
2694 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2696 ICmpInst* ICmpInst::clone() const {
2697 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2700 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2701 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2702 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2703 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2704 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2705 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2706 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2707 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2708 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2709 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2710 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2711 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2712 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2713 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2714 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2715 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2716 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2717 CallInst *CallInst::clone() const { return new CallInst(*this); }
2718 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2719 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2721 ExtractElementInst *ExtractElementInst::clone() const {
2722 return new ExtractElementInst(*this);
2724 InsertElementInst *InsertElementInst::clone() const {
2725 return new InsertElementInst(*this);
2727 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2728 return new ShuffleVectorInst(*this);
2730 PHINode *PHINode::clone() const { return new PHINode(*this); }
2731 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2732 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2733 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2734 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2735 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2736 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}