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 return ParamAttrs && ParamAttrs->hasAttrSomewhere(ParamAttr::ByVal);
412 void CallInst::setDoesNotThrow(bool doesNotThrow) {
413 const ParamAttrsList *PAL = getParamAttrs();
415 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
417 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
422 //===----------------------------------------------------------------------===//
423 // InvokeInst Implementation
424 //===----------------------------------------------------------------------===//
426 InvokeInst::~InvokeInst() {
427 delete [] OperandList;
429 ParamAttrs->dropRef();
432 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
433 Value* const *Args, unsigned NumArgs) {
435 NumOperands = 3+NumArgs;
436 Use *OL = OperandList = new Use[3+NumArgs];
437 OL[0].init(Fn, this);
438 OL[1].init(IfNormal, this);
439 OL[2].init(IfException, this);
440 const FunctionType *FTy =
441 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
442 FTy = FTy; // silence warning.
444 assert((NumArgs == FTy->getNumParams()) ||
445 (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
446 "Calling a function with bad signature");
448 for (unsigned i = 0, e = NumArgs; i != e; i++) {
449 assert((i >= FTy->getNumParams() ||
450 FTy->getParamType(i) == Args[i]->getType()) &&
451 "Invoking a function with a bad signature!");
453 OL[i+3].init(Args[i], this);
457 InvokeInst::InvokeInst(const InvokeInst &II)
458 : TerminatorInst(II.getType(), Instruction::Invoke,
459 new Use[II.getNumOperands()], II.getNumOperands()),
461 setParamAttrs(II.getParamAttrs());
462 SubclassData = II.SubclassData;
463 Use *OL = OperandList, *InOL = II.OperandList;
464 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
465 OL[i].init(InOL[i], this);
468 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
469 return getSuccessor(idx);
471 unsigned InvokeInst::getNumSuccessorsV() const {
472 return getNumSuccessors();
474 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
475 return setSuccessor(idx, B);
478 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
479 if (ParamAttrs == newAttrs)
483 ParamAttrs->dropRef();
488 ParamAttrs = newAttrs;
491 bool InvokeInst::paramHasAttr(uint16_t i, unsigned attr) const {
492 if (ParamAttrs && ParamAttrs->paramHasAttr(i, (ParameterAttributes)attr))
494 if (const Function *F = getCalledFunction())
495 return F->paramHasAttr(i, (ParameterAttributes)attr);
500 /// @brief Determine if the call does not access memory.
501 bool InvokeInst::doesNotAccessMemory() const {
502 return paramHasAttr(0, ParamAttr::ReadNone);
505 /// @brief Determine if the call does not access or only reads memory.
506 bool InvokeInst::onlyReadsMemory() const {
507 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
510 /// @brief Determine if the call cannot return.
511 bool InvokeInst::doesNotReturn() const {
512 return paramHasAttr(0, ParamAttr::NoReturn);
515 /// @brief Determine if the call cannot unwind.
516 bool InvokeInst::doesNotThrow() const {
517 return paramHasAttr(0, ParamAttr::NoUnwind);
520 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
521 const ParamAttrsList *PAL = getParamAttrs();
523 PAL = ParamAttrsList::includeAttrs(PAL, 0, ParamAttr::NoUnwind);
525 PAL = ParamAttrsList::excludeAttrs(PAL, 0, ParamAttr::NoUnwind);
529 /// @brief Determine if the call returns a structure.
530 bool InvokeInst::isStructReturn() const {
531 // Be friendly and also check the callee.
532 return paramHasAttr(1, ParamAttr::StructRet);
536 //===----------------------------------------------------------------------===//
537 // ReturnInst Implementation
538 //===----------------------------------------------------------------------===//
540 ReturnInst::ReturnInst(const ReturnInst &RI)
541 : TerminatorInst(Type::VoidTy, Instruction::Ret,
542 &RetVal, RI.getNumOperands()) {
543 if (RI.getNumOperands())
544 RetVal.init(RI.RetVal, this);
547 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
548 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
551 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
552 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
555 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
556 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
561 void ReturnInst::init(Value *retVal) {
562 if (retVal && retVal->getType() != Type::VoidTy) {
563 assert(!isa<BasicBlock>(retVal) &&
564 "Cannot return basic block. Probably using the incorrect ctor");
566 RetVal.init(retVal, this);
570 unsigned ReturnInst::getNumSuccessorsV() const {
571 return getNumSuccessors();
574 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
575 // emit the vtable for the class in this translation unit.
576 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
577 assert(0 && "ReturnInst has no successors!");
580 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
581 assert(0 && "ReturnInst has no successors!");
587 //===----------------------------------------------------------------------===//
588 // UnwindInst Implementation
589 //===----------------------------------------------------------------------===//
591 UnwindInst::UnwindInst(Instruction *InsertBefore)
592 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
594 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
595 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
599 unsigned UnwindInst::getNumSuccessorsV() const {
600 return getNumSuccessors();
603 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
604 assert(0 && "UnwindInst has no successors!");
607 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
608 assert(0 && "UnwindInst has no successors!");
613 //===----------------------------------------------------------------------===//
614 // UnreachableInst Implementation
615 //===----------------------------------------------------------------------===//
617 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
618 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
620 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
621 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
624 unsigned UnreachableInst::getNumSuccessorsV() const {
625 return getNumSuccessors();
628 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
629 assert(0 && "UnwindInst has no successors!");
632 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
633 assert(0 && "UnwindInst has no successors!");
638 //===----------------------------------------------------------------------===//
639 // BranchInst Implementation
640 //===----------------------------------------------------------------------===//
642 void BranchInst::AssertOK() {
644 assert(getCondition()->getType() == Type::Int1Ty &&
645 "May only branch on boolean predicates!");
648 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
649 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
650 assert(IfTrue != 0 && "Branch destination may not be null!");
651 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
653 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
654 Instruction *InsertBefore)
655 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
656 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
657 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
658 Ops[2].init(Cond, this);
664 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
665 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
666 assert(IfTrue != 0 && "Branch destination may not be null!");
667 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
670 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
671 BasicBlock *InsertAtEnd)
672 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
673 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
674 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
675 Ops[2].init(Cond, this);
682 BranchInst::BranchInst(const BranchInst &BI) :
683 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
684 OperandList[0].init(BI.getOperand(0), this);
685 if (BI.getNumOperands() != 1) {
686 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
687 OperandList[1].init(BI.getOperand(1), this);
688 OperandList[2].init(BI.getOperand(2), this);
692 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
693 return getSuccessor(idx);
695 unsigned BranchInst::getNumSuccessorsV() const {
696 return getNumSuccessors();
698 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
699 setSuccessor(idx, B);
703 //===----------------------------------------------------------------------===//
704 // AllocationInst Implementation
705 //===----------------------------------------------------------------------===//
707 static Value *getAISize(Value *Amt) {
709 Amt = ConstantInt::get(Type::Int32Ty, 1);
711 assert(!isa<BasicBlock>(Amt) &&
712 "Passed basic block into allocation size parameter! Use other ctor");
713 assert(Amt->getType() == Type::Int32Ty &&
714 "Malloc/Allocation array size is not a 32-bit integer!");
719 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
720 unsigned Align, const std::string &Name,
721 Instruction *InsertBefore)
722 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
723 InsertBefore), Alignment(Align) {
724 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
725 assert(Ty != Type::VoidTy && "Cannot allocate void!");
729 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
730 unsigned Align, const std::string &Name,
731 BasicBlock *InsertAtEnd)
732 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
733 InsertAtEnd), Alignment(Align) {
734 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
735 assert(Ty != Type::VoidTy && "Cannot allocate void!");
739 // Out of line virtual method, so the vtable, etc has a home.
740 AllocationInst::~AllocationInst() {
743 bool AllocationInst::isArrayAllocation() const {
744 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
745 return CI->getZExtValue() != 1;
749 const Type *AllocationInst::getAllocatedType() const {
750 return getType()->getElementType();
753 AllocaInst::AllocaInst(const AllocaInst &AI)
754 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
755 Instruction::Alloca, AI.getAlignment()) {
758 MallocInst::MallocInst(const MallocInst &MI)
759 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
760 Instruction::Malloc, MI.getAlignment()) {
763 //===----------------------------------------------------------------------===//
764 // FreeInst Implementation
765 //===----------------------------------------------------------------------===//
767 void FreeInst::AssertOK() {
768 assert(isa<PointerType>(getOperand(0)->getType()) &&
769 "Can not free something of nonpointer type!");
772 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
773 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
777 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
778 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
783 //===----------------------------------------------------------------------===//
784 // LoadInst Implementation
785 //===----------------------------------------------------------------------===//
787 void LoadInst::AssertOK() {
788 assert(isa<PointerType>(getOperand(0)->getType()) &&
789 "Ptr must have pointer type.");
792 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
793 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
794 Load, Ptr, InsertBef) {
801 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
802 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
803 Load, Ptr, InsertAE) {
810 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
811 Instruction *InsertBef)
812 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
813 Load, Ptr, InsertBef) {
814 setVolatile(isVolatile);
820 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
821 unsigned Align, Instruction *InsertBef)
822 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
823 Load, Ptr, InsertBef) {
824 setVolatile(isVolatile);
830 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
831 unsigned Align, BasicBlock *InsertAE)
832 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
833 Load, Ptr, InsertAE) {
834 setVolatile(isVolatile);
840 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
841 BasicBlock *InsertAE)
842 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
843 Load, Ptr, InsertAE) {
844 setVolatile(isVolatile);
852 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
853 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
854 Load, Ptr, InsertBef) {
858 if (Name && Name[0]) setName(Name);
861 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
862 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
863 Load, Ptr, InsertAE) {
867 if (Name && Name[0]) setName(Name);
870 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
871 Instruction *InsertBef)
872 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
873 Load, Ptr, InsertBef) {
874 setVolatile(isVolatile);
877 if (Name && Name[0]) setName(Name);
880 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
881 BasicBlock *InsertAE)
882 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
883 Load, Ptr, InsertAE) {
884 setVolatile(isVolatile);
887 if (Name && Name[0]) setName(Name);
890 void LoadInst::setAlignment(unsigned Align) {
891 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
892 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
895 //===----------------------------------------------------------------------===//
896 // StoreInst Implementation
897 //===----------------------------------------------------------------------===//
899 void StoreInst::AssertOK() {
900 assert(isa<PointerType>(getOperand(1)->getType()) &&
901 "Ptr must have pointer type!");
902 assert(getOperand(0)->getType() ==
903 cast<PointerType>(getOperand(1)->getType())->getElementType()
904 && "Ptr must be a pointer to Val type!");
908 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
909 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
910 Ops[0].init(val, this);
911 Ops[1].init(addr, this);
917 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
918 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
919 Ops[0].init(val, this);
920 Ops[1].init(addr, this);
926 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
927 Instruction *InsertBefore)
928 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
929 Ops[0].init(val, this);
930 Ops[1].init(addr, this);
931 setVolatile(isVolatile);
936 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
937 unsigned Align, Instruction *InsertBefore)
938 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
939 Ops[0].init(val, this);
940 Ops[1].init(addr, this);
941 setVolatile(isVolatile);
946 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
947 unsigned Align, BasicBlock *InsertAtEnd)
948 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
949 Ops[0].init(val, this);
950 Ops[1].init(addr, this);
951 setVolatile(isVolatile);
956 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
957 BasicBlock *InsertAtEnd)
958 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
959 Ops[0].init(val, this);
960 Ops[1].init(addr, this);
961 setVolatile(isVolatile);
966 void StoreInst::setAlignment(unsigned Align) {
967 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
968 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
971 //===----------------------------------------------------------------------===//
972 // GetElementPtrInst Implementation
973 //===----------------------------------------------------------------------===//
975 static unsigned retrieveAddrSpace(const Value *Val) {
976 return cast<PointerType>(Val->getType())->getAddressSpace();
979 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
980 NumOperands = 1+NumIdx;
981 Use *OL = OperandList = new Use[NumOperands];
982 OL[0].init(Ptr, this);
984 for (unsigned i = 0; i != NumIdx; ++i)
985 OL[i+1].init(Idx[i], this);
988 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
990 Use *OL = OperandList = new Use[2];
991 OL[0].init(Ptr, this);
992 OL[1].init(Idx, this);
995 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
996 const std::string &Name, Instruction *InBe)
997 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
998 retrieveAddrSpace(Ptr)),
999 GetElementPtr, 0, 0, InBe) {
1004 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1005 const std::string &Name, BasicBlock *IAE)
1006 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1007 retrieveAddrSpace(Ptr)),
1008 GetElementPtr, 0, 0, IAE) {
1013 GetElementPtrInst::~GetElementPtrInst() {
1014 delete[] OperandList;
1017 // getIndexedType - Returns the type of the element that would be loaded with
1018 // a load instruction with the specified parameters.
1020 // A null type is returned if the indices are invalid for the specified
1023 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1026 bool AllowCompositeLeaf) {
1027 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
1029 // Handle the special case of the empty set index set...
1031 if (AllowCompositeLeaf ||
1032 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
1033 return cast<PointerType>(Ptr)->getElementType();
1037 unsigned CurIdx = 0;
1038 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1039 if (NumIdx == CurIdx) {
1040 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1041 return 0; // Can't load a whole structure or array!?!?
1044 Value *Index = Idxs[CurIdx++];
1045 if (isa<PointerType>(CT) && CurIdx != 1)
1046 return 0; // Can only index into pointer types at the first index!
1047 if (!CT->indexValid(Index)) return 0;
1048 Ptr = CT->getTypeAtIndex(Index);
1050 // If the new type forwards to another type, then it is in the middle
1051 // of being refined to another type (and hence, may have dropped all
1052 // references to what it was using before). So, use the new forwarded
1054 if (const Type * Ty = Ptr->getForwardedType()) {
1058 return CurIdx == NumIdx ? Ptr : 0;
1061 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1062 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1063 if (!PTy) return 0; // Type isn't a pointer type!
1065 // Check the pointer index.
1066 if (!PTy->indexValid(Idx)) return 0;
1068 return PTy->getElementType();
1072 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1073 /// zeros. If so, the result pointer and the first operand have the same
1074 /// value, just potentially different types.
1075 bool GetElementPtrInst::hasAllZeroIndices() const {
1076 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1077 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1078 if (!CI->isZero()) return false;
1086 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1087 /// constant integers. If so, the result pointer and the first operand have
1088 /// a constant offset between them.
1089 bool GetElementPtrInst::hasAllConstantIndices() const {
1090 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1091 if (!isa<ConstantInt>(getOperand(i)))
1098 //===----------------------------------------------------------------------===//
1099 // ExtractElementInst Implementation
1100 //===----------------------------------------------------------------------===//
1102 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1103 const std::string &Name,
1104 Instruction *InsertBef)
1105 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1106 ExtractElement, Ops, 2, InsertBef) {
1107 assert(isValidOperands(Val, Index) &&
1108 "Invalid extractelement instruction operands!");
1109 Ops[0].init(Val, this);
1110 Ops[1].init(Index, this);
1114 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1115 const std::string &Name,
1116 Instruction *InsertBef)
1117 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1118 ExtractElement, Ops, 2, InsertBef) {
1119 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1120 assert(isValidOperands(Val, Index) &&
1121 "Invalid extractelement instruction operands!");
1122 Ops[0].init(Val, this);
1123 Ops[1].init(Index, this);
1128 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1129 const std::string &Name,
1130 BasicBlock *InsertAE)
1131 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1132 ExtractElement, Ops, 2, InsertAE) {
1133 assert(isValidOperands(Val, Index) &&
1134 "Invalid extractelement instruction operands!");
1136 Ops[0].init(Val, this);
1137 Ops[1].init(Index, this);
1141 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1142 const std::string &Name,
1143 BasicBlock *InsertAE)
1144 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1145 ExtractElement, Ops, 2, InsertAE) {
1146 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1147 assert(isValidOperands(Val, Index) &&
1148 "Invalid extractelement instruction operands!");
1150 Ops[0].init(Val, this);
1151 Ops[1].init(Index, this);
1156 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1157 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1163 //===----------------------------------------------------------------------===//
1164 // InsertElementInst Implementation
1165 //===----------------------------------------------------------------------===//
1167 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1168 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1169 Ops[0].init(IE.Ops[0], this);
1170 Ops[1].init(IE.Ops[1], this);
1171 Ops[2].init(IE.Ops[2], this);
1173 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1174 const std::string &Name,
1175 Instruction *InsertBef)
1176 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1177 assert(isValidOperands(Vec, Elt, Index) &&
1178 "Invalid insertelement instruction operands!");
1179 Ops[0].init(Vec, this);
1180 Ops[1].init(Elt, this);
1181 Ops[2].init(Index, this);
1185 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1186 const std::string &Name,
1187 Instruction *InsertBef)
1188 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1189 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1190 assert(isValidOperands(Vec, Elt, Index) &&
1191 "Invalid insertelement instruction operands!");
1192 Ops[0].init(Vec, this);
1193 Ops[1].init(Elt, this);
1194 Ops[2].init(Index, this);
1199 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1200 const std::string &Name,
1201 BasicBlock *InsertAE)
1202 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1203 assert(isValidOperands(Vec, Elt, Index) &&
1204 "Invalid insertelement instruction operands!");
1206 Ops[0].init(Vec, this);
1207 Ops[1].init(Elt, this);
1208 Ops[2].init(Index, this);
1212 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1213 const std::string &Name,
1214 BasicBlock *InsertAE)
1215 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1216 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1217 assert(isValidOperands(Vec, Elt, Index) &&
1218 "Invalid insertelement instruction operands!");
1220 Ops[0].init(Vec, this);
1221 Ops[1].init(Elt, this);
1222 Ops[2].init(Index, this);
1226 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1227 const Value *Index) {
1228 if (!isa<VectorType>(Vec->getType()))
1229 return false; // First operand of insertelement must be vector type.
1231 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1232 return false;// Second operand of insertelement must be vector element type.
1234 if (Index->getType() != Type::Int32Ty)
1235 return false; // Third operand of insertelement must be uint.
1240 //===----------------------------------------------------------------------===//
1241 // ShuffleVectorInst Implementation
1242 //===----------------------------------------------------------------------===//
1244 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1245 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1246 Ops[0].init(SV.Ops[0], this);
1247 Ops[1].init(SV.Ops[1], this);
1248 Ops[2].init(SV.Ops[2], this);
1251 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1252 const std::string &Name,
1253 Instruction *InsertBefore)
1254 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1255 assert(isValidOperands(V1, V2, Mask) &&
1256 "Invalid shuffle vector instruction operands!");
1257 Ops[0].init(V1, this);
1258 Ops[1].init(V2, this);
1259 Ops[2].init(Mask, this);
1263 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1264 const std::string &Name,
1265 BasicBlock *InsertAtEnd)
1266 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1267 assert(isValidOperands(V1, V2, Mask) &&
1268 "Invalid shuffle vector instruction operands!");
1270 Ops[0].init(V1, this);
1271 Ops[1].init(V2, this);
1272 Ops[2].init(Mask, this);
1276 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1277 const Value *Mask) {
1278 if (!isa<VectorType>(V1->getType())) return false;
1279 if (V1->getType() != V2->getType()) return false;
1280 if (!isa<VectorType>(Mask->getType()) ||
1281 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1282 cast<VectorType>(Mask->getType())->getNumElements() !=
1283 cast<VectorType>(V1->getType())->getNumElements())
1289 //===----------------------------------------------------------------------===//
1290 // BinaryOperator Class
1291 //===----------------------------------------------------------------------===//
1293 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1294 const Type *Ty, const std::string &Name,
1295 Instruction *InsertBefore)
1296 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1297 Ops[0].init(S1, this);
1298 Ops[1].init(S2, this);
1303 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1304 const Type *Ty, const std::string &Name,
1305 BasicBlock *InsertAtEnd)
1306 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1307 Ops[0].init(S1, this);
1308 Ops[1].init(S2, this);
1314 void BinaryOperator::init(BinaryOps iType) {
1315 Value *LHS = getOperand(0), *RHS = getOperand(1);
1316 LHS = LHS; RHS = RHS; // Silence warnings.
1317 assert(LHS->getType() == RHS->getType() &&
1318 "Binary operator operand types must match!");
1323 assert(getType() == LHS->getType() &&
1324 "Arithmetic operation should return same type as operands!");
1325 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1326 isa<VectorType>(getType())) &&
1327 "Tried to create an arithmetic operation on a non-arithmetic type!");
1331 assert(getType() == LHS->getType() &&
1332 "Arithmetic operation should return same type as operands!");
1333 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1334 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1335 "Incorrect operand type (not integer) for S/UDIV");
1338 assert(getType() == LHS->getType() &&
1339 "Arithmetic operation should return same type as operands!");
1340 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1341 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1342 && "Incorrect operand type (not floating point) for FDIV");
1346 assert(getType() == LHS->getType() &&
1347 "Arithmetic operation should return same type as operands!");
1348 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1349 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1350 "Incorrect operand type (not integer) for S/UREM");
1353 assert(getType() == LHS->getType() &&
1354 "Arithmetic operation should return same type as operands!");
1355 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1356 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1357 && "Incorrect operand type (not floating point) for FREM");
1362 assert(getType() == LHS->getType() &&
1363 "Shift operation should return same type as operands!");
1364 assert(getType()->isInteger() &&
1365 "Shift operation requires integer operands");
1369 assert(getType() == LHS->getType() &&
1370 "Logical operation should return same type as operands!");
1371 assert((getType()->isInteger() ||
1372 (isa<VectorType>(getType()) &&
1373 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1374 "Tried to create a logical operation on a non-integral type!");
1382 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1383 const std::string &Name,
1384 Instruction *InsertBefore) {
1385 assert(S1->getType() == S2->getType() &&
1386 "Cannot create binary operator with two operands of differing type!");
1387 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1390 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1391 const std::string &Name,
1392 BasicBlock *InsertAtEnd) {
1393 BinaryOperator *Res = create(Op, S1, S2, Name);
1394 InsertAtEnd->getInstList().push_back(Res);
1398 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1399 Instruction *InsertBefore) {
1400 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1401 return new BinaryOperator(Instruction::Sub,
1403 Op->getType(), Name, InsertBefore);
1406 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1407 BasicBlock *InsertAtEnd) {
1408 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1409 return new BinaryOperator(Instruction::Sub,
1411 Op->getType(), Name, InsertAtEnd);
1414 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1415 Instruction *InsertBefore) {
1417 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1418 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1419 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1421 C = ConstantInt::getAllOnesValue(Op->getType());
1424 return new BinaryOperator(Instruction::Xor, Op, C,
1425 Op->getType(), Name, InsertBefore);
1428 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1429 BasicBlock *InsertAtEnd) {
1431 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1432 // Create a vector of all ones values.
1433 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1435 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1437 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1440 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1441 Op->getType(), Name, InsertAtEnd);
1445 // isConstantAllOnes - Helper function for several functions below
1446 static inline bool isConstantAllOnes(const Value *V) {
1447 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1448 return CI->isAllOnesValue();
1449 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1450 return CV->isAllOnesValue();
1454 bool BinaryOperator::isNeg(const Value *V) {
1455 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1456 if (Bop->getOpcode() == Instruction::Sub)
1457 return Bop->getOperand(0) ==
1458 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1462 bool BinaryOperator::isNot(const Value *V) {
1463 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1464 return (Bop->getOpcode() == Instruction::Xor &&
1465 (isConstantAllOnes(Bop->getOperand(1)) ||
1466 isConstantAllOnes(Bop->getOperand(0))));
1470 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1471 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1472 return cast<BinaryOperator>(BinOp)->getOperand(1);
1475 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1476 return getNegArgument(const_cast<Value*>(BinOp));
1479 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1480 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1481 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1482 Value *Op0 = BO->getOperand(0);
1483 Value *Op1 = BO->getOperand(1);
1484 if (isConstantAllOnes(Op0)) return Op1;
1486 assert(isConstantAllOnes(Op1));
1490 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1491 return getNotArgument(const_cast<Value*>(BinOp));
1495 // swapOperands - Exchange the two operands to this instruction. This
1496 // instruction is safe to use on any binary instruction and does not
1497 // modify the semantics of the instruction. If the instruction is
1498 // order dependent (SetLT f.e.) the opcode is changed.
1500 bool BinaryOperator::swapOperands() {
1501 if (!isCommutative())
1502 return true; // Can't commute operands
1503 std::swap(Ops[0], Ops[1]);
1507 //===----------------------------------------------------------------------===//
1509 //===----------------------------------------------------------------------===//
1511 // Just determine if this cast only deals with integral->integral conversion.
1512 bool CastInst::isIntegerCast() const {
1513 switch (getOpcode()) {
1514 default: return false;
1515 case Instruction::ZExt:
1516 case Instruction::SExt:
1517 case Instruction::Trunc:
1519 case Instruction::BitCast:
1520 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1524 bool CastInst::isLosslessCast() const {
1525 // Only BitCast can be lossless, exit fast if we're not BitCast
1526 if (getOpcode() != Instruction::BitCast)
1529 // Identity cast is always lossless
1530 const Type* SrcTy = getOperand(0)->getType();
1531 const Type* DstTy = getType();
1535 // Pointer to pointer is always lossless.
1536 if (isa<PointerType>(SrcTy))
1537 return isa<PointerType>(DstTy);
1538 return false; // Other types have no identity values
1541 /// This function determines if the CastInst does not require any bits to be
1542 /// changed in order to effect the cast. Essentially, it identifies cases where
1543 /// no code gen is necessary for the cast, hence the name no-op cast. For
1544 /// example, the following are all no-op casts:
1545 /// # bitcast uint %X, int
1546 /// # bitcast uint* %x, sbyte*
1547 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1548 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1549 /// @brief Determine if a cast is a no-op.
1550 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1551 switch (getOpcode()) {
1553 assert(!"Invalid CastOp");
1554 case Instruction::Trunc:
1555 case Instruction::ZExt:
1556 case Instruction::SExt:
1557 case Instruction::FPTrunc:
1558 case Instruction::FPExt:
1559 case Instruction::UIToFP:
1560 case Instruction::SIToFP:
1561 case Instruction::FPToUI:
1562 case Instruction::FPToSI:
1563 return false; // These always modify bits
1564 case Instruction::BitCast:
1565 return true; // BitCast never modifies bits.
1566 case Instruction::PtrToInt:
1567 return IntPtrTy->getPrimitiveSizeInBits() ==
1568 getType()->getPrimitiveSizeInBits();
1569 case Instruction::IntToPtr:
1570 return IntPtrTy->getPrimitiveSizeInBits() ==
1571 getOperand(0)->getType()->getPrimitiveSizeInBits();
1575 /// This function determines if a pair of casts can be eliminated and what
1576 /// opcode should be used in the elimination. This assumes that there are two
1577 /// instructions like this:
1578 /// * %F = firstOpcode SrcTy %x to MidTy
1579 /// * %S = secondOpcode MidTy %F to DstTy
1580 /// The function returns a resultOpcode so these two casts can be replaced with:
1581 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1582 /// If no such cast is permited, the function returns 0.
1583 unsigned CastInst::isEliminableCastPair(
1584 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1585 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1587 // Define the 144 possibilities for these two cast instructions. The values
1588 // in this matrix determine what to do in a given situation and select the
1589 // case in the switch below. The rows correspond to firstOp, the columns
1590 // correspond to secondOp. In looking at the table below, keep in mind
1591 // the following cast properties:
1593 // Size Compare Source Destination
1594 // Operator Src ? Size Type Sign Type Sign
1595 // -------- ------------ ------------------- ---------------------
1596 // TRUNC > Integer Any Integral Any
1597 // ZEXT < Integral Unsigned Integer Any
1598 // SEXT < Integral Signed Integer Any
1599 // FPTOUI n/a FloatPt n/a Integral Unsigned
1600 // FPTOSI n/a FloatPt n/a Integral Signed
1601 // UITOFP n/a Integral Unsigned FloatPt n/a
1602 // SITOFP n/a Integral Signed FloatPt n/a
1603 // FPTRUNC > FloatPt n/a FloatPt n/a
1604 // FPEXT < FloatPt n/a FloatPt n/a
1605 // PTRTOINT n/a Pointer n/a Integral Unsigned
1606 // INTTOPTR n/a Integral Unsigned Pointer n/a
1607 // BITCONVERT = FirstClass n/a FirstClass n/a
1609 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1610 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1611 // into "fptoui double to ulong", but this loses information about the range
1612 // of the produced value (we no longer know the top-part is all zeros).
1613 // Further this conversion is often much more expensive for typical hardware,
1614 // and causes issues when building libgcc. We disallow fptosi+sext for the
1616 const unsigned numCastOps =
1617 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1618 static const uint8_t CastResults[numCastOps][numCastOps] = {
1619 // T F F U S F F P I B -+
1620 // R Z S P P I I T P 2 N T |
1621 // U E E 2 2 2 2 R E I T C +- secondOp
1622 // N X X U S F F N X N 2 V |
1623 // C T T I I P P C T T P T -+
1624 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1625 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1626 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1627 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1628 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1629 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1630 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1631 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1632 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1633 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1634 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1635 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1638 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1639 [secondOp-Instruction::CastOpsBegin];
1642 // categorically disallowed
1645 // allowed, use first cast's opcode
1648 // allowed, use second cast's opcode
1651 // no-op cast in second op implies firstOp as long as the DestTy
1653 if (DstTy->isInteger())
1657 // no-op cast in second op implies firstOp as long as the DestTy
1658 // is floating point
1659 if (DstTy->isFloatingPoint())
1663 // no-op cast in first op implies secondOp as long as the SrcTy
1665 if (SrcTy->isInteger())
1669 // no-op cast in first op implies secondOp as long as the SrcTy
1670 // is a floating point
1671 if (SrcTy->isFloatingPoint())
1675 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1676 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1677 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1678 if (MidSize >= PtrSize)
1679 return Instruction::BitCast;
1683 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1684 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1685 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1686 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1687 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1688 if (SrcSize == DstSize)
1689 return Instruction::BitCast;
1690 else if (SrcSize < DstSize)
1694 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1695 return Instruction::ZExt;
1697 // fpext followed by ftrunc is allowed if the bit size returned to is
1698 // the same as the original, in which case its just a bitcast
1700 return Instruction::BitCast;
1701 return 0; // If the types are not the same we can't eliminate it.
1703 // bitcast followed by ptrtoint is allowed as long as the bitcast
1704 // is a pointer to pointer cast.
1705 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1709 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1710 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1714 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1715 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1716 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1717 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1718 if (SrcSize <= PtrSize && SrcSize == DstSize)
1719 return Instruction::BitCast;
1723 // cast combination can't happen (error in input). This is for all cases
1724 // where the MidTy is not the same for the two cast instructions.
1725 assert(!"Invalid Cast Combination");
1728 assert(!"Error in CastResults table!!!");
1734 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1735 const std::string &Name, Instruction *InsertBefore) {
1736 // Construct and return the appropriate CastInst subclass
1738 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1739 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1740 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1741 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1742 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1743 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1744 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1745 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1746 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1747 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1748 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1749 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1751 assert(!"Invalid opcode provided");
1756 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1757 const std::string &Name, BasicBlock *InsertAtEnd) {
1758 // Construct and return the appropriate CastInst subclass
1760 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1761 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1762 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1763 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1764 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1765 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1766 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1767 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1768 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1769 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1770 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1771 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1773 assert(!"Invalid opcode provided");
1778 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1779 const std::string &Name,
1780 Instruction *InsertBefore) {
1781 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1782 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1783 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1786 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1787 const std::string &Name,
1788 BasicBlock *InsertAtEnd) {
1789 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1790 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1791 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1794 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1795 const std::string &Name,
1796 Instruction *InsertBefore) {
1797 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1798 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1799 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1802 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1803 const std::string &Name,
1804 BasicBlock *InsertAtEnd) {
1805 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1806 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1807 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1810 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1811 const std::string &Name,
1812 Instruction *InsertBefore) {
1813 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1814 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1815 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1818 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1819 const std::string &Name,
1820 BasicBlock *InsertAtEnd) {
1821 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1822 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1823 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1826 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1827 const std::string &Name,
1828 BasicBlock *InsertAtEnd) {
1829 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1830 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1833 if (Ty->isInteger())
1834 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1835 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1838 /// @brief Create a BitCast or a PtrToInt cast instruction
1839 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1840 const std::string &Name,
1841 Instruction *InsertBefore) {
1842 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1843 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1846 if (Ty->isInteger())
1847 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1848 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1851 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1852 bool isSigned, const std::string &Name,
1853 Instruction *InsertBefore) {
1854 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1855 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1856 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1857 Instruction::CastOps opcode =
1858 (SrcBits == DstBits ? Instruction::BitCast :
1859 (SrcBits > DstBits ? Instruction::Trunc :
1860 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1861 return create(opcode, C, Ty, Name, InsertBefore);
1864 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1865 bool isSigned, const std::string &Name,
1866 BasicBlock *InsertAtEnd) {
1867 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1868 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1869 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1870 Instruction::CastOps opcode =
1871 (SrcBits == DstBits ? Instruction::BitCast :
1872 (SrcBits > DstBits ? Instruction::Trunc :
1873 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1874 return create(opcode, C, Ty, Name, InsertAtEnd);
1877 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1878 const std::string &Name,
1879 Instruction *InsertBefore) {
1880 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1882 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1883 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1884 Instruction::CastOps opcode =
1885 (SrcBits == DstBits ? Instruction::BitCast :
1886 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1887 return create(opcode, C, Ty, Name, InsertBefore);
1890 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1891 const std::string &Name,
1892 BasicBlock *InsertAtEnd) {
1893 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1895 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1896 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1897 Instruction::CastOps opcode =
1898 (SrcBits == DstBits ? Instruction::BitCast :
1899 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1900 return create(opcode, C, Ty, Name, InsertAtEnd);
1903 // Check whether it is valid to call getCastOpcode for these types.
1904 // This routine must be kept in sync with getCastOpcode.
1905 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1906 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1909 if (SrcTy == DestTy)
1912 // Get the bit sizes, we'll need these
1913 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1914 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1916 // Run through the possibilities ...
1917 if (DestTy->isInteger()) { // Casting to integral
1918 if (SrcTy->isInteger()) { // Casting from integral
1920 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1922 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1923 // Casting from vector
1924 return DestBits == PTy->getBitWidth();
1925 } else { // Casting from something else
1926 return isa<PointerType>(SrcTy);
1928 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1929 if (SrcTy->isInteger()) { // Casting from integral
1931 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1933 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1934 // Casting from vector
1935 return DestBits == PTy->getBitWidth();
1936 } else { // Casting from something else
1939 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1940 // Casting to vector
1941 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1942 // Casting from vector
1943 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
1944 } else { // Casting from something else
1945 return DestPTy->getBitWidth() == SrcBits;
1947 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
1948 if (isa<PointerType>(SrcTy)) { // Casting from pointer
1950 } else if (SrcTy->isInteger()) { // Casting from integral
1952 } else { // Casting from something else
1955 } else { // Casting to something else
1960 // Provide a way to get a "cast" where the cast opcode is inferred from the
1961 // types and size of the operand. This, basically, is a parallel of the
1962 // logic in the castIsValid function below. This axiom should hold:
1963 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1964 // should not assert in castIsValid. In other words, this produces a "correct"
1965 // casting opcode for the arguments passed to it.
1966 // This routine must be kept in sync with isCastable.
1967 Instruction::CastOps
1968 CastInst::getCastOpcode(
1969 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1970 // Get the bit sizes, we'll need these
1971 const Type *SrcTy = Src->getType();
1972 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1973 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1975 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
1976 "Only first class types are castable!");
1978 // Run through the possibilities ...
1979 if (DestTy->isInteger()) { // Casting to integral
1980 if (SrcTy->isInteger()) { // Casting from integral
1981 if (DestBits < SrcBits)
1982 return Trunc; // int -> smaller int
1983 else if (DestBits > SrcBits) { // its an extension
1985 return SExt; // signed -> SEXT
1987 return ZExt; // unsigned -> ZEXT
1989 return BitCast; // Same size, No-op cast
1991 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1993 return FPToSI; // FP -> sint
1995 return FPToUI; // FP -> uint
1996 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1997 assert(DestBits == PTy->getBitWidth() &&
1998 "Casting vector to integer of different width");
1999 return BitCast; // Same size, no-op cast
2001 assert(isa<PointerType>(SrcTy) &&
2002 "Casting from a value that is not first-class type");
2003 return PtrToInt; // ptr -> int
2005 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2006 if (SrcTy->isInteger()) { // Casting from integral
2008 return SIToFP; // sint -> FP
2010 return UIToFP; // uint -> FP
2011 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2012 if (DestBits < SrcBits) {
2013 return FPTrunc; // FP -> smaller FP
2014 } else if (DestBits > SrcBits) {
2015 return FPExt; // FP -> larger FP
2017 return BitCast; // same size, no-op cast
2019 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2020 assert(DestBits == PTy->getBitWidth() &&
2021 "Casting vector to floating point of different width");
2022 return BitCast; // same size, no-op cast
2024 assert(0 && "Casting pointer or non-first class to float");
2026 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2027 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2028 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2029 "Casting vector to vector of different widths");
2030 return BitCast; // vector -> vector
2031 } else if (DestPTy->getBitWidth() == SrcBits) {
2032 return BitCast; // float/int -> vector
2034 assert(!"Illegal cast to vector (wrong type or size)");
2036 } else if (isa<PointerType>(DestTy)) {
2037 if (isa<PointerType>(SrcTy)) {
2038 return BitCast; // ptr -> ptr
2039 } else if (SrcTy->isInteger()) {
2040 return IntToPtr; // int -> ptr
2042 assert(!"Casting pointer to other than pointer or int");
2045 assert(!"Casting to type that is not first-class");
2048 // If we fall through to here we probably hit an assertion cast above
2049 // and assertions are not turned on. Anything we return is an error, so
2050 // BitCast is as good a choice as any.
2054 //===----------------------------------------------------------------------===//
2055 // CastInst SubClass Constructors
2056 //===----------------------------------------------------------------------===//
2058 /// Check that the construction parameters for a CastInst are correct. This
2059 /// could be broken out into the separate constructors but it is useful to have
2060 /// it in one place and to eliminate the redundant code for getting the sizes
2061 /// of the types involved.
2063 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2065 // Check for type sanity on the arguments
2066 const Type *SrcTy = S->getType();
2067 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2070 // Get the size of the types in bits, we'll need this later
2071 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2072 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2074 // Switch on the opcode provided
2076 default: return false; // This is an input error
2077 case Instruction::Trunc:
2078 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2079 case Instruction::ZExt:
2080 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2081 case Instruction::SExt:
2082 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2083 case Instruction::FPTrunc:
2084 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2085 SrcBitSize > DstBitSize;
2086 case Instruction::FPExt:
2087 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2088 SrcBitSize < DstBitSize;
2089 case Instruction::UIToFP:
2090 case Instruction::SIToFP:
2091 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2092 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2093 return SVTy->getElementType()->isInteger() &&
2094 DVTy->getElementType()->isFloatingPoint() &&
2095 SVTy->getNumElements() == DVTy->getNumElements();
2098 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2099 case Instruction::FPToUI:
2100 case Instruction::FPToSI:
2101 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2102 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2103 return SVTy->getElementType()->isFloatingPoint() &&
2104 DVTy->getElementType()->isInteger() &&
2105 SVTy->getNumElements() == DVTy->getNumElements();
2108 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2109 case Instruction::PtrToInt:
2110 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2111 case Instruction::IntToPtr:
2112 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2113 case Instruction::BitCast:
2114 // BitCast implies a no-op cast of type only. No bits change.
2115 // However, you can't cast pointers to anything but pointers.
2116 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2119 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2120 // these cases, the cast is okay if the source and destination bit widths
2122 return SrcBitSize == DstBitSize;
2126 TruncInst::TruncInst(
2127 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2128 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2129 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2132 TruncInst::TruncInst(
2133 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2134 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2135 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2139 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2140 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2141 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2145 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2146 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2147 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2150 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2151 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2152 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2156 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2157 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2158 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2161 FPTruncInst::FPTruncInst(
2162 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2163 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2164 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2167 FPTruncInst::FPTruncInst(
2168 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2169 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2170 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2173 FPExtInst::FPExtInst(
2174 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2175 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2176 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2179 FPExtInst::FPExtInst(
2180 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2181 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2182 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2185 UIToFPInst::UIToFPInst(
2186 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2187 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2188 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2191 UIToFPInst::UIToFPInst(
2192 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2193 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2194 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2197 SIToFPInst::SIToFPInst(
2198 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2199 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2200 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2203 SIToFPInst::SIToFPInst(
2204 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2205 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2206 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2209 FPToUIInst::FPToUIInst(
2210 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2211 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2212 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2215 FPToUIInst::FPToUIInst(
2216 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2217 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2218 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2221 FPToSIInst::FPToSIInst(
2222 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2223 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2224 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2227 FPToSIInst::FPToSIInst(
2228 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2229 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2230 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2233 PtrToIntInst::PtrToIntInst(
2234 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2235 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2236 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2239 PtrToIntInst::PtrToIntInst(
2240 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2241 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2242 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2245 IntToPtrInst::IntToPtrInst(
2246 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2247 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2248 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2251 IntToPtrInst::IntToPtrInst(
2252 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2253 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2254 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2257 BitCastInst::BitCastInst(
2258 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2259 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2260 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2263 BitCastInst::BitCastInst(
2264 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2265 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2266 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2269 //===----------------------------------------------------------------------===//
2271 //===----------------------------------------------------------------------===//
2273 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2274 const std::string &Name, Instruction *InsertBefore)
2275 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2276 Ops[0].init(LHS, this);
2277 Ops[1].init(RHS, this);
2278 SubclassData = predicate;
2280 if (op == Instruction::ICmp) {
2281 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2282 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2283 "Invalid ICmp predicate value");
2284 const Type* Op0Ty = getOperand(0)->getType();
2285 const Type* Op1Ty = getOperand(1)->getType();
2286 assert(Op0Ty == Op1Ty &&
2287 "Both operands to ICmp instruction are not of the same type!");
2288 // Check that the operands are the right type
2289 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2290 "Invalid operand types for ICmp instruction");
2293 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2294 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2295 "Invalid FCmp predicate value");
2296 const Type* Op0Ty = getOperand(0)->getType();
2297 const Type* Op1Ty = getOperand(1)->getType();
2298 assert(Op0Ty == Op1Ty &&
2299 "Both operands to FCmp instruction are not of the same type!");
2300 // Check that the operands are the right type
2301 assert(Op0Ty->isFloatingPoint() &&
2302 "Invalid operand types for FCmp instruction");
2305 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2306 const std::string &Name, BasicBlock *InsertAtEnd)
2307 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2308 Ops[0].init(LHS, this);
2309 Ops[1].init(RHS, this);
2310 SubclassData = predicate;
2312 if (op == Instruction::ICmp) {
2313 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2314 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2315 "Invalid ICmp predicate value");
2317 const Type* Op0Ty = getOperand(0)->getType();
2318 const Type* Op1Ty = getOperand(1)->getType();
2319 assert(Op0Ty == Op1Ty &&
2320 "Both operands to ICmp instruction are not of the same type!");
2321 // Check that the operands are the right type
2322 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2323 "Invalid operand types for ICmp instruction");
2326 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2327 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2328 "Invalid FCmp predicate value");
2329 const Type* Op0Ty = getOperand(0)->getType();
2330 const Type* Op1Ty = getOperand(1)->getType();
2331 assert(Op0Ty == Op1Ty &&
2332 "Both operands to FCmp instruction are not of the same type!");
2333 // Check that the operands are the right type
2334 assert(Op0Ty->isFloatingPoint() &&
2335 "Invalid operand types for FCmp instruction");
2339 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2340 const std::string &Name, Instruction *InsertBefore) {
2341 if (Op == Instruction::ICmp) {
2342 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2345 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2350 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2351 const std::string &Name, BasicBlock *InsertAtEnd) {
2352 if (Op == Instruction::ICmp) {
2353 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2356 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2360 void CmpInst::swapOperands() {
2361 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2364 cast<FCmpInst>(this)->swapOperands();
2367 bool CmpInst::isCommutative() {
2368 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2369 return IC->isCommutative();
2370 return cast<FCmpInst>(this)->isCommutative();
2373 bool CmpInst::isEquality() {
2374 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2375 return IC->isEquality();
2376 return cast<FCmpInst>(this)->isEquality();
2380 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2383 assert(!"Unknown icmp predicate!");
2384 case ICMP_EQ: return ICMP_NE;
2385 case ICMP_NE: return ICMP_EQ;
2386 case ICMP_UGT: return ICMP_ULE;
2387 case ICMP_ULT: return ICMP_UGE;
2388 case ICMP_UGE: return ICMP_ULT;
2389 case ICMP_ULE: return ICMP_UGT;
2390 case ICMP_SGT: return ICMP_SLE;
2391 case ICMP_SLT: return ICMP_SGE;
2392 case ICMP_SGE: return ICMP_SLT;
2393 case ICMP_SLE: return ICMP_SGT;
2397 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2399 default: assert(! "Unknown icmp predicate!");
2400 case ICMP_EQ: case ICMP_NE:
2402 case ICMP_SGT: return ICMP_SLT;
2403 case ICMP_SLT: return ICMP_SGT;
2404 case ICMP_SGE: return ICMP_SLE;
2405 case ICMP_SLE: return ICMP_SGE;
2406 case ICMP_UGT: return ICMP_ULT;
2407 case ICMP_ULT: return ICMP_UGT;
2408 case ICMP_UGE: return ICMP_ULE;
2409 case ICMP_ULE: return ICMP_UGE;
2413 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2415 default: assert(! "Unknown icmp predicate!");
2416 case ICMP_EQ: case ICMP_NE:
2417 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2419 case ICMP_UGT: return ICMP_SGT;
2420 case ICMP_ULT: return ICMP_SLT;
2421 case ICMP_UGE: return ICMP_SGE;
2422 case ICMP_ULE: return ICMP_SLE;
2426 bool ICmpInst::isSignedPredicate(Predicate pred) {
2428 default: assert(! "Unknown icmp predicate!");
2429 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2431 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2432 case ICMP_UGE: case ICMP_ULE:
2437 /// Initialize a set of values that all satisfy the condition with C.
2440 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2443 uint32_t BitWidth = C.getBitWidth();
2445 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2446 case ICmpInst::ICMP_EQ: Upper++; break;
2447 case ICmpInst::ICMP_NE: Lower++; break;
2448 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2449 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2450 case ICmpInst::ICMP_UGT:
2451 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2453 case ICmpInst::ICMP_SGT:
2454 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2456 case ICmpInst::ICMP_ULE:
2457 Lower = APInt::getMinValue(BitWidth); Upper++;
2459 case ICmpInst::ICMP_SLE:
2460 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2462 case ICmpInst::ICMP_UGE:
2463 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2465 case ICmpInst::ICMP_SGE:
2466 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2469 return ConstantRange(Lower, Upper);
2472 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2475 assert(!"Unknown icmp predicate!");
2476 case FCMP_OEQ: return FCMP_UNE;
2477 case FCMP_ONE: return FCMP_UEQ;
2478 case FCMP_OGT: return FCMP_ULE;
2479 case FCMP_OLT: return FCMP_UGE;
2480 case FCMP_OGE: return FCMP_ULT;
2481 case FCMP_OLE: return FCMP_UGT;
2482 case FCMP_UEQ: return FCMP_ONE;
2483 case FCMP_UNE: return FCMP_OEQ;
2484 case FCMP_UGT: return FCMP_OLE;
2485 case FCMP_ULT: return FCMP_OGE;
2486 case FCMP_UGE: return FCMP_OLT;
2487 case FCMP_ULE: return FCMP_OGT;
2488 case FCMP_ORD: return FCMP_UNO;
2489 case FCMP_UNO: return FCMP_ORD;
2490 case FCMP_TRUE: return FCMP_FALSE;
2491 case FCMP_FALSE: return FCMP_TRUE;
2495 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2497 default: assert(!"Unknown fcmp predicate!");
2498 case FCMP_FALSE: case FCMP_TRUE:
2499 case FCMP_OEQ: case FCMP_ONE:
2500 case FCMP_UEQ: case FCMP_UNE:
2501 case FCMP_ORD: case FCMP_UNO:
2503 case FCMP_OGT: return FCMP_OLT;
2504 case FCMP_OLT: return FCMP_OGT;
2505 case FCMP_OGE: return FCMP_OLE;
2506 case FCMP_OLE: return FCMP_OGE;
2507 case FCMP_UGT: return FCMP_ULT;
2508 case FCMP_ULT: return FCMP_UGT;
2509 case FCMP_UGE: return FCMP_ULE;
2510 case FCMP_ULE: return FCMP_UGE;
2514 bool CmpInst::isUnsigned(unsigned short predicate) {
2515 switch (predicate) {
2516 default: return false;
2517 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2518 case ICmpInst::ICMP_UGE: return true;
2522 bool CmpInst::isSigned(unsigned short predicate){
2523 switch (predicate) {
2524 default: return false;
2525 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2526 case ICmpInst::ICMP_SGE: return true;
2530 bool CmpInst::isOrdered(unsigned short predicate) {
2531 switch (predicate) {
2532 default: return false;
2533 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2534 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2535 case FCmpInst::FCMP_ORD: return true;
2539 bool CmpInst::isUnordered(unsigned short predicate) {
2540 switch (predicate) {
2541 default: return false;
2542 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2543 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2544 case FCmpInst::FCMP_UNO: return true;
2548 //===----------------------------------------------------------------------===//
2549 // SwitchInst Implementation
2550 //===----------------------------------------------------------------------===//
2552 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2553 assert(Value && Default);
2554 ReservedSpace = 2+NumCases*2;
2556 OperandList = new Use[ReservedSpace];
2558 OperandList[0].init(Value, this);
2559 OperandList[1].init(Default, this);
2562 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2563 /// switch on and a default destination. The number of additional cases can
2564 /// be specified here to make memory allocation more efficient. This
2565 /// constructor can also autoinsert before another instruction.
2566 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2567 Instruction *InsertBefore)
2568 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2569 init(Value, Default, NumCases);
2572 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2573 /// switch on and a default destination. The number of additional cases can
2574 /// be specified here to make memory allocation more efficient. This
2575 /// constructor also autoinserts at the end of the specified BasicBlock.
2576 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2577 BasicBlock *InsertAtEnd)
2578 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2579 init(Value, Default, NumCases);
2582 SwitchInst::SwitchInst(const SwitchInst &SI)
2583 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2584 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2585 Use *OL = OperandList, *InOL = SI.OperandList;
2586 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2587 OL[i].init(InOL[i], this);
2588 OL[i+1].init(InOL[i+1], this);
2592 SwitchInst::~SwitchInst() {
2593 delete [] OperandList;
2597 /// addCase - Add an entry to the switch instruction...
2599 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2600 unsigned OpNo = NumOperands;
2601 if (OpNo+2 > ReservedSpace)
2602 resizeOperands(0); // Get more space!
2603 // Initialize some new operands.
2604 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2605 NumOperands = OpNo+2;
2606 OperandList[OpNo].init(OnVal, this);
2607 OperandList[OpNo+1].init(Dest, this);
2610 /// removeCase - This method removes the specified successor from the switch
2611 /// instruction. Note that this cannot be used to remove the default
2612 /// destination (successor #0).
2614 void SwitchInst::removeCase(unsigned idx) {
2615 assert(idx != 0 && "Cannot remove the default case!");
2616 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2618 unsigned NumOps = getNumOperands();
2619 Use *OL = OperandList;
2621 // Move everything after this operand down.
2623 // FIXME: we could just swap with the end of the list, then erase. However,
2624 // client might not expect this to happen. The code as it is thrashes the
2625 // use/def lists, which is kinda lame.
2626 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2628 OL[i-2+1] = OL[i+1];
2631 // Nuke the last value.
2632 OL[NumOps-2].set(0);
2633 OL[NumOps-2+1].set(0);
2634 NumOperands = NumOps-2;
2637 /// resizeOperands - resize operands - This adjusts the length of the operands
2638 /// list according to the following behavior:
2639 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2640 /// of operation. This grows the number of ops by 1.5 times.
2641 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2642 /// 3. If NumOps == NumOperands, trim the reserved space.
2644 void SwitchInst::resizeOperands(unsigned NumOps) {
2646 NumOps = getNumOperands()/2*6;
2647 } else if (NumOps*2 > NumOperands) {
2648 // No resize needed.
2649 if (ReservedSpace >= NumOps) return;
2650 } else if (NumOps == NumOperands) {
2651 if (ReservedSpace == NumOps) return;
2656 ReservedSpace = NumOps;
2657 Use *NewOps = new Use[NumOps];
2658 Use *OldOps = OperandList;
2659 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2660 NewOps[i].init(OldOps[i], this);
2664 OperandList = NewOps;
2668 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2669 return getSuccessor(idx);
2671 unsigned SwitchInst::getNumSuccessorsV() const {
2672 return getNumSuccessors();
2674 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2675 setSuccessor(idx, B);
2679 // Define these methods here so vtables don't get emitted into every translation
2680 // unit that uses these classes.
2682 GetElementPtrInst *GetElementPtrInst::clone() const {
2683 return new GetElementPtrInst(*this);
2686 BinaryOperator *BinaryOperator::clone() const {
2687 return create(getOpcode(), Ops[0], Ops[1]);
2690 FCmpInst* FCmpInst::clone() const {
2691 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2693 ICmpInst* ICmpInst::clone() const {
2694 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2697 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2698 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2699 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2700 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2701 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2702 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2703 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2704 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2705 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2706 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2707 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2708 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2709 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2710 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2711 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2712 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2713 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2714 CallInst *CallInst::clone() const { return new CallInst(*this); }
2715 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2716 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2718 ExtractElementInst *ExtractElementInst::clone() const {
2719 return new ExtractElementInst(*this);
2721 InsertElementInst *InsertElementInst::clone() const {
2722 return new InsertElementInst(*this);
2724 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2725 return new ShuffleVectorInst(*this);
2727 PHINode *PHINode::clone() const { return new PHINode(*this); }
2728 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2729 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2730 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2731 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2732 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2733 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}