1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Support/CallSite.h"
21 #include "llvm/Support/ConstantRange.h"
22 #include "llvm/Support/MathExtras.h"
25 //===----------------------------------------------------------------------===//
27 //===----------------------------------------------------------------------===//
29 CallSite::CallSite(Instruction *C) {
30 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
33 unsigned CallSite::getCallingConv() const {
34 if (CallInst *CI = dyn_cast<CallInst>(I))
35 return CI->getCallingConv();
37 return cast<InvokeInst>(I)->getCallingConv();
39 void CallSite::setCallingConv(unsigned CC) {
40 if (CallInst *CI = dyn_cast<CallInst>(I))
41 CI->setCallingConv(CC);
43 cast<InvokeInst>(I)->setCallingConv(CC);
45 const PAListPtr &CallSite::getParamAttrs() const {
46 if (CallInst *CI = dyn_cast<CallInst>(I))
47 return CI->getParamAttrs();
49 return cast<InvokeInst>(I)->getParamAttrs();
51 void CallSite::setParamAttrs(const PAListPtr &PAL) {
52 if (CallInst *CI = dyn_cast<CallInst>(I))
53 CI->setParamAttrs(PAL);
55 cast<InvokeInst>(I)->setParamAttrs(PAL);
57 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
58 if (CallInst *CI = dyn_cast<CallInst>(I))
59 return CI->paramHasAttr(i, attr);
61 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
63 uint16_t CallSite::getParamAlignment(uint16_t i) const {
64 if (CallInst *CI = dyn_cast<CallInst>(I))
65 return CI->getParamAlignment(i);
67 return cast<InvokeInst>(I)->getParamAlignment(i);
70 bool CallSite::doesNotAccessMemory() const {
71 if (CallInst *CI = dyn_cast<CallInst>(I))
72 return CI->doesNotAccessMemory();
74 return cast<InvokeInst>(I)->doesNotAccessMemory();
76 bool CallSite::onlyReadsMemory() const {
77 if (CallInst *CI = dyn_cast<CallInst>(I))
78 return CI->onlyReadsMemory();
80 return cast<InvokeInst>(I)->onlyReadsMemory();
82 bool CallSite::doesNotThrow() const {
83 if (CallInst *CI = dyn_cast<CallInst>(I))
84 return CI->doesNotThrow();
86 return cast<InvokeInst>(I)->doesNotThrow();
88 void CallSite::setDoesNotThrow(bool doesNotThrow) {
89 if (CallInst *CI = dyn_cast<CallInst>(I))
90 CI->setDoesNotThrow(doesNotThrow);
92 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
95 //===----------------------------------------------------------------------===//
96 // TerminatorInst Class
97 //===----------------------------------------------------------------------===//
99 // Out of line virtual method, so the vtable, etc has a home.
100 TerminatorInst::~TerminatorInst() {
103 // Out of line virtual method, so the vtable, etc has a home.
104 UnaryInstruction::~UnaryInstruction() {
108 //===----------------------------------------------------------------------===//
110 //===----------------------------------------------------------------------===//
112 PHINode::PHINode(const PHINode &PN)
113 : Instruction(PN.getType(), Instruction::PHI,
114 new Use[PN.getNumOperands()], PN.getNumOperands()),
115 ReservedSpace(PN.getNumOperands()) {
116 Use *OL = OperandList;
117 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
118 OL[i].init(PN.getOperand(i), this);
119 OL[i+1].init(PN.getOperand(i+1), this);
123 PHINode::~PHINode() {
124 delete [] OperandList;
127 // removeIncomingValue - Remove an incoming value. This is useful if a
128 // predecessor basic block is deleted.
129 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
130 unsigned NumOps = getNumOperands();
131 Use *OL = OperandList;
132 assert(Idx*2 < NumOps && "BB not in PHI node!");
133 Value *Removed = OL[Idx*2];
135 // Move everything after this operand down.
137 // FIXME: we could just swap with the end of the list, then erase. However,
138 // client might not expect this to happen. The code as it is thrashes the
139 // use/def lists, which is kinda lame.
140 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
145 // Nuke the last value.
147 OL[NumOps-2+1].set(0);
148 NumOperands = NumOps-2;
150 // If the PHI node is dead, because it has zero entries, nuke it now.
151 if (NumOps == 2 && DeletePHIIfEmpty) {
152 // If anyone is using this PHI, make them use a dummy value instead...
153 replaceAllUsesWith(UndefValue::get(getType()));
159 /// resizeOperands - resize operands - This adjusts the length of the operands
160 /// list according to the following behavior:
161 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
162 /// of operation. This grows the number of ops by 1.5 times.
163 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
164 /// 3. If NumOps == NumOperands, trim the reserved space.
166 void PHINode::resizeOperands(unsigned NumOps) {
168 NumOps = (getNumOperands())*3/2;
169 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
170 } else if (NumOps*2 > NumOperands) {
172 if (ReservedSpace >= NumOps) return;
173 } else if (NumOps == NumOperands) {
174 if (ReservedSpace == NumOps) return;
179 ReservedSpace = NumOps;
180 Use *NewOps = new Use[NumOps];
181 Use *OldOps = OperandList;
182 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
183 NewOps[i].init(OldOps[i], this);
187 OperandList = NewOps;
190 /// hasConstantValue - If the specified PHI node always merges together the same
191 /// value, return the value, otherwise return null.
193 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
194 // If the PHI node only has one incoming value, eliminate the PHI node...
195 if (getNumIncomingValues() == 1) {
196 if (getIncomingValue(0) != this) // not X = phi X
197 return getIncomingValue(0);
199 return UndefValue::get(getType()); // Self cycle is dead.
202 // Otherwise if all of the incoming values are the same for the PHI, replace
203 // the PHI node with the incoming value.
206 bool HasUndefInput = false;
207 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
208 if (isa<UndefValue>(getIncomingValue(i))) {
209 HasUndefInput = true;
210 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
211 if (InVal && getIncomingValue(i) != InVal)
212 return 0; // Not the same, bail out.
214 InVal = getIncomingValue(i);
217 // The only case that could cause InVal to be null is if we have a PHI node
218 // that only has entries for itself. In this case, there is no entry into the
219 // loop, so kill the PHI.
221 if (InVal == 0) InVal = UndefValue::get(getType());
223 // If we have a PHI node like phi(X, undef, X), where X is defined by some
224 // instruction, we cannot always return X as the result of the PHI node. Only
225 // do this if X is not an instruction (thus it must dominate the PHI block),
226 // or if the client is prepared to deal with this possibility.
227 if (HasUndefInput && !AllowNonDominatingInstruction)
228 if (Instruction *IV = dyn_cast<Instruction>(InVal))
229 // If it's in the entry block, it dominates everything.
230 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
232 return 0; // Cannot guarantee that InVal dominates this PHINode.
234 // All of the incoming values are the same, return the value now.
239 //===----------------------------------------------------------------------===//
240 // CallInst Implementation
241 //===----------------------------------------------------------------------===//
243 CallInst::~CallInst() {
244 delete [] OperandList;
247 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
248 NumOperands = NumParams+1;
249 Use *OL = OperandList = new Use[NumParams+1];
250 OL[0].init(Func, this);
252 const FunctionType *FTy =
253 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
254 FTy = FTy; // silence warning.
256 assert((NumParams == FTy->getNumParams() ||
257 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
258 "Calling a function with bad signature!");
259 for (unsigned i = 0; i != NumParams; ++i) {
260 assert((i >= FTy->getNumParams() ||
261 FTy->getParamType(i) == Params[i]->getType()) &&
262 "Calling a function with a bad signature!");
263 OL[i+1].init(Params[i], this);
267 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
269 Use *OL = OperandList = new Use[3];
270 OL[0].init(Func, this);
271 OL[1].init(Actual1, this);
272 OL[2].init(Actual2, this);
274 const FunctionType *FTy =
275 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
276 FTy = FTy; // silence warning.
278 assert((FTy->getNumParams() == 2 ||
279 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
280 "Calling a function with bad signature");
281 assert((0 >= FTy->getNumParams() ||
282 FTy->getParamType(0) == Actual1->getType()) &&
283 "Calling a function with a bad signature!");
284 assert((1 >= FTy->getNumParams() ||
285 FTy->getParamType(1) == Actual2->getType()) &&
286 "Calling a function with a bad signature!");
289 void CallInst::init(Value *Func, Value *Actual) {
291 Use *OL = OperandList = new Use[2];
292 OL[0].init(Func, this);
293 OL[1].init(Actual, this);
295 const FunctionType *FTy =
296 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
297 FTy = FTy; // silence warning.
299 assert((FTy->getNumParams() == 1 ||
300 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
301 "Calling a function with bad signature");
302 assert((0 == FTy->getNumParams() ||
303 FTy->getParamType(0) == Actual->getType()) &&
304 "Calling a function with a bad signature!");
307 void CallInst::init(Value *Func) {
309 Use *OL = OperandList = new Use[1];
310 OL[0].init(Func, this);
312 const FunctionType *FTy =
313 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
314 FTy = FTy; // silence warning.
316 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
319 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
320 Instruction *InsertBefore)
321 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
322 ->getElementType())->getReturnType(),
323 Instruction::Call, 0, 0, InsertBefore) {
328 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
329 BasicBlock *InsertAtEnd)
330 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
331 ->getElementType())->getReturnType(),
332 Instruction::Call, 0, 0, InsertAtEnd) {
336 CallInst::CallInst(Value *Func, const std::string &Name,
337 Instruction *InsertBefore)
338 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
339 ->getElementType())->getReturnType(),
340 Instruction::Call, 0, 0, InsertBefore) {
345 CallInst::CallInst(Value *Func, const std::string &Name,
346 BasicBlock *InsertAtEnd)
347 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
348 ->getElementType())->getReturnType(),
349 Instruction::Call, 0, 0, InsertAtEnd) {
354 CallInst::CallInst(const CallInst &CI)
355 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
356 CI.getNumOperands()) {
357 setParamAttrs(CI.getParamAttrs());
358 SubclassData = CI.SubclassData;
359 Use *OL = OperandList;
360 Use *InOL = CI.OperandList;
361 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
362 OL[i].init(InOL[i], this);
365 bool CallInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
366 if (ParamAttrs.paramHasAttr(i, attr))
368 if (const Function *F = getCalledFunction())
369 return F->paramHasAttr(i, attr);
373 uint16_t CallInst::getParamAlignment(uint16_t i) const {
374 return ParamAttrs.getParamAlignment(i);
377 /// @brief Determine if the call does not access memory.
378 bool CallInst::doesNotAccessMemory() const {
379 return paramHasAttr(0, ParamAttr::ReadNone);
382 /// @brief Determine if the call does not access or only reads memory.
383 bool CallInst::onlyReadsMemory() const {
384 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
387 /// @brief Determine if the call cannot return.
388 bool CallInst::doesNotReturn() const {
389 return paramHasAttr(0, ParamAttr::NoReturn);
392 /// @brief Determine if the call cannot unwind.
393 bool CallInst::doesNotThrow() const {
394 return paramHasAttr(0, ParamAttr::NoUnwind);
397 /// @brief Determine if the call returns a structure through first
398 /// pointer argument.
399 bool CallInst::hasStructRetAttr() const {
400 // Be friendly and also check the callee.
401 return paramHasAttr(1, ParamAttr::StructRet);
404 /// @brief Determine if any call argument is an aggregate passed by value.
405 bool CallInst::hasByValArgument() const {
406 if (ParamAttrs.hasAttrSomewhere(ParamAttr::ByVal))
408 // Be consistent with other methods and check the callee too.
409 if (const Function *F = getCalledFunction())
410 return F->getParamAttrs().hasAttrSomewhere(ParamAttr::ByVal);
414 void CallInst::setDoesNotThrow(bool doesNotThrow) {
415 PAListPtr PAL = getParamAttrs();
417 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
419 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
424 //===----------------------------------------------------------------------===//
425 // InvokeInst Implementation
426 //===----------------------------------------------------------------------===//
428 InvokeInst::~InvokeInst() {
429 delete [] OperandList;
432 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
433 Value* const *Args, unsigned NumArgs) {
434 NumOperands = 3+NumArgs;
435 Use *OL = OperandList = new Use[3+NumArgs];
436 OL[0].init(Fn, this);
437 OL[1].init(IfNormal, this);
438 OL[2].init(IfException, this);
439 const FunctionType *FTy =
440 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
441 FTy = FTy; // silence warning.
443 assert(((NumArgs == FTy->getNumParams()) ||
444 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
445 "Calling a function with bad signature");
447 for (unsigned i = 0, e = NumArgs; i != e; i++) {
448 assert((i >= FTy->getNumParams() ||
449 FTy->getParamType(i) == Args[i]->getType()) &&
450 "Invoking a function with a bad signature!");
452 OL[i+3].init(Args[i], this);
456 InvokeInst::InvokeInst(const InvokeInst &II)
457 : TerminatorInst(II.getType(), Instruction::Invoke,
458 new Use[II.getNumOperands()], II.getNumOperands()) {
459 setParamAttrs(II.getParamAttrs());
460 SubclassData = II.SubclassData;
461 Use *OL = OperandList, *InOL = II.OperandList;
462 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
463 OL[i].init(InOL[i], this);
466 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
467 return getSuccessor(idx);
469 unsigned InvokeInst::getNumSuccessorsV() const {
470 return getNumSuccessors();
472 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
473 return setSuccessor(idx, B);
476 bool InvokeInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
477 if (ParamAttrs.paramHasAttr(i, attr))
479 if (const Function *F = getCalledFunction())
480 return F->paramHasAttr(i, attr);
484 uint16_t InvokeInst::getParamAlignment(uint16_t i) const {
485 return ParamAttrs.getParamAlignment(i);
488 /// @brief Determine if the call does not access memory.
489 bool InvokeInst::doesNotAccessMemory() const {
490 return paramHasAttr(0, ParamAttr::ReadNone);
493 /// @brief Determine if the call does not access or only reads memory.
494 bool InvokeInst::onlyReadsMemory() const {
495 return doesNotAccessMemory() || paramHasAttr(0, ParamAttr::ReadOnly);
498 /// @brief Determine if the call cannot return.
499 bool InvokeInst::doesNotReturn() const {
500 return paramHasAttr(0, ParamAttr::NoReturn);
503 /// @brief Determine if the call cannot unwind.
504 bool InvokeInst::doesNotThrow() const {
505 return paramHasAttr(0, ParamAttr::NoUnwind);
508 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
509 PAListPtr PAL = getParamAttrs();
511 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
513 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
517 /// @brief Determine if the invoke returns a structure through first
518 /// pointer argument.
519 bool InvokeInst::hasStructRetAttr() const {
520 // Be friendly and also check the callee.
521 return paramHasAttr(1, ParamAttr::StructRet);
525 //===----------------------------------------------------------------------===//
526 // ReturnInst Implementation
527 //===----------------------------------------------------------------------===//
529 ReturnInst::ReturnInst(const ReturnInst &RI)
530 : TerminatorInst(Type::VoidTy, Instruction::Ret,
531 &RetVal, RI.getNumOperands()) {
532 unsigned N = RI.getNumOperands();
534 RetVal.init(RI.RetVal, this);
536 Use *OL = OperandList = new Use[N];
537 for (unsigned i = 0; i < N; ++i)
538 OL[i].init(RI.getOperand(i), this);
542 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
543 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
547 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
548 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
552 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
553 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
556 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
557 Instruction *InsertBefore)
558 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N, InsertBefore) {
562 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
563 BasicBlock *InsertAtEnd)
564 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N, InsertAtEnd) {
568 ReturnInst::ReturnInst(Value * const* retVals, unsigned N)
569 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N) {
574 void ReturnInst::init(Value * const* retVals, unsigned N) {
575 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
578 if (NumOperands == 1) {
580 if (V->getType() == Type::VoidTy)
582 RetVal.init(V, this);
586 Use *OL = OperandList = new Use[NumOperands];
587 for (unsigned i = 0; i < NumOperands; ++i) {
588 Value *V = *retVals++;
589 assert(!isa<BasicBlock>(V) &&
590 "Cannot return basic block. Probably using the incorrect ctor");
595 unsigned ReturnInst::getNumSuccessorsV() const {
596 return getNumSuccessors();
599 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
600 /// emit the vtable for the class in this translation unit.
601 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
602 assert(0 && "ReturnInst has no successors!");
605 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
606 assert(0 && "ReturnInst has no successors!");
611 ReturnInst::~ReturnInst() {
613 delete [] OperandList;
616 //===----------------------------------------------------------------------===//
617 // UnwindInst Implementation
618 //===----------------------------------------------------------------------===//
620 UnwindInst::UnwindInst(Instruction *InsertBefore)
621 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
623 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
624 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
628 unsigned UnwindInst::getNumSuccessorsV() const {
629 return getNumSuccessors();
632 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
633 assert(0 && "UnwindInst has no successors!");
636 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
637 assert(0 && "UnwindInst has no successors!");
642 //===----------------------------------------------------------------------===//
643 // UnreachableInst Implementation
644 //===----------------------------------------------------------------------===//
646 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
647 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
649 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
650 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
653 unsigned UnreachableInst::getNumSuccessorsV() const {
654 return getNumSuccessors();
657 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
658 assert(0 && "UnwindInst has no successors!");
661 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
662 assert(0 && "UnwindInst has no successors!");
667 //===----------------------------------------------------------------------===//
668 // BranchInst Implementation
669 //===----------------------------------------------------------------------===//
671 void BranchInst::AssertOK() {
673 assert(getCondition()->getType() == Type::Int1Ty &&
674 "May only branch on boolean predicates!");
677 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
678 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
679 assert(IfTrue != 0 && "Branch destination may not be null!");
680 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
682 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
683 Instruction *InsertBefore)
684 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
685 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
686 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
687 Ops[2].init(Cond, this);
693 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
694 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
695 assert(IfTrue != 0 && "Branch destination may not be null!");
696 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
699 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
700 BasicBlock *InsertAtEnd)
701 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
702 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
703 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
704 Ops[2].init(Cond, this);
711 BranchInst::BranchInst(const BranchInst &BI) :
712 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
713 OperandList[0].init(BI.getOperand(0), this);
714 if (BI.getNumOperands() != 1) {
715 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
716 OperandList[1].init(BI.getOperand(1), this);
717 OperandList[2].init(BI.getOperand(2), this);
721 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
722 return getSuccessor(idx);
724 unsigned BranchInst::getNumSuccessorsV() const {
725 return getNumSuccessors();
727 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
728 setSuccessor(idx, B);
732 //===----------------------------------------------------------------------===//
733 // AllocationInst Implementation
734 //===----------------------------------------------------------------------===//
736 static Value *getAISize(Value *Amt) {
738 Amt = ConstantInt::get(Type::Int32Ty, 1);
740 assert(!isa<BasicBlock>(Amt) &&
741 "Passed basic block into allocation size parameter! Use other ctor");
742 assert(Amt->getType() == Type::Int32Ty &&
743 "Malloc/Allocation array size is not a 32-bit integer!");
748 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
749 unsigned Align, const std::string &Name,
750 Instruction *InsertBefore)
751 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
752 InsertBefore), Alignment(Align) {
753 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
754 assert(Ty != Type::VoidTy && "Cannot allocate void!");
758 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
759 unsigned Align, const std::string &Name,
760 BasicBlock *InsertAtEnd)
761 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
762 InsertAtEnd), Alignment(Align) {
763 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
764 assert(Ty != Type::VoidTy && "Cannot allocate void!");
768 // Out of line virtual method, so the vtable, etc has a home.
769 AllocationInst::~AllocationInst() {
772 bool AllocationInst::isArrayAllocation() const {
773 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
774 return CI->getZExtValue() != 1;
778 const Type *AllocationInst::getAllocatedType() const {
779 return getType()->getElementType();
782 AllocaInst::AllocaInst(const AllocaInst &AI)
783 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
784 Instruction::Alloca, AI.getAlignment()) {
787 MallocInst::MallocInst(const MallocInst &MI)
788 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
789 Instruction::Malloc, MI.getAlignment()) {
792 //===----------------------------------------------------------------------===//
793 // FreeInst Implementation
794 //===----------------------------------------------------------------------===//
796 void FreeInst::AssertOK() {
797 assert(isa<PointerType>(getOperand(0)->getType()) &&
798 "Can not free something of nonpointer type!");
801 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
802 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
806 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
807 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
812 //===----------------------------------------------------------------------===//
813 // LoadInst Implementation
814 //===----------------------------------------------------------------------===//
816 void LoadInst::AssertOK() {
817 assert(isa<PointerType>(getOperand(0)->getType()) &&
818 "Ptr must have pointer type.");
821 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
822 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
823 Load, Ptr, InsertBef) {
830 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
831 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
832 Load, Ptr, InsertAE) {
839 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
840 Instruction *InsertBef)
841 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
842 Load, Ptr, InsertBef) {
843 setVolatile(isVolatile);
849 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
850 unsigned Align, Instruction *InsertBef)
851 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
852 Load, Ptr, InsertBef) {
853 setVolatile(isVolatile);
859 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
860 unsigned Align, BasicBlock *InsertAE)
861 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
862 Load, Ptr, InsertAE) {
863 setVolatile(isVolatile);
869 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
870 BasicBlock *InsertAE)
871 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
872 Load, Ptr, InsertAE) {
873 setVolatile(isVolatile);
881 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
882 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
883 Load, Ptr, InsertBef) {
887 if (Name && Name[0]) setName(Name);
890 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
891 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
892 Load, Ptr, InsertAE) {
896 if (Name && Name[0]) setName(Name);
899 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
900 Instruction *InsertBef)
901 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
902 Load, Ptr, InsertBef) {
903 setVolatile(isVolatile);
906 if (Name && Name[0]) setName(Name);
909 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
910 BasicBlock *InsertAE)
911 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
912 Load, Ptr, InsertAE) {
913 setVolatile(isVolatile);
916 if (Name && Name[0]) setName(Name);
919 void LoadInst::setAlignment(unsigned Align) {
920 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
921 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
924 //===----------------------------------------------------------------------===//
925 // StoreInst Implementation
926 //===----------------------------------------------------------------------===//
928 void StoreInst::AssertOK() {
929 assert(isa<PointerType>(getOperand(1)->getType()) &&
930 "Ptr must have pointer type!");
931 assert(getOperand(0)->getType() ==
932 cast<PointerType>(getOperand(1)->getType())->getElementType()
933 && "Ptr must be a pointer to Val type!");
937 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
938 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
939 Ops[0].init(val, this);
940 Ops[1].init(addr, this);
946 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
947 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
948 Ops[0].init(val, this);
949 Ops[1].init(addr, this);
955 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
956 Instruction *InsertBefore)
957 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
958 Ops[0].init(val, this);
959 Ops[1].init(addr, this);
960 setVolatile(isVolatile);
965 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
966 unsigned Align, Instruction *InsertBefore)
967 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
968 Ops[0].init(val, this);
969 Ops[1].init(addr, this);
970 setVolatile(isVolatile);
975 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
976 unsigned Align, BasicBlock *InsertAtEnd)
977 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
978 Ops[0].init(val, this);
979 Ops[1].init(addr, this);
980 setVolatile(isVolatile);
985 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
986 BasicBlock *InsertAtEnd)
987 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
988 Ops[0].init(val, this);
989 Ops[1].init(addr, this);
990 setVolatile(isVolatile);
995 void StoreInst::setAlignment(unsigned Align) {
996 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
997 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1000 //===----------------------------------------------------------------------===//
1001 // GetElementPtrInst Implementation
1002 //===----------------------------------------------------------------------===//
1004 static unsigned retrieveAddrSpace(const Value *Val) {
1005 return cast<PointerType>(Val->getType())->getAddressSpace();
1008 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
1009 NumOperands = 1+NumIdx;
1010 Use *OL = OperandList = new Use[NumOperands];
1011 OL[0].init(Ptr, this);
1013 for (unsigned i = 0; i != NumIdx; ++i)
1014 OL[i+1].init(Idx[i], this);
1017 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
1019 Use *OL = OperandList = new Use[2];
1020 OL[0].init(Ptr, this);
1021 OL[1].init(Idx, this);
1024 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1025 const std::string &Name, Instruction *InBe)
1026 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1027 retrieveAddrSpace(Ptr)),
1028 GetElementPtr, 0, 0, InBe) {
1033 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1034 const std::string &Name, BasicBlock *IAE)
1035 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1036 retrieveAddrSpace(Ptr)),
1037 GetElementPtr, 0, 0, IAE) {
1042 GetElementPtrInst::~GetElementPtrInst() {
1043 delete[] OperandList;
1046 // getIndexedType - Returns the type of the element that would be loaded with
1047 // a load instruction with the specified parameters.
1049 // A null type is returned if the indices are invalid for the specified
1052 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1055 bool AllowCompositeLeaf) {
1056 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
1058 // Handle the special case of the empty set index set...
1060 if (AllowCompositeLeaf ||
1061 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
1062 return cast<PointerType>(Ptr)->getElementType();
1067 unsigned CurIdx = 0;
1068 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
1069 if (NumIdx == CurIdx) {
1070 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
1071 return 0; // Can't load a whole structure or array!?!?
1074 Value *Index = Idxs[CurIdx++];
1075 if (isa<PointerType>(CT) && CurIdx != 1)
1076 return 0; // Can only index into pointer types at the first index!
1077 if (!CT->indexValid(Index)) return 0;
1078 Ptr = CT->getTypeAtIndex(Index);
1080 // If the new type forwards to another type, then it is in the middle
1081 // of being refined to another type (and hence, may have dropped all
1082 // references to what it was using before). So, use the new forwarded
1084 if (const Type * Ty = Ptr->getForwardedType()) {
1088 return CurIdx == NumIdx ? Ptr : 0;
1091 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1092 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1093 if (!PTy) return 0; // Type isn't a pointer type!
1095 // Check the pointer index.
1096 if (!PTy->indexValid(Idx)) return 0;
1098 return PTy->getElementType();
1102 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1103 /// zeros. If so, the result pointer and the first operand have the same
1104 /// value, just potentially different types.
1105 bool GetElementPtrInst::hasAllZeroIndices() const {
1106 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1107 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1108 if (!CI->isZero()) return false;
1116 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1117 /// constant integers. If so, the result pointer and the first operand have
1118 /// a constant offset between them.
1119 bool GetElementPtrInst::hasAllConstantIndices() const {
1120 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1121 if (!isa<ConstantInt>(getOperand(i)))
1128 //===----------------------------------------------------------------------===//
1129 // ExtractElementInst Implementation
1130 //===----------------------------------------------------------------------===//
1132 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1133 const std::string &Name,
1134 Instruction *InsertBef)
1135 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1136 ExtractElement, Ops, 2, InsertBef) {
1137 assert(isValidOperands(Val, Index) &&
1138 "Invalid extractelement instruction operands!");
1139 Ops[0].init(Val, this);
1140 Ops[1].init(Index, this);
1144 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1145 const std::string &Name,
1146 Instruction *InsertBef)
1147 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1148 ExtractElement, Ops, 2, InsertBef) {
1149 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1150 assert(isValidOperands(Val, Index) &&
1151 "Invalid extractelement instruction operands!");
1152 Ops[0].init(Val, this);
1153 Ops[1].init(Index, this);
1158 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1159 const std::string &Name,
1160 BasicBlock *InsertAE)
1161 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1162 ExtractElement, Ops, 2, InsertAE) {
1163 assert(isValidOperands(Val, Index) &&
1164 "Invalid extractelement instruction operands!");
1166 Ops[0].init(Val, this);
1167 Ops[1].init(Index, this);
1171 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1172 const std::string &Name,
1173 BasicBlock *InsertAE)
1174 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1175 ExtractElement, Ops, 2, InsertAE) {
1176 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1177 assert(isValidOperands(Val, Index) &&
1178 "Invalid extractelement instruction operands!");
1180 Ops[0].init(Val, this);
1181 Ops[1].init(Index, this);
1186 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1187 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1193 //===----------------------------------------------------------------------===//
1194 // InsertElementInst Implementation
1195 //===----------------------------------------------------------------------===//
1197 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1198 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1199 Ops[0].init(IE.Ops[0], this);
1200 Ops[1].init(IE.Ops[1], this);
1201 Ops[2].init(IE.Ops[2], this);
1203 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1204 const std::string &Name,
1205 Instruction *InsertBef)
1206 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1207 assert(isValidOperands(Vec, Elt, Index) &&
1208 "Invalid insertelement instruction operands!");
1209 Ops[0].init(Vec, this);
1210 Ops[1].init(Elt, this);
1211 Ops[2].init(Index, this);
1215 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1216 const std::string &Name,
1217 Instruction *InsertBef)
1218 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1219 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1220 assert(isValidOperands(Vec, Elt, Index) &&
1221 "Invalid insertelement instruction operands!");
1222 Ops[0].init(Vec, this);
1223 Ops[1].init(Elt, this);
1224 Ops[2].init(Index, this);
1229 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1230 const std::string &Name,
1231 BasicBlock *InsertAE)
1232 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1233 assert(isValidOperands(Vec, Elt, Index) &&
1234 "Invalid insertelement instruction operands!");
1236 Ops[0].init(Vec, this);
1237 Ops[1].init(Elt, this);
1238 Ops[2].init(Index, this);
1242 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1243 const std::string &Name,
1244 BasicBlock *InsertAE)
1245 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1246 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1247 assert(isValidOperands(Vec, Elt, Index) &&
1248 "Invalid insertelement instruction operands!");
1250 Ops[0].init(Vec, this);
1251 Ops[1].init(Elt, this);
1252 Ops[2].init(Index, this);
1256 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1257 const Value *Index) {
1258 if (!isa<VectorType>(Vec->getType()))
1259 return false; // First operand of insertelement must be vector type.
1261 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1262 return false;// Second operand of insertelement must be vector element type.
1264 if (Index->getType() != Type::Int32Ty)
1265 return false; // Third operand of insertelement must be uint.
1270 //===----------------------------------------------------------------------===//
1271 // ShuffleVectorInst Implementation
1272 //===----------------------------------------------------------------------===//
1274 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1275 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1276 Ops[0].init(SV.Ops[0], this);
1277 Ops[1].init(SV.Ops[1], this);
1278 Ops[2].init(SV.Ops[2], this);
1281 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1282 const std::string &Name,
1283 Instruction *InsertBefore)
1284 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1285 assert(isValidOperands(V1, V2, Mask) &&
1286 "Invalid shuffle vector instruction operands!");
1287 Ops[0].init(V1, this);
1288 Ops[1].init(V2, this);
1289 Ops[2].init(Mask, this);
1293 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1294 const std::string &Name,
1295 BasicBlock *InsertAtEnd)
1296 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1297 assert(isValidOperands(V1, V2, Mask) &&
1298 "Invalid shuffle vector instruction operands!");
1300 Ops[0].init(V1, this);
1301 Ops[1].init(V2, this);
1302 Ops[2].init(Mask, this);
1306 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1307 const Value *Mask) {
1308 if (!isa<VectorType>(V1->getType()) ||
1309 V1->getType() != V2->getType())
1312 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1313 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1314 MaskTy->getElementType() != Type::Int32Ty ||
1315 MaskTy->getNumElements() !=
1316 cast<VectorType>(V1->getType())->getNumElements())
1321 /// getMaskValue - Return the index from the shuffle mask for the specified
1322 /// output result. This is either -1 if the element is undef or a number less
1323 /// than 2*numelements.
1324 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1325 const Constant *Mask = cast<Constant>(getOperand(2));
1326 if (isa<UndefValue>(Mask)) return -1;
1327 if (isa<ConstantAggregateZero>(Mask)) return 0;
1328 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1329 assert(i < MaskCV->getNumOperands() && "Index out of range");
1331 if (isa<UndefValue>(MaskCV->getOperand(i)))
1333 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1337 //===----------------------------------------------------------------------===//
1338 // BinaryOperator Class
1339 //===----------------------------------------------------------------------===//
1341 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1342 const Type *Ty, const std::string &Name,
1343 Instruction *InsertBefore)
1344 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1345 Ops[0].init(S1, this);
1346 Ops[1].init(S2, this);
1351 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1352 const Type *Ty, const std::string &Name,
1353 BasicBlock *InsertAtEnd)
1354 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1355 Ops[0].init(S1, this);
1356 Ops[1].init(S2, this);
1362 void BinaryOperator::init(BinaryOps iType) {
1363 Value *LHS = getOperand(0), *RHS = getOperand(1);
1364 LHS = LHS; RHS = RHS; // Silence warnings.
1365 assert(LHS->getType() == RHS->getType() &&
1366 "Binary operator operand types must match!");
1371 assert(getType() == LHS->getType() &&
1372 "Arithmetic operation should return same type as operands!");
1373 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1374 isa<VectorType>(getType())) &&
1375 "Tried to create an arithmetic operation on a non-arithmetic type!");
1379 assert(getType() == LHS->getType() &&
1380 "Arithmetic operation should return same type as operands!");
1381 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1382 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1383 "Incorrect operand type (not integer) for S/UDIV");
1386 assert(getType() == LHS->getType() &&
1387 "Arithmetic operation should return same type as operands!");
1388 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1389 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1390 && "Incorrect operand type (not floating point) for FDIV");
1394 assert(getType() == LHS->getType() &&
1395 "Arithmetic operation should return same type as operands!");
1396 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1397 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1398 "Incorrect operand type (not integer) for S/UREM");
1401 assert(getType() == LHS->getType() &&
1402 "Arithmetic operation should return same type as operands!");
1403 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1404 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1405 && "Incorrect operand type (not floating point) for FREM");
1410 assert(getType() == LHS->getType() &&
1411 "Shift operation should return same type as operands!");
1412 assert(getType()->isInteger() &&
1413 "Shift operation requires integer operands");
1417 assert(getType() == LHS->getType() &&
1418 "Logical operation should return same type as operands!");
1419 assert((getType()->isInteger() ||
1420 (isa<VectorType>(getType()) &&
1421 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1422 "Tried to create a logical operation on a non-integral type!");
1430 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1431 const std::string &Name,
1432 Instruction *InsertBefore) {
1433 assert(S1->getType() == S2->getType() &&
1434 "Cannot create binary operator with two operands of differing type!");
1435 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1438 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1439 const std::string &Name,
1440 BasicBlock *InsertAtEnd) {
1441 BinaryOperator *Res = create(Op, S1, S2, Name);
1442 InsertAtEnd->getInstList().push_back(Res);
1446 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1447 Instruction *InsertBefore) {
1448 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1449 return new BinaryOperator(Instruction::Sub,
1451 Op->getType(), Name, InsertBefore);
1454 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1455 BasicBlock *InsertAtEnd) {
1456 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1457 return new BinaryOperator(Instruction::Sub,
1459 Op->getType(), Name, InsertAtEnd);
1462 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1463 Instruction *InsertBefore) {
1465 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1466 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1467 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1469 C = ConstantInt::getAllOnesValue(Op->getType());
1472 return new BinaryOperator(Instruction::Xor, Op, C,
1473 Op->getType(), Name, InsertBefore);
1476 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1477 BasicBlock *InsertAtEnd) {
1479 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1480 // Create a vector of all ones values.
1481 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1483 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1485 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1488 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1489 Op->getType(), Name, InsertAtEnd);
1493 // isConstantAllOnes - Helper function for several functions below
1494 static inline bool isConstantAllOnes(const Value *V) {
1495 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1496 return CI->isAllOnesValue();
1497 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1498 return CV->isAllOnesValue();
1502 bool BinaryOperator::isNeg(const Value *V) {
1503 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1504 if (Bop->getOpcode() == Instruction::Sub)
1505 return Bop->getOperand(0) ==
1506 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1510 bool BinaryOperator::isNot(const Value *V) {
1511 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1512 return (Bop->getOpcode() == Instruction::Xor &&
1513 (isConstantAllOnes(Bop->getOperand(1)) ||
1514 isConstantAllOnes(Bop->getOperand(0))));
1518 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1519 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1520 return cast<BinaryOperator>(BinOp)->getOperand(1);
1523 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1524 return getNegArgument(const_cast<Value*>(BinOp));
1527 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1528 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1529 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1530 Value *Op0 = BO->getOperand(0);
1531 Value *Op1 = BO->getOperand(1);
1532 if (isConstantAllOnes(Op0)) return Op1;
1534 assert(isConstantAllOnes(Op1));
1538 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1539 return getNotArgument(const_cast<Value*>(BinOp));
1543 // swapOperands - Exchange the two operands to this instruction. This
1544 // instruction is safe to use on any binary instruction and does not
1545 // modify the semantics of the instruction. If the instruction is
1546 // order dependent (SetLT f.e.) the opcode is changed.
1548 bool BinaryOperator::swapOperands() {
1549 if (!isCommutative())
1550 return true; // Can't commute operands
1551 std::swap(Ops[0], Ops[1]);
1555 //===----------------------------------------------------------------------===//
1557 //===----------------------------------------------------------------------===//
1559 // Just determine if this cast only deals with integral->integral conversion.
1560 bool CastInst::isIntegerCast() const {
1561 switch (getOpcode()) {
1562 default: return false;
1563 case Instruction::ZExt:
1564 case Instruction::SExt:
1565 case Instruction::Trunc:
1567 case Instruction::BitCast:
1568 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1572 bool CastInst::isLosslessCast() const {
1573 // Only BitCast can be lossless, exit fast if we're not BitCast
1574 if (getOpcode() != Instruction::BitCast)
1577 // Identity cast is always lossless
1578 const Type* SrcTy = getOperand(0)->getType();
1579 const Type* DstTy = getType();
1583 // Pointer to pointer is always lossless.
1584 if (isa<PointerType>(SrcTy))
1585 return isa<PointerType>(DstTy);
1586 return false; // Other types have no identity values
1589 /// This function determines if the CastInst does not require any bits to be
1590 /// changed in order to effect the cast. Essentially, it identifies cases where
1591 /// no code gen is necessary for the cast, hence the name no-op cast. For
1592 /// example, the following are all no-op casts:
1593 /// # bitcast uint %X, int
1594 /// # bitcast uint* %x, sbyte*
1595 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1596 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1597 /// @brief Determine if a cast is a no-op.
1598 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1599 switch (getOpcode()) {
1601 assert(!"Invalid CastOp");
1602 case Instruction::Trunc:
1603 case Instruction::ZExt:
1604 case Instruction::SExt:
1605 case Instruction::FPTrunc:
1606 case Instruction::FPExt:
1607 case Instruction::UIToFP:
1608 case Instruction::SIToFP:
1609 case Instruction::FPToUI:
1610 case Instruction::FPToSI:
1611 return false; // These always modify bits
1612 case Instruction::BitCast:
1613 return true; // BitCast never modifies bits.
1614 case Instruction::PtrToInt:
1615 return IntPtrTy->getPrimitiveSizeInBits() ==
1616 getType()->getPrimitiveSizeInBits();
1617 case Instruction::IntToPtr:
1618 return IntPtrTy->getPrimitiveSizeInBits() ==
1619 getOperand(0)->getType()->getPrimitiveSizeInBits();
1623 /// This function determines if a pair of casts can be eliminated and what
1624 /// opcode should be used in the elimination. This assumes that there are two
1625 /// instructions like this:
1626 /// * %F = firstOpcode SrcTy %x to MidTy
1627 /// * %S = secondOpcode MidTy %F to DstTy
1628 /// The function returns a resultOpcode so these two casts can be replaced with:
1629 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1630 /// If no such cast is permited, the function returns 0.
1631 unsigned CastInst::isEliminableCastPair(
1632 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1633 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1635 // Define the 144 possibilities for these two cast instructions. The values
1636 // in this matrix determine what to do in a given situation and select the
1637 // case in the switch below. The rows correspond to firstOp, the columns
1638 // correspond to secondOp. In looking at the table below, keep in mind
1639 // the following cast properties:
1641 // Size Compare Source Destination
1642 // Operator Src ? Size Type Sign Type Sign
1643 // -------- ------------ ------------------- ---------------------
1644 // TRUNC > Integer Any Integral Any
1645 // ZEXT < Integral Unsigned Integer Any
1646 // SEXT < Integral Signed Integer Any
1647 // FPTOUI n/a FloatPt n/a Integral Unsigned
1648 // FPTOSI n/a FloatPt n/a Integral Signed
1649 // UITOFP n/a Integral Unsigned FloatPt n/a
1650 // SITOFP n/a Integral Signed FloatPt n/a
1651 // FPTRUNC > FloatPt n/a FloatPt n/a
1652 // FPEXT < FloatPt n/a FloatPt n/a
1653 // PTRTOINT n/a Pointer n/a Integral Unsigned
1654 // INTTOPTR n/a Integral Unsigned Pointer n/a
1655 // BITCONVERT = FirstClass n/a FirstClass n/a
1657 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1658 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1659 // into "fptoui double to ulong", but this loses information about the range
1660 // of the produced value (we no longer know the top-part is all zeros).
1661 // Further this conversion is often much more expensive for typical hardware,
1662 // and causes issues when building libgcc. We disallow fptosi+sext for the
1664 const unsigned numCastOps =
1665 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1666 static const uint8_t CastResults[numCastOps][numCastOps] = {
1667 // T F F U S F F P I B -+
1668 // R Z S P P I I T P 2 N T |
1669 // U E E 2 2 2 2 R E I T C +- secondOp
1670 // N X X U S F F N X N 2 V |
1671 // C T T I I P P C T T P T -+
1672 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1673 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1674 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1675 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1676 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1677 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1678 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1679 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1680 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1681 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1682 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1683 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1686 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1687 [secondOp-Instruction::CastOpsBegin];
1690 // categorically disallowed
1693 // allowed, use first cast's opcode
1696 // allowed, use second cast's opcode
1699 // no-op cast in second op implies firstOp as long as the DestTy
1701 if (DstTy->isInteger())
1705 // no-op cast in second op implies firstOp as long as the DestTy
1706 // is floating point
1707 if (DstTy->isFloatingPoint())
1711 // no-op cast in first op implies secondOp as long as the SrcTy
1713 if (SrcTy->isInteger())
1717 // no-op cast in first op implies secondOp as long as the SrcTy
1718 // is a floating point
1719 if (SrcTy->isFloatingPoint())
1723 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1724 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1725 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1726 if (MidSize >= PtrSize)
1727 return Instruction::BitCast;
1731 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1732 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1733 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1734 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1735 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1736 if (SrcSize == DstSize)
1737 return Instruction::BitCast;
1738 else if (SrcSize < DstSize)
1742 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1743 return Instruction::ZExt;
1745 // fpext followed by ftrunc is allowed if the bit size returned to is
1746 // the same as the original, in which case its just a bitcast
1748 return Instruction::BitCast;
1749 return 0; // If the types are not the same we can't eliminate it.
1751 // bitcast followed by ptrtoint is allowed as long as the bitcast
1752 // is a pointer to pointer cast.
1753 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1757 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1758 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1762 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1763 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1764 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1765 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1766 if (SrcSize <= PtrSize && SrcSize == DstSize)
1767 return Instruction::BitCast;
1771 // cast combination can't happen (error in input). This is for all cases
1772 // where the MidTy is not the same for the two cast instructions.
1773 assert(!"Invalid Cast Combination");
1776 assert(!"Error in CastResults table!!!");
1782 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1783 const std::string &Name, Instruction *InsertBefore) {
1784 // Construct and return the appropriate CastInst subclass
1786 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1787 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1788 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1789 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1790 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1791 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1792 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1793 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1794 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1795 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1796 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1797 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1799 assert(!"Invalid opcode provided");
1804 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1805 const std::string &Name, BasicBlock *InsertAtEnd) {
1806 // Construct and return the appropriate CastInst subclass
1808 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1809 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1810 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1811 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1812 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1813 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1814 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1815 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1816 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1817 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1818 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1819 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1821 assert(!"Invalid opcode provided");
1826 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1827 const std::string &Name,
1828 Instruction *InsertBefore) {
1829 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1830 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1831 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1834 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1835 const std::string &Name,
1836 BasicBlock *InsertAtEnd) {
1837 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1838 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1839 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1842 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1843 const std::string &Name,
1844 Instruction *InsertBefore) {
1845 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1846 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1847 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1850 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1851 const std::string &Name,
1852 BasicBlock *InsertAtEnd) {
1853 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1854 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1855 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1858 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1859 const std::string &Name,
1860 Instruction *InsertBefore) {
1861 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1862 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1863 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1866 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1867 const std::string &Name,
1868 BasicBlock *InsertAtEnd) {
1869 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1870 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1871 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1874 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1875 const std::string &Name,
1876 BasicBlock *InsertAtEnd) {
1877 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1878 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1881 if (Ty->isInteger())
1882 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1883 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1886 /// @brief Create a BitCast or a PtrToInt cast instruction
1887 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1888 const std::string &Name,
1889 Instruction *InsertBefore) {
1890 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1891 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1894 if (Ty->isInteger())
1895 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1896 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1899 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1900 bool isSigned, const std::string &Name,
1901 Instruction *InsertBefore) {
1902 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1903 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1904 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1905 Instruction::CastOps opcode =
1906 (SrcBits == DstBits ? Instruction::BitCast :
1907 (SrcBits > DstBits ? Instruction::Trunc :
1908 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1909 return create(opcode, C, Ty, Name, InsertBefore);
1912 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1913 bool isSigned, const std::string &Name,
1914 BasicBlock *InsertAtEnd) {
1915 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1916 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1917 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1918 Instruction::CastOps opcode =
1919 (SrcBits == DstBits ? Instruction::BitCast :
1920 (SrcBits > DstBits ? Instruction::Trunc :
1921 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1922 return create(opcode, C, Ty, Name, InsertAtEnd);
1925 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1926 const std::string &Name,
1927 Instruction *InsertBefore) {
1928 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1930 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1931 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1932 Instruction::CastOps opcode =
1933 (SrcBits == DstBits ? Instruction::BitCast :
1934 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1935 return create(opcode, C, Ty, Name, InsertBefore);
1938 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1939 const std::string &Name,
1940 BasicBlock *InsertAtEnd) {
1941 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1943 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1944 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1945 Instruction::CastOps opcode =
1946 (SrcBits == DstBits ? Instruction::BitCast :
1947 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1948 return create(opcode, C, Ty, Name, InsertAtEnd);
1951 // Check whether it is valid to call getCastOpcode for these types.
1952 // This routine must be kept in sync with getCastOpcode.
1953 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1954 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1957 if (SrcTy == DestTy)
1960 // Get the bit sizes, we'll need these
1961 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1962 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1964 // Run through the possibilities ...
1965 if (DestTy->isInteger()) { // Casting to integral
1966 if (SrcTy->isInteger()) { // Casting from integral
1968 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1970 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1971 // Casting from vector
1972 return DestBits == PTy->getBitWidth();
1973 } else { // Casting from something else
1974 return isa<PointerType>(SrcTy);
1976 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1977 if (SrcTy->isInteger()) { // Casting from integral
1979 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1981 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1982 // Casting from vector
1983 return DestBits == PTy->getBitWidth();
1984 } else { // Casting from something else
1987 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1988 // Casting to vector
1989 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1990 // Casting from vector
1991 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
1992 } else { // Casting from something else
1993 return DestPTy->getBitWidth() == SrcBits;
1995 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
1996 if (isa<PointerType>(SrcTy)) { // Casting from pointer
1998 } else if (SrcTy->isInteger()) { // Casting from integral
2000 } else { // Casting from something else
2003 } else { // Casting to something else
2008 // Provide a way to get a "cast" where the cast opcode is inferred from the
2009 // types and size of the operand. This, basically, is a parallel of the
2010 // logic in the castIsValid function below. This axiom should hold:
2011 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2012 // should not assert in castIsValid. In other words, this produces a "correct"
2013 // casting opcode for the arguments passed to it.
2014 // This routine must be kept in sync with isCastable.
2015 Instruction::CastOps
2016 CastInst::getCastOpcode(
2017 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2018 // Get the bit sizes, we'll need these
2019 const Type *SrcTy = Src->getType();
2020 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2021 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2023 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2024 "Only first class types are castable!");
2026 // Run through the possibilities ...
2027 if (DestTy->isInteger()) { // Casting to integral
2028 if (SrcTy->isInteger()) { // Casting from integral
2029 if (DestBits < SrcBits)
2030 return Trunc; // int -> smaller int
2031 else if (DestBits > SrcBits) { // its an extension
2033 return SExt; // signed -> SEXT
2035 return ZExt; // unsigned -> ZEXT
2037 return BitCast; // Same size, No-op cast
2039 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2041 return FPToSI; // FP -> sint
2043 return FPToUI; // FP -> uint
2044 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2045 assert(DestBits == PTy->getBitWidth() &&
2046 "Casting vector to integer of different width");
2047 return BitCast; // Same size, no-op cast
2049 assert(isa<PointerType>(SrcTy) &&
2050 "Casting from a value that is not first-class type");
2051 return PtrToInt; // ptr -> int
2053 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2054 if (SrcTy->isInteger()) { // Casting from integral
2056 return SIToFP; // sint -> FP
2058 return UIToFP; // uint -> FP
2059 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2060 if (DestBits < SrcBits) {
2061 return FPTrunc; // FP -> smaller FP
2062 } else if (DestBits > SrcBits) {
2063 return FPExt; // FP -> larger FP
2065 return BitCast; // same size, no-op cast
2067 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2068 assert(DestBits == PTy->getBitWidth() &&
2069 "Casting vector to floating point of different width");
2070 return BitCast; // same size, no-op cast
2072 assert(0 && "Casting pointer or non-first class to float");
2074 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2075 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2076 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2077 "Casting vector to vector of different widths");
2078 return BitCast; // vector -> vector
2079 } else if (DestPTy->getBitWidth() == SrcBits) {
2080 return BitCast; // float/int -> vector
2082 assert(!"Illegal cast to vector (wrong type or size)");
2084 } else if (isa<PointerType>(DestTy)) {
2085 if (isa<PointerType>(SrcTy)) {
2086 return BitCast; // ptr -> ptr
2087 } else if (SrcTy->isInteger()) {
2088 return IntToPtr; // int -> ptr
2090 assert(!"Casting pointer to other than pointer or int");
2093 assert(!"Casting to type that is not first-class");
2096 // If we fall through to here we probably hit an assertion cast above
2097 // and assertions are not turned on. Anything we return is an error, so
2098 // BitCast is as good a choice as any.
2102 //===----------------------------------------------------------------------===//
2103 // CastInst SubClass Constructors
2104 //===----------------------------------------------------------------------===//
2106 /// Check that the construction parameters for a CastInst are correct. This
2107 /// could be broken out into the separate constructors but it is useful to have
2108 /// it in one place and to eliminate the redundant code for getting the sizes
2109 /// of the types involved.
2111 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2113 // Check for type sanity on the arguments
2114 const Type *SrcTy = S->getType();
2115 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2118 // Get the size of the types in bits, we'll need this later
2119 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2120 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2122 // Switch on the opcode provided
2124 default: return false; // This is an input error
2125 case Instruction::Trunc:
2126 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2127 case Instruction::ZExt:
2128 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2129 case Instruction::SExt:
2130 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2131 case Instruction::FPTrunc:
2132 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2133 SrcBitSize > DstBitSize;
2134 case Instruction::FPExt:
2135 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2136 SrcBitSize < DstBitSize;
2137 case Instruction::UIToFP:
2138 case Instruction::SIToFP:
2139 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2140 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2141 return SVTy->getElementType()->isInteger() &&
2142 DVTy->getElementType()->isFloatingPoint() &&
2143 SVTy->getNumElements() == DVTy->getNumElements();
2146 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2147 case Instruction::FPToUI:
2148 case Instruction::FPToSI:
2149 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2150 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2151 return SVTy->getElementType()->isFloatingPoint() &&
2152 DVTy->getElementType()->isInteger() &&
2153 SVTy->getNumElements() == DVTy->getNumElements();
2156 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2157 case Instruction::PtrToInt:
2158 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2159 case Instruction::IntToPtr:
2160 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2161 case Instruction::BitCast:
2162 // BitCast implies a no-op cast of type only. No bits change.
2163 // However, you can't cast pointers to anything but pointers.
2164 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2167 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2168 // these cases, the cast is okay if the source and destination bit widths
2170 return SrcBitSize == DstBitSize;
2174 TruncInst::TruncInst(
2175 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2176 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2177 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2180 TruncInst::TruncInst(
2181 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2182 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2183 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2187 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2188 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2189 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2193 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2194 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2195 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2198 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2199 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2200 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2204 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2205 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2206 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2209 FPTruncInst::FPTruncInst(
2210 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2211 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2212 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2215 FPTruncInst::FPTruncInst(
2216 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2217 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2218 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2221 FPExtInst::FPExtInst(
2222 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2223 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2224 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2227 FPExtInst::FPExtInst(
2228 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2229 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2230 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2233 UIToFPInst::UIToFPInst(
2234 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2235 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2236 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2239 UIToFPInst::UIToFPInst(
2240 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2241 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2242 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2245 SIToFPInst::SIToFPInst(
2246 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2247 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2248 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2251 SIToFPInst::SIToFPInst(
2252 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2253 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2254 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2257 FPToUIInst::FPToUIInst(
2258 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2259 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2260 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2263 FPToUIInst::FPToUIInst(
2264 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2265 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2266 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2269 FPToSIInst::FPToSIInst(
2270 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2271 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2272 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2275 FPToSIInst::FPToSIInst(
2276 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2277 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2278 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2281 PtrToIntInst::PtrToIntInst(
2282 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2283 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2284 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2287 PtrToIntInst::PtrToIntInst(
2288 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2289 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2290 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2293 IntToPtrInst::IntToPtrInst(
2294 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2295 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2296 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2299 IntToPtrInst::IntToPtrInst(
2300 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2301 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2302 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2305 BitCastInst::BitCastInst(
2306 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2307 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2308 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2311 BitCastInst::BitCastInst(
2312 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2313 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2314 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2317 //===----------------------------------------------------------------------===//
2319 //===----------------------------------------------------------------------===//
2321 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2322 const std::string &Name, Instruction *InsertBefore)
2323 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2324 Ops[0].init(LHS, this);
2325 Ops[1].init(RHS, this);
2326 SubclassData = predicate;
2328 if (op == Instruction::ICmp) {
2329 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2330 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2331 "Invalid ICmp predicate value");
2332 const Type* Op0Ty = getOperand(0)->getType();
2333 const Type* Op1Ty = getOperand(1)->getType();
2334 assert(Op0Ty == Op1Ty &&
2335 "Both operands to ICmp instruction are not of the same type!");
2336 // Check that the operands are the right type
2337 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2338 "Invalid operand types for ICmp instruction");
2341 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2342 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2343 "Invalid FCmp predicate value");
2344 const Type* Op0Ty = getOperand(0)->getType();
2345 const Type* Op1Ty = getOperand(1)->getType();
2346 assert(Op0Ty == Op1Ty &&
2347 "Both operands to FCmp instruction are not of the same type!");
2348 // Check that the operands are the right type
2349 assert(Op0Ty->isFloatingPoint() &&
2350 "Invalid operand types for FCmp instruction");
2353 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2354 const std::string &Name, BasicBlock *InsertAtEnd)
2355 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2356 Ops[0].init(LHS, this);
2357 Ops[1].init(RHS, this);
2358 SubclassData = predicate;
2360 if (op == Instruction::ICmp) {
2361 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2362 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2363 "Invalid ICmp predicate value");
2365 const Type* Op0Ty = getOperand(0)->getType();
2366 const Type* Op1Ty = getOperand(1)->getType();
2367 assert(Op0Ty == Op1Ty &&
2368 "Both operands to ICmp instruction are not of the same type!");
2369 // Check that the operands are the right type
2370 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2371 "Invalid operand types for ICmp instruction");
2374 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2375 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2376 "Invalid FCmp predicate value");
2377 const Type* Op0Ty = getOperand(0)->getType();
2378 const Type* Op1Ty = getOperand(1)->getType();
2379 assert(Op0Ty == Op1Ty &&
2380 "Both operands to FCmp instruction are not of the same type!");
2381 // Check that the operands are the right type
2382 assert(Op0Ty->isFloatingPoint() &&
2383 "Invalid operand types for FCmp instruction");
2387 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2388 const std::string &Name, Instruction *InsertBefore) {
2389 if (Op == Instruction::ICmp) {
2390 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2393 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2398 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2399 const std::string &Name, BasicBlock *InsertAtEnd) {
2400 if (Op == Instruction::ICmp) {
2401 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2404 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2408 void CmpInst::swapOperands() {
2409 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2412 cast<FCmpInst>(this)->swapOperands();
2415 bool CmpInst::isCommutative() {
2416 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2417 return IC->isCommutative();
2418 return cast<FCmpInst>(this)->isCommutative();
2421 bool CmpInst::isEquality() {
2422 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2423 return IC->isEquality();
2424 return cast<FCmpInst>(this)->isEquality();
2428 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2431 assert(!"Unknown icmp predicate!");
2432 case ICMP_EQ: return ICMP_NE;
2433 case ICMP_NE: return ICMP_EQ;
2434 case ICMP_UGT: return ICMP_ULE;
2435 case ICMP_ULT: return ICMP_UGE;
2436 case ICMP_UGE: return ICMP_ULT;
2437 case ICMP_ULE: return ICMP_UGT;
2438 case ICMP_SGT: return ICMP_SLE;
2439 case ICMP_SLT: return ICMP_SGE;
2440 case ICMP_SGE: return ICMP_SLT;
2441 case ICMP_SLE: return ICMP_SGT;
2445 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2447 default: assert(! "Unknown icmp predicate!");
2448 case ICMP_EQ: case ICMP_NE:
2450 case ICMP_SGT: return ICMP_SLT;
2451 case ICMP_SLT: return ICMP_SGT;
2452 case ICMP_SGE: return ICMP_SLE;
2453 case ICMP_SLE: return ICMP_SGE;
2454 case ICMP_UGT: return ICMP_ULT;
2455 case ICMP_ULT: return ICMP_UGT;
2456 case ICMP_UGE: return ICMP_ULE;
2457 case ICMP_ULE: return ICMP_UGE;
2461 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2463 default: assert(! "Unknown icmp predicate!");
2464 case ICMP_EQ: case ICMP_NE:
2465 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2467 case ICMP_UGT: return ICMP_SGT;
2468 case ICMP_ULT: return ICMP_SLT;
2469 case ICMP_UGE: return ICMP_SGE;
2470 case ICMP_ULE: return ICMP_SLE;
2474 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2476 default: assert(! "Unknown icmp predicate!");
2477 case ICMP_EQ: case ICMP_NE:
2478 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2480 case ICMP_SGT: return ICMP_UGT;
2481 case ICMP_SLT: return ICMP_ULT;
2482 case ICMP_SGE: return ICMP_UGE;
2483 case ICMP_SLE: return ICMP_ULE;
2487 bool ICmpInst::isSignedPredicate(Predicate pred) {
2489 default: assert(! "Unknown icmp predicate!");
2490 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2492 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2493 case ICMP_UGE: case ICMP_ULE:
2498 /// Initialize a set of values that all satisfy the condition with C.
2501 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2504 uint32_t BitWidth = C.getBitWidth();
2506 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2507 case ICmpInst::ICMP_EQ: Upper++; break;
2508 case ICmpInst::ICMP_NE: Lower++; break;
2509 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2510 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2511 case ICmpInst::ICMP_UGT:
2512 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2514 case ICmpInst::ICMP_SGT:
2515 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2517 case ICmpInst::ICMP_ULE:
2518 Lower = APInt::getMinValue(BitWidth); Upper++;
2520 case ICmpInst::ICMP_SLE:
2521 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2523 case ICmpInst::ICMP_UGE:
2524 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2526 case ICmpInst::ICMP_SGE:
2527 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2530 return ConstantRange(Lower, Upper);
2533 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2536 assert(!"Unknown icmp predicate!");
2537 case FCMP_OEQ: return FCMP_UNE;
2538 case FCMP_ONE: return FCMP_UEQ;
2539 case FCMP_OGT: return FCMP_ULE;
2540 case FCMP_OLT: return FCMP_UGE;
2541 case FCMP_OGE: return FCMP_ULT;
2542 case FCMP_OLE: return FCMP_UGT;
2543 case FCMP_UEQ: return FCMP_ONE;
2544 case FCMP_UNE: return FCMP_OEQ;
2545 case FCMP_UGT: return FCMP_OLE;
2546 case FCMP_ULT: return FCMP_OGE;
2547 case FCMP_UGE: return FCMP_OLT;
2548 case FCMP_ULE: return FCMP_OGT;
2549 case FCMP_ORD: return FCMP_UNO;
2550 case FCMP_UNO: return FCMP_ORD;
2551 case FCMP_TRUE: return FCMP_FALSE;
2552 case FCMP_FALSE: return FCMP_TRUE;
2556 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2558 default: assert(!"Unknown fcmp predicate!");
2559 case FCMP_FALSE: case FCMP_TRUE:
2560 case FCMP_OEQ: case FCMP_ONE:
2561 case FCMP_UEQ: case FCMP_UNE:
2562 case FCMP_ORD: case FCMP_UNO:
2564 case FCMP_OGT: return FCMP_OLT;
2565 case FCMP_OLT: return FCMP_OGT;
2566 case FCMP_OGE: return FCMP_OLE;
2567 case FCMP_OLE: return FCMP_OGE;
2568 case FCMP_UGT: return FCMP_ULT;
2569 case FCMP_ULT: return FCMP_UGT;
2570 case FCMP_UGE: return FCMP_ULE;
2571 case FCMP_ULE: return FCMP_UGE;
2575 bool CmpInst::isUnsigned(unsigned short predicate) {
2576 switch (predicate) {
2577 default: return false;
2578 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2579 case ICmpInst::ICMP_UGE: return true;
2583 bool CmpInst::isSigned(unsigned short predicate){
2584 switch (predicate) {
2585 default: return false;
2586 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2587 case ICmpInst::ICMP_SGE: return true;
2591 bool CmpInst::isOrdered(unsigned short predicate) {
2592 switch (predicate) {
2593 default: return false;
2594 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2595 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2596 case FCmpInst::FCMP_ORD: return true;
2600 bool CmpInst::isUnordered(unsigned short predicate) {
2601 switch (predicate) {
2602 default: return false;
2603 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2604 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2605 case FCmpInst::FCMP_UNO: return true;
2609 //===----------------------------------------------------------------------===//
2610 // SwitchInst Implementation
2611 //===----------------------------------------------------------------------===//
2613 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2614 assert(Value && Default);
2615 ReservedSpace = 2+NumCases*2;
2617 OperandList = new Use[ReservedSpace];
2619 OperandList[0].init(Value, this);
2620 OperandList[1].init(Default, this);
2623 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2624 /// switch on and a default destination. The number of additional cases can
2625 /// be specified here to make memory allocation more efficient. This
2626 /// constructor can also autoinsert before another instruction.
2627 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2628 Instruction *InsertBefore)
2629 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2630 init(Value, Default, NumCases);
2633 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2634 /// switch on and a default destination. The number of additional cases can
2635 /// be specified here to make memory allocation more efficient. This
2636 /// constructor also autoinserts at the end of the specified BasicBlock.
2637 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2638 BasicBlock *InsertAtEnd)
2639 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2640 init(Value, Default, NumCases);
2643 SwitchInst::SwitchInst(const SwitchInst &SI)
2644 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2645 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2646 Use *OL = OperandList, *InOL = SI.OperandList;
2647 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2648 OL[i].init(InOL[i], this);
2649 OL[i+1].init(InOL[i+1], this);
2653 SwitchInst::~SwitchInst() {
2654 delete [] OperandList;
2658 /// addCase - Add an entry to the switch instruction...
2660 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2661 unsigned OpNo = NumOperands;
2662 if (OpNo+2 > ReservedSpace)
2663 resizeOperands(0); // Get more space!
2664 // Initialize some new operands.
2665 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2666 NumOperands = OpNo+2;
2667 OperandList[OpNo].init(OnVal, this);
2668 OperandList[OpNo+1].init(Dest, this);
2671 /// removeCase - This method removes the specified successor from the switch
2672 /// instruction. Note that this cannot be used to remove the default
2673 /// destination (successor #0).
2675 void SwitchInst::removeCase(unsigned idx) {
2676 assert(idx != 0 && "Cannot remove the default case!");
2677 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2679 unsigned NumOps = getNumOperands();
2680 Use *OL = OperandList;
2682 // Move everything after this operand down.
2684 // FIXME: we could just swap with the end of the list, then erase. However,
2685 // client might not expect this to happen. The code as it is thrashes the
2686 // use/def lists, which is kinda lame.
2687 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2689 OL[i-2+1] = OL[i+1];
2692 // Nuke the last value.
2693 OL[NumOps-2].set(0);
2694 OL[NumOps-2+1].set(0);
2695 NumOperands = NumOps-2;
2698 /// resizeOperands - resize operands - This adjusts the length of the operands
2699 /// list according to the following behavior:
2700 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2701 /// of operation. This grows the number of ops by 1.5 times.
2702 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2703 /// 3. If NumOps == NumOperands, trim the reserved space.
2705 void SwitchInst::resizeOperands(unsigned NumOps) {
2707 NumOps = getNumOperands()/2*6;
2708 } else if (NumOps*2 > NumOperands) {
2709 // No resize needed.
2710 if (ReservedSpace >= NumOps) return;
2711 } else if (NumOps == NumOperands) {
2712 if (ReservedSpace == NumOps) return;
2717 ReservedSpace = NumOps;
2718 Use *NewOps = new Use[NumOps];
2719 Use *OldOps = OperandList;
2720 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2721 NewOps[i].init(OldOps[i], this);
2725 OperandList = NewOps;
2729 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2730 return getSuccessor(idx);
2732 unsigned SwitchInst::getNumSuccessorsV() const {
2733 return getNumSuccessors();
2735 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2736 setSuccessor(idx, B);
2739 //===----------------------------------------------------------------------===//
2740 // GetResultInst Implementation
2741 //===----------------------------------------------------------------------===//
2743 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2744 const std::string &Name,
2745 Instruction *InsertBef)
2746 : Instruction(cast<StructType>(Aggregate->getType())->getElementType(Index),
2747 GetResult, &Aggr, 1, InsertBef) {
2748 assert(isValidOperands(Aggregate, Index) && "Invalid GetResultInst operands!");
2749 Aggr.init(Aggregate, this);
2754 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2758 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2759 unsigned NumElements = STy->getNumElements();
2760 if (Index >= NumElements)
2763 // getresult aggregate value's element types are restricted to
2764 // avoid nested aggregates.
2765 for (unsigned i = 0; i < NumElements; ++i)
2766 if (!STy->getElementType(i)->isFirstClassType())
2769 // Otherwise, Aggregate is valid.
2775 // Define these methods here so vtables don't get emitted into every translation
2776 // unit that uses these classes.
2778 GetElementPtrInst *GetElementPtrInst::clone() const {
2779 return new GetElementPtrInst(*this);
2782 BinaryOperator *BinaryOperator::clone() const {
2783 return create(getOpcode(), Ops[0], Ops[1]);
2786 FCmpInst* FCmpInst::clone() const {
2787 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2789 ICmpInst* ICmpInst::clone() const {
2790 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2793 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2794 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2795 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2796 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2797 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2798 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2799 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2800 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2801 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2802 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2803 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2804 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2805 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2806 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2807 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2808 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2809 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2810 CallInst *CallInst::clone() const { return new CallInst(*this); }
2811 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2812 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2814 ExtractElementInst *ExtractElementInst::clone() const {
2815 return new ExtractElementInst(*this);
2817 InsertElementInst *InsertElementInst::clone() const {
2818 return new InsertElementInst(*this);
2820 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2821 return new ShuffleVectorInst(*this);
2823 PHINode *PHINode::clone() const { return new PHINode(*this); }
2824 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2825 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2826 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2827 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2828 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2829 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2830 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }