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/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/ConstantRange.h"
21 #include "llvm/Support/MathExtras.h"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 CallSite::CallSite(Instruction *C) {
29 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
32 unsigned CallSite::getCallingConv() const {
33 if (CallInst *CI = dyn_cast<CallInst>(I))
34 return CI->getCallingConv();
36 return cast<InvokeInst>(I)->getCallingConv();
38 void CallSite::setCallingConv(unsigned CC) {
39 if (CallInst *CI = dyn_cast<CallInst>(I))
40 CI->setCallingConv(CC);
42 cast<InvokeInst>(I)->setCallingConv(CC);
44 const PAListPtr &CallSite::getParamAttrs() const {
45 if (CallInst *CI = dyn_cast<CallInst>(I))
46 return CI->getParamAttrs();
48 return cast<InvokeInst>(I)->getParamAttrs();
50 void CallSite::setParamAttrs(const PAListPtr &PAL) {
51 if (CallInst *CI = dyn_cast<CallInst>(I))
52 CI->setParamAttrs(PAL);
54 cast<InvokeInst>(I)->setParamAttrs(PAL);
56 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
57 if (CallInst *CI = dyn_cast<CallInst>(I))
58 return CI->paramHasAttr(i, attr);
60 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
62 uint16_t CallSite::getParamAlignment(uint16_t i) const {
63 if (CallInst *CI = dyn_cast<CallInst>(I))
64 return CI->getParamAlignment(i);
66 return cast<InvokeInst>(I)->getParamAlignment(i);
69 bool CallSite::doesNotAccessMemory() const {
70 if (CallInst *CI = dyn_cast<CallInst>(I))
71 return CI->doesNotAccessMemory();
73 return cast<InvokeInst>(I)->doesNotAccessMemory();
75 bool CallSite::onlyReadsMemory() const {
76 if (CallInst *CI = dyn_cast<CallInst>(I))
77 return CI->onlyReadsMemory();
79 return cast<InvokeInst>(I)->onlyReadsMemory();
81 bool CallSite::doesNotThrow() const {
82 if (CallInst *CI = dyn_cast<CallInst>(I))
83 return CI->doesNotThrow();
85 return cast<InvokeInst>(I)->doesNotThrow();
87 void CallSite::setDoesNotThrow(bool doesNotThrow) {
88 if (CallInst *CI = dyn_cast<CallInst>(I))
89 CI->setDoesNotThrow(doesNotThrow);
91 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
94 bool CallSite::hasArgument(const Value *Arg) const {
95 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
101 //===----------------------------------------------------------------------===//
102 // TerminatorInst Class
103 //===----------------------------------------------------------------------===//
105 // Out of line virtual method, so the vtable, etc has a home.
106 TerminatorInst::~TerminatorInst() {
109 //===----------------------------------------------------------------------===//
110 // UnaryInstruction Class
111 //===----------------------------------------------------------------------===//
113 // Out of line virtual method, so the vtable, etc has a home.
114 UnaryInstruction::~UnaryInstruction() {
117 //===----------------------------------------------------------------------===//
119 //===----------------------------------------------------------------------===//
121 PHINode::PHINode(const PHINode &PN)
122 : Instruction(PN.getType(), Instruction::PHI,
123 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
124 ReservedSpace(PN.getNumOperands()) {
125 Use *OL = OperandList;
126 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
127 OL[i] = PN.getOperand(i);
128 OL[i+1] = PN.getOperand(i+1);
132 PHINode::~PHINode() {
133 dropHungoffUses(OperandList);
136 // removeIncomingValue - Remove an incoming value. This is useful if a
137 // predecessor basic block is deleted.
138 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
139 unsigned NumOps = getNumOperands();
140 Use *OL = OperandList;
141 assert(Idx*2 < NumOps && "BB not in PHI node!");
142 Value *Removed = OL[Idx*2];
144 // Move everything after this operand down.
146 // FIXME: we could just swap with the end of the list, then erase. However,
147 // client might not expect this to happen. The code as it is thrashes the
148 // use/def lists, which is kinda lame.
149 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
154 // Nuke the last value.
156 OL[NumOps-2+1].set(0);
157 NumOperands = NumOps-2;
159 // If the PHI node is dead, because it has zero entries, nuke it now.
160 if (NumOps == 2 && DeletePHIIfEmpty) {
161 // If anyone is using this PHI, make them use a dummy value instead...
162 replaceAllUsesWith(UndefValue::get(getType()));
168 /// resizeOperands - resize operands - This adjusts the length of the operands
169 /// list according to the following behavior:
170 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
171 /// of operation. This grows the number of ops by 1.5 times.
172 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
173 /// 3. If NumOps == NumOperands, trim the reserved space.
175 void PHINode::resizeOperands(unsigned NumOps) {
176 unsigned e = getNumOperands();
179 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
180 } else if (NumOps*2 > NumOperands) {
182 if (ReservedSpace >= NumOps) return;
183 } else if (NumOps == NumOperands) {
184 if (ReservedSpace == NumOps) return;
189 ReservedSpace = NumOps;
190 Use *OldOps = OperandList;
191 Use *NewOps = allocHungoffUses(NumOps);
192 for (unsigned i = 0; i != e; ++i) {
193 NewOps[i] = OldOps[i];
195 OperandList = NewOps;
196 if (OldOps) Use::zap(OldOps, OldOps + e, true);
199 /// hasConstantValue - If the specified PHI node always merges together the same
200 /// value, return the value, otherwise return null.
202 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
203 // If the PHI node only has one incoming value, eliminate the PHI node...
204 if (getNumIncomingValues() == 1) {
205 if (getIncomingValue(0) != this) // not X = phi X
206 return getIncomingValue(0);
208 return UndefValue::get(getType()); // Self cycle is dead.
211 // Otherwise if all of the incoming values are the same for the PHI, replace
212 // the PHI node with the incoming value.
215 bool HasUndefInput = false;
216 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
217 if (isa<UndefValue>(getIncomingValue(i))) {
218 HasUndefInput = true;
219 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
220 if (InVal && getIncomingValue(i) != InVal)
221 return 0; // Not the same, bail out.
223 InVal = getIncomingValue(i);
226 // The only case that could cause InVal to be null is if we have a PHI node
227 // that only has entries for itself. In this case, there is no entry into the
228 // loop, so kill the PHI.
230 if (InVal == 0) InVal = UndefValue::get(getType());
232 // If we have a PHI node like phi(X, undef, X), where X is defined by some
233 // instruction, we cannot always return X as the result of the PHI node. Only
234 // do this if X is not an instruction (thus it must dominate the PHI block),
235 // or if the client is prepared to deal with this possibility.
236 if (HasUndefInput && !AllowNonDominatingInstruction)
237 if (Instruction *IV = dyn_cast<Instruction>(InVal))
238 // If it's in the entry block, it dominates everything.
239 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
241 return 0; // Cannot guarantee that InVal dominates this PHINode.
243 // All of the incoming values are the same, return the value now.
248 //===----------------------------------------------------------------------===//
249 // CallInst Implementation
250 //===----------------------------------------------------------------------===//
252 CallInst::~CallInst() {
255 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
256 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
257 Use *OL = OperandList;
260 const FunctionType *FTy =
261 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
262 FTy = FTy; // silence warning.
264 assert((NumParams == FTy->getNumParams() ||
265 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
266 "Calling a function with bad signature!");
267 for (unsigned i = 0; i != NumParams; ++i) {
268 assert((i >= FTy->getNumParams() ||
269 FTy->getParamType(i) == Params[i]->getType()) &&
270 "Calling a function with a bad signature!");
275 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
276 assert(NumOperands == 3 && "NumOperands not set up?");
277 Use *OL = OperandList;
282 const FunctionType *FTy =
283 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
284 FTy = FTy; // silence warning.
286 assert((FTy->getNumParams() == 2 ||
287 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
288 "Calling a function with bad signature");
289 assert((0 >= FTy->getNumParams() ||
290 FTy->getParamType(0) == Actual1->getType()) &&
291 "Calling a function with a bad signature!");
292 assert((1 >= FTy->getNumParams() ||
293 FTy->getParamType(1) == Actual2->getType()) &&
294 "Calling a function with a bad signature!");
297 void CallInst::init(Value *Func, Value *Actual) {
298 assert(NumOperands == 2 && "NumOperands not set up?");
299 Use *OL = OperandList;
303 const FunctionType *FTy =
304 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
305 FTy = FTy; // silence warning.
307 assert((FTy->getNumParams() == 1 ||
308 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
309 "Calling a function with bad signature");
310 assert((0 == FTy->getNumParams() ||
311 FTy->getParamType(0) == Actual->getType()) &&
312 "Calling a function with a bad signature!");
315 void CallInst::init(Value *Func) {
316 assert(NumOperands == 1 && "NumOperands not set up?");
317 Use *OL = OperandList;
320 const FunctionType *FTy =
321 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
322 FTy = FTy; // silence warning.
324 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
327 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
328 Instruction *InsertBefore)
329 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
330 ->getElementType())->getReturnType(),
332 OperandTraits<CallInst>::op_end(this) - 2,
338 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
339 BasicBlock *InsertAtEnd)
340 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
341 ->getElementType())->getReturnType(),
343 OperandTraits<CallInst>::op_end(this) - 2,
348 CallInst::CallInst(Value *Func, const std::string &Name,
349 Instruction *InsertBefore)
350 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
351 ->getElementType())->getReturnType(),
353 OperandTraits<CallInst>::op_end(this) - 1,
359 CallInst::CallInst(Value *Func, const std::string &Name,
360 BasicBlock *InsertAtEnd)
361 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
362 ->getElementType())->getReturnType(),
364 OperandTraits<CallInst>::op_end(this) - 1,
370 CallInst::CallInst(const CallInst &CI)
371 : Instruction(CI.getType(), Instruction::Call,
372 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
373 CI.getNumOperands()) {
374 setParamAttrs(CI.getParamAttrs());
375 SubclassData = CI.SubclassData;
376 Use *OL = OperandList;
377 Use *InOL = CI.OperandList;
378 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
382 void CallInst::addParamAttr(unsigned i, ParameterAttributes attr) {
383 PAListPtr PAL = getParamAttrs();
384 PAL = PAL.addAttr(i, attr);
388 bool CallInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
389 if (ParamAttrs.paramHasAttr(i, attr))
391 if (const Function *F = getCalledFunction())
392 return F->paramHasAttr(i, attr);
396 void CallInst::setDoesNotThrow(bool doesNotThrow) {
397 PAListPtr PAL = getParamAttrs();
399 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
401 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
406 //===----------------------------------------------------------------------===//
407 // InvokeInst Implementation
408 //===----------------------------------------------------------------------===//
410 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
411 Value* const *Args, unsigned NumArgs) {
412 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
413 Use *OL = OperandList;
417 const FunctionType *FTy =
418 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
419 FTy = FTy; // silence warning.
421 assert(((NumArgs == FTy->getNumParams()) ||
422 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
423 "Calling a function with bad signature");
425 for (unsigned i = 0, e = NumArgs; i != e; i++) {
426 assert((i >= FTy->getNumParams() ||
427 FTy->getParamType(i) == Args[i]->getType()) &&
428 "Invoking a function with a bad signature!");
434 InvokeInst::InvokeInst(const InvokeInst &II)
435 : TerminatorInst(II.getType(), Instruction::Invoke,
436 OperandTraits<InvokeInst>::op_end(this)
437 - II.getNumOperands(),
438 II.getNumOperands()) {
439 setParamAttrs(II.getParamAttrs());
440 SubclassData = II.SubclassData;
441 Use *OL = OperandList, *InOL = II.OperandList;
442 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
446 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
447 return getSuccessor(idx);
449 unsigned InvokeInst::getNumSuccessorsV() const {
450 return getNumSuccessors();
452 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
453 return setSuccessor(idx, B);
456 bool InvokeInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
457 if (ParamAttrs.paramHasAttr(i, attr))
459 if (const Function *F = getCalledFunction())
460 return F->paramHasAttr(i, attr);
464 void InvokeInst::addParamAttr(unsigned i, ParameterAttributes attr) {
465 PAListPtr PAL = getParamAttrs();
466 PAL = PAL.addAttr(i, attr);
470 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
471 PAListPtr PAL = getParamAttrs();
473 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
475 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
480 //===----------------------------------------------------------------------===//
481 // ReturnInst Implementation
482 //===----------------------------------------------------------------------===//
484 ReturnInst::ReturnInst(const ReturnInst &RI)
485 : TerminatorInst(Type::VoidTy, Instruction::Ret,
486 OperandTraits<ReturnInst>::op_end(this)
487 - RI.getNumOperands(),
488 RI.getNumOperands()) {
489 unsigned N = RI.getNumOperands();
491 Op<0>() = RI.Op<0>();
493 Use *OL = OperandList;
494 for (unsigned i = 0; i < N; ++i)
495 OL[i] = RI.getOperand(i);
499 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
500 : TerminatorInst(Type::VoidTy, Instruction::Ret,
501 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
502 retVal != 0, InsertBefore) {
506 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
507 : TerminatorInst(Type::VoidTy, Instruction::Ret,
508 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
509 retVal != 0, InsertAtEnd) {
513 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
514 : TerminatorInst(Type::VoidTy, Instruction::Ret,
515 OperandTraits<ReturnInst>::op_end(this),
519 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
520 Instruction *InsertBefore)
521 : TerminatorInst(Type::VoidTy, Instruction::Ret,
522 OperandTraits<ReturnInst>::op_end(this) - N,
527 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
528 BasicBlock *InsertAtEnd)
529 : TerminatorInst(Type::VoidTy, Instruction::Ret,
530 OperandTraits<ReturnInst>::op_end(this) - N,
536 void ReturnInst::init(Value * const* retVals, unsigned N) {
537 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
540 if (NumOperands == 1) {
542 if (V->getType() == Type::VoidTy)
548 Use *OL = OperandList;
549 for (unsigned i = 0; i < NumOperands; ++i) {
550 Value *V = *retVals++;
551 assert(!isa<BasicBlock>(V) &&
552 "Cannot return basic block. Probably using the incorrect ctor");
557 unsigned ReturnInst::getNumSuccessorsV() const {
558 return getNumSuccessors();
561 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
562 /// emit the vtable for the class in this translation unit.
563 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
564 assert(0 && "ReturnInst has no successors!");
567 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
568 assert(0 && "ReturnInst has no successors!");
573 ReturnInst::~ReturnInst() {
576 //===----------------------------------------------------------------------===//
577 // UnwindInst Implementation
578 //===----------------------------------------------------------------------===//
580 UnwindInst::UnwindInst(Instruction *InsertBefore)
581 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
583 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
584 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
588 unsigned UnwindInst::getNumSuccessorsV() const {
589 return getNumSuccessors();
592 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
593 assert(0 && "UnwindInst has no successors!");
596 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
597 assert(0 && "UnwindInst has no successors!");
602 //===----------------------------------------------------------------------===//
603 // UnreachableInst Implementation
604 //===----------------------------------------------------------------------===//
606 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
607 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
609 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
610 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
613 unsigned UnreachableInst::getNumSuccessorsV() const {
614 return getNumSuccessors();
617 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
618 assert(0 && "UnwindInst has no successors!");
621 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
622 assert(0 && "UnwindInst has no successors!");
627 //===----------------------------------------------------------------------===//
628 // BranchInst Implementation
629 //===----------------------------------------------------------------------===//
631 void BranchInst::AssertOK() {
633 assert(getCondition()->getType() == Type::Int1Ty &&
634 "May only branch on boolean predicates!");
637 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
638 : TerminatorInst(Type::VoidTy, Instruction::Br,
639 OperandTraits<BranchInst>::op_end(this) - 1,
641 assert(IfTrue != 0 && "Branch destination may not be null!");
644 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
645 Instruction *InsertBefore)
646 : TerminatorInst(Type::VoidTy, Instruction::Br,
647 OperandTraits<BranchInst>::op_end(this) - 3,
657 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
658 : TerminatorInst(Type::VoidTy, Instruction::Br,
659 OperandTraits<BranchInst>::op_end(this) - 1,
661 assert(IfTrue != 0 && "Branch destination may not be null!");
665 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
666 BasicBlock *InsertAtEnd)
667 : TerminatorInst(Type::VoidTy, Instruction::Br,
668 OperandTraits<BranchInst>::op_end(this) - 3,
679 BranchInst::BranchInst(const BranchInst &BI) :
680 TerminatorInst(Type::VoidTy, Instruction::Br,
681 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
682 BI.getNumOperands()) {
683 OperandList[0] = BI.getOperand(0);
684 if (BI.getNumOperands() != 1) {
685 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
686 OperandList[1] = BI.getOperand(1);
687 OperandList[2] = BI.getOperand(2);
691 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
692 return getSuccessor(idx);
694 unsigned BranchInst::getNumSuccessorsV() const {
695 return getNumSuccessors();
697 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
698 setSuccessor(idx, B);
702 //===----------------------------------------------------------------------===//
703 // AllocationInst Implementation
704 //===----------------------------------------------------------------------===//
706 static Value *getAISize(Value *Amt) {
708 Amt = ConstantInt::get(Type::Int32Ty, 1);
710 assert(!isa<BasicBlock>(Amt) &&
711 "Passed basic block into allocation size parameter! Use other ctor");
712 assert(Amt->getType() == Type::Int32Ty &&
713 "Malloc/Allocation array size is not a 32-bit integer!");
718 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
719 unsigned Align, const std::string &Name,
720 Instruction *InsertBefore)
721 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
724 assert(Ty != Type::VoidTy && "Cannot allocate void!");
728 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
729 unsigned Align, const std::string &Name,
730 BasicBlock *InsertAtEnd)
731 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
734 assert(Ty != Type::VoidTy && "Cannot allocate void!");
738 // Out of line virtual method, so the vtable, etc has a home.
739 AllocationInst::~AllocationInst() {
742 void AllocationInst::setAlignment(unsigned Align) {
743 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
744 SubclassData = Log2_32(Align) + 1;
745 assert(getAlignment() == Align && "Alignment representation error!");
748 bool AllocationInst::isArrayAllocation() const {
749 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
750 return CI->getZExtValue() != 1;
754 const Type *AllocationInst::getAllocatedType() const {
755 return getType()->getElementType();
758 AllocaInst::AllocaInst(const AllocaInst &AI)
759 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
760 Instruction::Alloca, AI.getAlignment()) {
763 MallocInst::MallocInst(const MallocInst &MI)
764 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
765 Instruction::Malloc, MI.getAlignment()) {
768 //===----------------------------------------------------------------------===//
769 // FreeInst Implementation
770 //===----------------------------------------------------------------------===//
772 void FreeInst::AssertOK() {
773 assert(isa<PointerType>(getOperand(0)->getType()) &&
774 "Can not free something of nonpointer type!");
777 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
778 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
782 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
783 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
788 //===----------------------------------------------------------------------===//
789 // LoadInst Implementation
790 //===----------------------------------------------------------------------===//
792 void LoadInst::AssertOK() {
793 assert(isa<PointerType>(getOperand(0)->getType()) &&
794 "Ptr must have pointer type.");
797 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
798 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
799 Load, Ptr, InsertBef) {
806 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
807 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
808 Load, Ptr, InsertAE) {
815 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
816 Instruction *InsertBef)
817 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
818 Load, Ptr, InsertBef) {
819 setVolatile(isVolatile);
825 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
826 unsigned Align, Instruction *InsertBef)
827 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
828 Load, Ptr, InsertBef) {
829 setVolatile(isVolatile);
835 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
836 unsigned Align, BasicBlock *InsertAE)
837 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
838 Load, Ptr, InsertAE) {
839 setVolatile(isVolatile);
845 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
846 BasicBlock *InsertAE)
847 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
848 Load, Ptr, InsertAE) {
849 setVolatile(isVolatile);
857 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
858 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
859 Load, Ptr, InsertBef) {
863 if (Name && Name[0]) setName(Name);
866 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
867 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
868 Load, Ptr, InsertAE) {
872 if (Name && Name[0]) setName(Name);
875 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
876 Instruction *InsertBef)
877 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
878 Load, Ptr, InsertBef) {
879 setVolatile(isVolatile);
882 if (Name && Name[0]) setName(Name);
885 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
886 BasicBlock *InsertAE)
887 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
888 Load, Ptr, InsertAE) {
889 setVolatile(isVolatile);
892 if (Name && Name[0]) setName(Name);
895 void LoadInst::setAlignment(unsigned Align) {
896 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
897 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
900 //===----------------------------------------------------------------------===//
901 // StoreInst Implementation
902 //===----------------------------------------------------------------------===//
904 void StoreInst::AssertOK() {
905 assert(isa<PointerType>(getOperand(1)->getType()) &&
906 "Ptr must have pointer type!");
907 assert(getOperand(0)->getType() ==
908 cast<PointerType>(getOperand(1)->getType())->getElementType()
909 && "Ptr must be a pointer to Val type!");
913 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
914 : Instruction(Type::VoidTy, Store,
915 OperandTraits<StoreInst>::op_begin(this),
916 OperandTraits<StoreInst>::operands(this),
925 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
926 : Instruction(Type::VoidTy, Store,
927 OperandTraits<StoreInst>::op_begin(this),
928 OperandTraits<StoreInst>::operands(this),
937 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
938 Instruction *InsertBefore)
939 : Instruction(Type::VoidTy, Store,
940 OperandTraits<StoreInst>::op_begin(this),
941 OperandTraits<StoreInst>::operands(this),
945 setVolatile(isVolatile);
950 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
951 unsigned Align, Instruction *InsertBefore)
952 : Instruction(Type::VoidTy, Store,
953 OperandTraits<StoreInst>::op_begin(this),
954 OperandTraits<StoreInst>::operands(this),
958 setVolatile(isVolatile);
963 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
964 unsigned Align, BasicBlock *InsertAtEnd)
965 : Instruction(Type::VoidTy, Store,
966 OperandTraits<StoreInst>::op_begin(this),
967 OperandTraits<StoreInst>::operands(this),
971 setVolatile(isVolatile);
976 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
977 BasicBlock *InsertAtEnd)
978 : Instruction(Type::VoidTy, Store,
979 OperandTraits<StoreInst>::op_begin(this),
980 OperandTraits<StoreInst>::operands(this),
984 setVolatile(isVolatile);
989 void StoreInst::setAlignment(unsigned Align) {
990 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
991 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
994 //===----------------------------------------------------------------------===//
995 // GetElementPtrInst Implementation
996 //===----------------------------------------------------------------------===//
998 static unsigned retrieveAddrSpace(const Value *Val) {
999 return cast<PointerType>(Val->getType())->getAddressSpace();
1002 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx, const std::string &Name) {
1003 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1004 Use *OL = OperandList;
1007 for (unsigned i = 0; i != NumIdx; ++i)
1013 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1014 assert(NumOperands == 2 && "NumOperands not initialized?");
1015 Use *OL = OperandList;
1022 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1023 : Instruction(GEPI.getType(), GetElementPtr,
1024 OperandTraits<GetElementPtrInst>::op_end(this)
1025 - GEPI.getNumOperands(),
1026 GEPI.getNumOperands()) {
1027 Use *OL = OperandList;
1028 Use *GEPIOL = GEPI.OperandList;
1029 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1033 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1034 const std::string &Name, Instruction *InBe)
1035 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1036 retrieveAddrSpace(Ptr)),
1038 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1040 init(Ptr, Idx, Name);
1043 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1044 const std::string &Name, BasicBlock *IAE)
1045 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1046 retrieveAddrSpace(Ptr)),
1048 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1050 init(Ptr, Idx, Name);
1053 // getIndexedType - Returns the type of the element that would be loaded with
1054 // a load instruction with the specified parameters.
1056 // A null type is returned if the indices are invalid for the specified
1059 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1062 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1063 if (!PTy) return 0; // Type isn't a pointer type!
1064 const Type *Agg = PTy->getElementType();
1066 // Handle the special case of the empty set index set...
1070 unsigned CurIdx = 1;
1071 for (; CurIdx != NumIdx; ++CurIdx) {
1072 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1073 if (!CT || isa<PointerType>(CT)) return 0;
1074 Value *Index = Idxs[CurIdx];
1075 if (!CT->indexValid(Index)) return 0;
1076 Agg = CT->getTypeAtIndex(Index);
1078 // If the new type forwards to another type, then it is in the middle
1079 // of being refined to another type (and hence, may have dropped all
1080 // references to what it was using before). So, use the new forwarded
1082 if (const Type *Ty = Agg->getForwardedType())
1085 return CurIdx == NumIdx ? Agg : 0;
1088 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1089 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1090 if (!PTy) return 0; // Type isn't a pointer type!
1092 // Check the pointer index.
1093 if (!PTy->indexValid(Idx)) return 0;
1095 return PTy->getElementType();
1099 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1100 /// zeros. If so, the result pointer and the first operand have the same
1101 /// value, just potentially different types.
1102 bool GetElementPtrInst::hasAllZeroIndices() const {
1103 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1104 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1105 if (!CI->isZero()) return false;
1113 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1114 /// constant integers. If so, the result pointer and the first operand have
1115 /// a constant offset between them.
1116 bool GetElementPtrInst::hasAllConstantIndices() const {
1117 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1118 if (!isa<ConstantInt>(getOperand(i)))
1125 //===----------------------------------------------------------------------===//
1126 // ExtractElementInst Implementation
1127 //===----------------------------------------------------------------------===//
1129 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1130 const std::string &Name,
1131 Instruction *InsertBef)
1132 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1134 OperandTraits<ExtractElementInst>::op_begin(this),
1136 assert(isValidOperands(Val, Index) &&
1137 "Invalid extractelement instruction operands!");
1143 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1144 const std::string &Name,
1145 Instruction *InsertBef)
1146 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1148 OperandTraits<ExtractElementInst>::op_begin(this),
1150 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1151 assert(isValidOperands(Val, Index) &&
1152 "Invalid extractelement instruction operands!");
1159 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1160 const std::string &Name,
1161 BasicBlock *InsertAE)
1162 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1164 OperandTraits<ExtractElementInst>::op_begin(this),
1166 assert(isValidOperands(Val, Index) &&
1167 "Invalid extractelement instruction operands!");
1174 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1175 const std::string &Name,
1176 BasicBlock *InsertAE)
1177 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1179 OperandTraits<ExtractElementInst>::op_begin(this),
1181 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1182 assert(isValidOperands(Val, Index) &&
1183 "Invalid extractelement instruction operands!");
1191 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1192 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1198 //===----------------------------------------------------------------------===//
1199 // InsertElementInst Implementation
1200 //===----------------------------------------------------------------------===//
1202 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1203 : Instruction(IE.getType(), InsertElement,
1204 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1205 Op<0>() = IE.Op<0>();
1206 Op<1>() = IE.Op<1>();
1207 Op<2>() = IE.Op<2>();
1209 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1210 const std::string &Name,
1211 Instruction *InsertBef)
1212 : Instruction(Vec->getType(), InsertElement,
1213 OperandTraits<InsertElementInst>::op_begin(this),
1215 assert(isValidOperands(Vec, Elt, Index) &&
1216 "Invalid insertelement instruction operands!");
1223 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1224 const std::string &Name,
1225 Instruction *InsertBef)
1226 : Instruction(Vec->getType(), InsertElement,
1227 OperandTraits<InsertElementInst>::op_begin(this),
1229 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1230 assert(isValidOperands(Vec, Elt, Index) &&
1231 "Invalid insertelement instruction operands!");
1239 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1240 const std::string &Name,
1241 BasicBlock *InsertAE)
1242 : Instruction(Vec->getType(), InsertElement,
1243 OperandTraits<InsertElementInst>::op_begin(this),
1245 assert(isValidOperands(Vec, Elt, Index) &&
1246 "Invalid insertelement instruction operands!");
1254 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1255 const std::string &Name,
1256 BasicBlock *InsertAE)
1257 : Instruction(Vec->getType(), InsertElement,
1258 OperandTraits<InsertElementInst>::op_begin(this),
1260 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1261 assert(isValidOperands(Vec, Elt, Index) &&
1262 "Invalid insertelement instruction operands!");
1270 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1271 const Value *Index) {
1272 if (!isa<VectorType>(Vec->getType()))
1273 return false; // First operand of insertelement must be vector type.
1275 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1276 return false;// Second operand of insertelement must be vector element type.
1278 if (Index->getType() != Type::Int32Ty)
1279 return false; // Third operand of insertelement must be uint.
1284 //===----------------------------------------------------------------------===//
1285 // ShuffleVectorInst Implementation
1286 //===----------------------------------------------------------------------===//
1288 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1289 : Instruction(SV.getType(), ShuffleVector,
1290 OperandTraits<ShuffleVectorInst>::op_begin(this),
1291 OperandTraits<ShuffleVectorInst>::operands(this)) {
1292 Op<0>() = SV.Op<0>();
1293 Op<1>() = SV.Op<1>();
1294 Op<2>() = SV.Op<2>();
1297 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1298 const std::string &Name,
1299 Instruction *InsertBefore)
1300 : Instruction(V1->getType(), ShuffleVector,
1301 OperandTraits<ShuffleVectorInst>::op_begin(this),
1302 OperandTraits<ShuffleVectorInst>::operands(this),
1304 assert(isValidOperands(V1, V2, Mask) &&
1305 "Invalid shuffle vector instruction operands!");
1312 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1313 const std::string &Name,
1314 BasicBlock *InsertAtEnd)
1315 : Instruction(V1->getType(), ShuffleVector,
1316 OperandTraits<ShuffleVectorInst>::op_begin(this),
1317 OperandTraits<ShuffleVectorInst>::operands(this),
1319 assert(isValidOperands(V1, V2, Mask) &&
1320 "Invalid shuffle vector instruction operands!");
1328 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1329 const Value *Mask) {
1330 if (!isa<VectorType>(V1->getType()) ||
1331 V1->getType() != V2->getType())
1334 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1335 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1336 MaskTy->getElementType() != Type::Int32Ty ||
1337 MaskTy->getNumElements() !=
1338 cast<VectorType>(V1->getType())->getNumElements())
1343 /// getMaskValue - Return the index from the shuffle mask for the specified
1344 /// output result. This is either -1 if the element is undef or a number less
1345 /// than 2*numelements.
1346 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1347 const Constant *Mask = cast<Constant>(getOperand(2));
1348 if (isa<UndefValue>(Mask)) return -1;
1349 if (isa<ConstantAggregateZero>(Mask)) return 0;
1350 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1351 assert(i < MaskCV->getNumOperands() && "Index out of range");
1353 if (isa<UndefValue>(MaskCV->getOperand(i)))
1355 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1358 //===----------------------------------------------------------------------===//
1359 // InsertValueInst Class
1360 //===----------------------------------------------------------------------===//
1362 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1363 unsigned NumIdx, const std::string &Name) {
1364 assert(NumOperands == 2 && "NumOperands not initialized?");
1368 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1372 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1373 const std::string &Name) {
1374 assert(NumOperands == 2 && "NumOperands not initialized?");
1378 Indices.push_back(Idx);
1382 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1383 : Instruction(IVI.getType(), InsertValue,
1384 OperandTraits<InsertValueInst>::op_begin(this), 2),
1385 Indices(IVI.Indices) {
1388 InsertValueInst::InsertValueInst(Value *Agg,
1391 const std::string &Name,
1392 Instruction *InsertBefore)
1393 : Instruction(Agg->getType(), InsertValue,
1394 OperandTraits<InsertValueInst>::op_begin(this),
1396 init(Agg, Val, Idx, Name);
1399 InsertValueInst::InsertValueInst(Value *Agg,
1402 const std::string &Name,
1403 BasicBlock *InsertAtEnd)
1404 : Instruction(Agg->getType(), InsertValue,
1405 OperandTraits<InsertValueInst>::op_begin(this),
1407 init(Agg, Val, Idx, Name);
1410 //===----------------------------------------------------------------------===//
1411 // ExtractValueInst Class
1412 //===----------------------------------------------------------------------===//
1414 void ExtractValueInst::init(Value *Agg, const unsigned *Idx, unsigned NumIdx, const std::string &Name) {
1415 assert(NumOperands == 1 && "NumOperands not initialized?");
1418 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1422 void ExtractValueInst::init(Value *Agg, unsigned Idx, const std::string &Name) {
1423 assert(NumOperands == 1 && "NumOperands not initialized?");
1426 Indices.push_back(Idx);
1430 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1431 : Instruction(reinterpret_cast<const Type*>(EVI.getType()), ExtractValue,
1432 OperandTraits<ExtractValueInst>::op_begin(this), 1),
1433 Indices(EVI.Indices) {
1436 // getIndexedType - Returns the type of the element that would be extracted
1437 // with an extractvalue instruction with the specified parameters.
1439 // A null type is returned if the indices are invalid for the specified
1442 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1443 const unsigned *Idxs,
1445 unsigned CurIdx = 0;
1446 for (; CurIdx != NumIdx; ++CurIdx) {
1447 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1448 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1449 unsigned Index = Idxs[CurIdx];
1450 if (!CT->indexValid(Index)) return 0;
1451 Agg = CT->getTypeAtIndex(Index);
1453 // If the new type forwards to another type, then it is in the middle
1454 // of being refined to another type (and hence, may have dropped all
1455 // references to what it was using before). So, use the new forwarded
1457 if (const Type *Ty = Agg->getForwardedType())
1460 return CurIdx == NumIdx ? Agg : 0;
1463 ExtractValueInst::ExtractValueInst(Value *Agg,
1465 const std::string &Name,
1466 BasicBlock *InsertAtEnd)
1467 : Instruction(checkType(getIndexedType(Agg->getType(), &Idx, 1)),
1469 OperandTraits<ExtractValueInst>::op_begin(this),
1471 init(Agg, Idx, Name);
1474 ExtractValueInst::ExtractValueInst(Value *Agg,
1476 const std::string &Name,
1477 Instruction *InsertBefore)
1478 : Instruction(checkType(getIndexedType(Agg->getType(), &Idx, 1)),
1480 OperandTraits<ExtractValueInst>::op_begin(this),
1482 init(Agg, Idx, Name);
1485 //===----------------------------------------------------------------------===//
1486 // BinaryOperator Class
1487 //===----------------------------------------------------------------------===//
1489 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1490 const Type *Ty, const std::string &Name,
1491 Instruction *InsertBefore)
1492 : Instruction(Ty, iType,
1493 OperandTraits<BinaryOperator>::op_begin(this),
1494 OperandTraits<BinaryOperator>::operands(this),
1502 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1503 const Type *Ty, const std::string &Name,
1504 BasicBlock *InsertAtEnd)
1505 : Instruction(Ty, iType,
1506 OperandTraits<BinaryOperator>::op_begin(this),
1507 OperandTraits<BinaryOperator>::operands(this),
1516 void BinaryOperator::init(BinaryOps iType) {
1517 Value *LHS = getOperand(0), *RHS = getOperand(1);
1518 LHS = LHS; RHS = RHS; // Silence warnings.
1519 assert(LHS->getType() == RHS->getType() &&
1520 "Binary operator operand types must match!");
1525 assert(getType() == LHS->getType() &&
1526 "Arithmetic operation should return same type as operands!");
1527 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1528 isa<VectorType>(getType())) &&
1529 "Tried to create an arithmetic operation on a non-arithmetic type!");
1533 assert(getType() == LHS->getType() &&
1534 "Arithmetic operation should return same type as operands!");
1535 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1536 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1537 "Incorrect operand type (not integer) for S/UDIV");
1540 assert(getType() == LHS->getType() &&
1541 "Arithmetic operation should return same type as operands!");
1542 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1543 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1544 && "Incorrect operand type (not floating point) for FDIV");
1548 assert(getType() == LHS->getType() &&
1549 "Arithmetic operation should return same type as operands!");
1550 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1551 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1552 "Incorrect operand type (not integer) for S/UREM");
1555 assert(getType() == LHS->getType() &&
1556 "Arithmetic operation should return same type as operands!");
1557 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1558 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1559 && "Incorrect operand type (not floating point) for FREM");
1564 assert(getType() == LHS->getType() &&
1565 "Shift operation should return same type as operands!");
1566 assert(getType()->isInteger() &&
1567 "Shift operation requires integer operands");
1571 assert(getType() == LHS->getType() &&
1572 "Logical operation should return same type as operands!");
1573 assert((getType()->isInteger() ||
1574 (isa<VectorType>(getType()) &&
1575 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1576 "Tried to create a logical operation on a non-integral type!");
1584 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1585 const std::string &Name,
1586 Instruction *InsertBefore) {
1587 assert(S1->getType() == S2->getType() &&
1588 "Cannot create binary operator with two operands of differing type!");
1589 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1592 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1593 const std::string &Name,
1594 BasicBlock *InsertAtEnd) {
1595 BinaryOperator *Res = Create(Op, S1, S2, Name);
1596 InsertAtEnd->getInstList().push_back(Res);
1600 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1601 Instruction *InsertBefore) {
1602 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1603 return new BinaryOperator(Instruction::Sub,
1605 Op->getType(), Name, InsertBefore);
1608 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1609 BasicBlock *InsertAtEnd) {
1610 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1611 return new BinaryOperator(Instruction::Sub,
1613 Op->getType(), Name, InsertAtEnd);
1616 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1617 Instruction *InsertBefore) {
1619 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1620 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1621 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1623 C = ConstantInt::getAllOnesValue(Op->getType());
1626 return new BinaryOperator(Instruction::Xor, Op, C,
1627 Op->getType(), Name, InsertBefore);
1630 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1631 BasicBlock *InsertAtEnd) {
1633 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1634 // Create a vector of all ones values.
1635 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1637 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1639 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1642 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1643 Op->getType(), Name, InsertAtEnd);
1647 // isConstantAllOnes - Helper function for several functions below
1648 static inline bool isConstantAllOnes(const Value *V) {
1649 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1650 return CI->isAllOnesValue();
1651 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1652 return CV->isAllOnesValue();
1656 bool BinaryOperator::isNeg(const Value *V) {
1657 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1658 if (Bop->getOpcode() == Instruction::Sub)
1659 return Bop->getOperand(0) ==
1660 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1664 bool BinaryOperator::isNot(const Value *V) {
1665 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1666 return (Bop->getOpcode() == Instruction::Xor &&
1667 (isConstantAllOnes(Bop->getOperand(1)) ||
1668 isConstantAllOnes(Bop->getOperand(0))));
1672 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1673 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1674 return cast<BinaryOperator>(BinOp)->getOperand(1);
1677 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1678 return getNegArgument(const_cast<Value*>(BinOp));
1681 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1682 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1683 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1684 Value *Op0 = BO->getOperand(0);
1685 Value *Op1 = BO->getOperand(1);
1686 if (isConstantAllOnes(Op0)) return Op1;
1688 assert(isConstantAllOnes(Op1));
1692 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1693 return getNotArgument(const_cast<Value*>(BinOp));
1697 // swapOperands - Exchange the two operands to this instruction. This
1698 // instruction is safe to use on any binary instruction and does not
1699 // modify the semantics of the instruction. If the instruction is
1700 // order dependent (SetLT f.e.) the opcode is changed.
1702 bool BinaryOperator::swapOperands() {
1703 if (!isCommutative())
1704 return true; // Can't commute operands
1705 Op<0>().swap(Op<1>());
1709 //===----------------------------------------------------------------------===//
1711 //===----------------------------------------------------------------------===//
1713 // Just determine if this cast only deals with integral->integral conversion.
1714 bool CastInst::isIntegerCast() const {
1715 switch (getOpcode()) {
1716 default: return false;
1717 case Instruction::ZExt:
1718 case Instruction::SExt:
1719 case Instruction::Trunc:
1721 case Instruction::BitCast:
1722 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1726 bool CastInst::isLosslessCast() const {
1727 // Only BitCast can be lossless, exit fast if we're not BitCast
1728 if (getOpcode() != Instruction::BitCast)
1731 // Identity cast is always lossless
1732 const Type* SrcTy = getOperand(0)->getType();
1733 const Type* DstTy = getType();
1737 // Pointer to pointer is always lossless.
1738 if (isa<PointerType>(SrcTy))
1739 return isa<PointerType>(DstTy);
1740 return false; // Other types have no identity values
1743 /// This function determines if the CastInst does not require any bits to be
1744 /// changed in order to effect the cast. Essentially, it identifies cases where
1745 /// no code gen is necessary for the cast, hence the name no-op cast. For
1746 /// example, the following are all no-op casts:
1747 /// # bitcast i32* %x to i8*
1748 /// # bitcast <2 x i32> %x to <4 x i16>
1749 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1750 /// @brief Determine if a cast is a no-op.
1751 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1752 switch (getOpcode()) {
1754 assert(!"Invalid CastOp");
1755 case Instruction::Trunc:
1756 case Instruction::ZExt:
1757 case Instruction::SExt:
1758 case Instruction::FPTrunc:
1759 case Instruction::FPExt:
1760 case Instruction::UIToFP:
1761 case Instruction::SIToFP:
1762 case Instruction::FPToUI:
1763 case Instruction::FPToSI:
1764 return false; // These always modify bits
1765 case Instruction::BitCast:
1766 return true; // BitCast never modifies bits.
1767 case Instruction::PtrToInt:
1768 return IntPtrTy->getPrimitiveSizeInBits() ==
1769 getType()->getPrimitiveSizeInBits();
1770 case Instruction::IntToPtr:
1771 return IntPtrTy->getPrimitiveSizeInBits() ==
1772 getOperand(0)->getType()->getPrimitiveSizeInBits();
1776 /// This function determines if a pair of casts can be eliminated and what
1777 /// opcode should be used in the elimination. This assumes that there are two
1778 /// instructions like this:
1779 /// * %F = firstOpcode SrcTy %x to MidTy
1780 /// * %S = secondOpcode MidTy %F to DstTy
1781 /// The function returns a resultOpcode so these two casts can be replaced with:
1782 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1783 /// If no such cast is permited, the function returns 0.
1784 unsigned CastInst::isEliminableCastPair(
1785 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1786 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1788 // Define the 144 possibilities for these two cast instructions. The values
1789 // in this matrix determine what to do in a given situation and select the
1790 // case in the switch below. The rows correspond to firstOp, the columns
1791 // correspond to secondOp. In looking at the table below, keep in mind
1792 // the following cast properties:
1794 // Size Compare Source Destination
1795 // Operator Src ? Size Type Sign Type Sign
1796 // -------- ------------ ------------------- ---------------------
1797 // TRUNC > Integer Any Integral Any
1798 // ZEXT < Integral Unsigned Integer Any
1799 // SEXT < Integral Signed Integer Any
1800 // FPTOUI n/a FloatPt n/a Integral Unsigned
1801 // FPTOSI n/a FloatPt n/a Integral Signed
1802 // UITOFP n/a Integral Unsigned FloatPt n/a
1803 // SITOFP n/a Integral Signed FloatPt n/a
1804 // FPTRUNC > FloatPt n/a FloatPt n/a
1805 // FPEXT < FloatPt n/a FloatPt n/a
1806 // PTRTOINT n/a Pointer n/a Integral Unsigned
1807 // INTTOPTR n/a Integral Unsigned Pointer n/a
1808 // BITCONVERT = FirstClass n/a FirstClass n/a
1810 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1811 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1812 // into "fptoui double to ulong", but this loses information about the range
1813 // of the produced value (we no longer know the top-part is all zeros).
1814 // Further this conversion is often much more expensive for typical hardware,
1815 // and causes issues when building libgcc. We disallow fptosi+sext for the
1817 const unsigned numCastOps =
1818 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1819 static const uint8_t CastResults[numCastOps][numCastOps] = {
1820 // T F F U S F F P I B -+
1821 // R Z S P P I I T P 2 N T |
1822 // U E E 2 2 2 2 R E I T C +- secondOp
1823 // N X X U S F F N X N 2 V |
1824 // C T T I I P P C T T P T -+
1825 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1826 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1827 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1828 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1829 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1830 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1831 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1832 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1833 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1834 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1835 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1836 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1839 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1840 [secondOp-Instruction::CastOpsBegin];
1843 // categorically disallowed
1846 // allowed, use first cast's opcode
1849 // allowed, use second cast's opcode
1852 // no-op cast in second op implies firstOp as long as the DestTy
1854 if (DstTy->isInteger())
1858 // no-op cast in second op implies firstOp as long as the DestTy
1859 // is floating point
1860 if (DstTy->isFloatingPoint())
1864 // no-op cast in first op implies secondOp as long as the SrcTy
1866 if (SrcTy->isInteger())
1870 // no-op cast in first op implies secondOp as long as the SrcTy
1871 // is a floating point
1872 if (SrcTy->isFloatingPoint())
1876 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1877 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1878 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1879 if (MidSize >= PtrSize)
1880 return Instruction::BitCast;
1884 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1885 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1886 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1887 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1888 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1889 if (SrcSize == DstSize)
1890 return Instruction::BitCast;
1891 else if (SrcSize < DstSize)
1895 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1896 return Instruction::ZExt;
1898 // fpext followed by ftrunc is allowed if the bit size returned to is
1899 // the same as the original, in which case its just a bitcast
1901 return Instruction::BitCast;
1902 return 0; // If the types are not the same we can't eliminate it.
1904 // bitcast followed by ptrtoint is allowed as long as the bitcast
1905 // is a pointer to pointer cast.
1906 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1910 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1911 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1915 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1916 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1917 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1918 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1919 if (SrcSize <= PtrSize && SrcSize == DstSize)
1920 return Instruction::BitCast;
1924 // cast combination can't happen (error in input). This is for all cases
1925 // where the MidTy is not the same for the two cast instructions.
1926 assert(!"Invalid Cast Combination");
1929 assert(!"Error in CastResults table!!!");
1935 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1936 const std::string &Name, Instruction *InsertBefore) {
1937 // Construct and return the appropriate CastInst subclass
1939 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1940 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1941 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1942 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1943 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1944 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1945 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1946 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1947 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1948 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1949 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1950 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1952 assert(!"Invalid opcode provided");
1957 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1958 const std::string &Name, BasicBlock *InsertAtEnd) {
1959 // Construct and return the appropriate CastInst subclass
1961 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1962 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1963 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1964 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1965 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1966 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1967 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1968 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1969 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1970 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1971 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1972 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1974 assert(!"Invalid opcode provided");
1979 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1980 const std::string &Name,
1981 Instruction *InsertBefore) {
1982 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1983 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1984 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1987 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1988 const std::string &Name,
1989 BasicBlock *InsertAtEnd) {
1990 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1991 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1992 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1995 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1996 const std::string &Name,
1997 Instruction *InsertBefore) {
1998 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1999 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2000 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2003 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2004 const std::string &Name,
2005 BasicBlock *InsertAtEnd) {
2006 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2007 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2008 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2011 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2012 const std::string &Name,
2013 Instruction *InsertBefore) {
2014 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2015 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2016 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2019 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2020 const std::string &Name,
2021 BasicBlock *InsertAtEnd) {
2022 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2023 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2024 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2027 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2028 const std::string &Name,
2029 BasicBlock *InsertAtEnd) {
2030 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2031 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2034 if (Ty->isInteger())
2035 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2036 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2039 /// @brief Create a BitCast or a PtrToInt cast instruction
2040 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2041 const std::string &Name,
2042 Instruction *InsertBefore) {
2043 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2044 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2047 if (Ty->isInteger())
2048 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2049 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2052 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2053 bool isSigned, const std::string &Name,
2054 Instruction *InsertBefore) {
2055 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2056 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2057 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2058 Instruction::CastOps opcode =
2059 (SrcBits == DstBits ? Instruction::BitCast :
2060 (SrcBits > DstBits ? Instruction::Trunc :
2061 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2062 return Create(opcode, C, Ty, Name, InsertBefore);
2065 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2066 bool isSigned, const std::string &Name,
2067 BasicBlock *InsertAtEnd) {
2068 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2069 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2070 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2071 Instruction::CastOps opcode =
2072 (SrcBits == DstBits ? Instruction::BitCast :
2073 (SrcBits > DstBits ? Instruction::Trunc :
2074 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2075 return Create(opcode, C, Ty, Name, InsertAtEnd);
2078 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2079 const std::string &Name,
2080 Instruction *InsertBefore) {
2081 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2083 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2084 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2085 Instruction::CastOps opcode =
2086 (SrcBits == DstBits ? Instruction::BitCast :
2087 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2088 return Create(opcode, C, Ty, Name, InsertBefore);
2091 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2092 const std::string &Name,
2093 BasicBlock *InsertAtEnd) {
2094 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2096 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2097 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2098 Instruction::CastOps opcode =
2099 (SrcBits == DstBits ? Instruction::BitCast :
2100 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2101 return Create(opcode, C, Ty, Name, InsertAtEnd);
2104 // Check whether it is valid to call getCastOpcode for these types.
2105 // This routine must be kept in sync with getCastOpcode.
2106 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2107 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2110 if (SrcTy == DestTy)
2113 // Get the bit sizes, we'll need these
2114 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2115 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2117 // Run through the possibilities ...
2118 if (DestTy->isInteger()) { // Casting to integral
2119 if (SrcTy->isInteger()) { // Casting from integral
2121 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2123 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2124 // Casting from vector
2125 return DestBits == PTy->getBitWidth();
2126 } else { // Casting from something else
2127 return isa<PointerType>(SrcTy);
2129 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2130 if (SrcTy->isInteger()) { // Casting from integral
2132 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2134 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2135 // Casting from vector
2136 return DestBits == PTy->getBitWidth();
2137 } else { // Casting from something else
2140 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2141 // Casting to vector
2142 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2143 // Casting from vector
2144 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2145 } else { // Casting from something else
2146 return DestPTy->getBitWidth() == SrcBits;
2148 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2149 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2151 } else if (SrcTy->isInteger()) { // Casting from integral
2153 } else { // Casting from something else
2156 } else { // Casting to something else
2161 // Provide a way to get a "cast" where the cast opcode is inferred from the
2162 // types and size of the operand. This, basically, is a parallel of the
2163 // logic in the castIsValid function below. This axiom should hold:
2164 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2165 // should not assert in castIsValid. In other words, this produces a "correct"
2166 // casting opcode for the arguments passed to it.
2167 // This routine must be kept in sync with isCastable.
2168 Instruction::CastOps
2169 CastInst::getCastOpcode(
2170 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2171 // Get the bit sizes, we'll need these
2172 const Type *SrcTy = Src->getType();
2173 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2174 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2176 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2177 "Only first class types are castable!");
2179 // Run through the possibilities ...
2180 if (DestTy->isInteger()) { // Casting to integral
2181 if (SrcTy->isInteger()) { // Casting from integral
2182 if (DestBits < SrcBits)
2183 return Trunc; // int -> smaller int
2184 else if (DestBits > SrcBits) { // its an extension
2186 return SExt; // signed -> SEXT
2188 return ZExt; // unsigned -> ZEXT
2190 return BitCast; // Same size, No-op cast
2192 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2194 return FPToSI; // FP -> sint
2196 return FPToUI; // FP -> uint
2197 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2198 assert(DestBits == PTy->getBitWidth() &&
2199 "Casting vector to integer of different width");
2200 return BitCast; // Same size, no-op cast
2202 assert(isa<PointerType>(SrcTy) &&
2203 "Casting from a value that is not first-class type");
2204 return PtrToInt; // ptr -> int
2206 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2207 if (SrcTy->isInteger()) { // Casting from integral
2209 return SIToFP; // sint -> FP
2211 return UIToFP; // uint -> FP
2212 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2213 if (DestBits < SrcBits) {
2214 return FPTrunc; // FP -> smaller FP
2215 } else if (DestBits > SrcBits) {
2216 return FPExt; // FP -> larger FP
2218 return BitCast; // same size, no-op cast
2220 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2221 assert(DestBits == PTy->getBitWidth() &&
2222 "Casting vector to floating point of different width");
2223 return BitCast; // same size, no-op cast
2225 assert(0 && "Casting pointer or non-first class to float");
2227 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2228 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2229 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2230 "Casting vector to vector of different widths");
2231 return BitCast; // vector -> vector
2232 } else if (DestPTy->getBitWidth() == SrcBits) {
2233 return BitCast; // float/int -> vector
2235 assert(!"Illegal cast to vector (wrong type or size)");
2237 } else if (isa<PointerType>(DestTy)) {
2238 if (isa<PointerType>(SrcTy)) {
2239 return BitCast; // ptr -> ptr
2240 } else if (SrcTy->isInteger()) {
2241 return IntToPtr; // int -> ptr
2243 assert(!"Casting pointer to other than pointer or int");
2246 assert(!"Casting to type that is not first-class");
2249 // If we fall through to here we probably hit an assertion cast above
2250 // and assertions are not turned on. Anything we return is an error, so
2251 // BitCast is as good a choice as any.
2255 //===----------------------------------------------------------------------===//
2256 // CastInst SubClass Constructors
2257 //===----------------------------------------------------------------------===//
2259 /// Check that the construction parameters for a CastInst are correct. This
2260 /// could be broken out into the separate constructors but it is useful to have
2261 /// it in one place and to eliminate the redundant code for getting the sizes
2262 /// of the types involved.
2264 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2266 // Check for type sanity on the arguments
2267 const Type *SrcTy = S->getType();
2268 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2271 // Get the size of the types in bits, we'll need this later
2272 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2273 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2275 // Switch on the opcode provided
2277 default: return false; // This is an input error
2278 case Instruction::Trunc:
2279 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2280 case Instruction::ZExt:
2281 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2282 case Instruction::SExt:
2283 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2284 case Instruction::FPTrunc:
2285 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2286 SrcBitSize > DstBitSize;
2287 case Instruction::FPExt:
2288 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2289 SrcBitSize < DstBitSize;
2290 case Instruction::UIToFP:
2291 case Instruction::SIToFP:
2292 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2293 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2294 return SVTy->getElementType()->isInteger() &&
2295 DVTy->getElementType()->isFloatingPoint() &&
2296 SVTy->getNumElements() == DVTy->getNumElements();
2299 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2300 case Instruction::FPToUI:
2301 case Instruction::FPToSI:
2302 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2303 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2304 return SVTy->getElementType()->isFloatingPoint() &&
2305 DVTy->getElementType()->isInteger() &&
2306 SVTy->getNumElements() == DVTy->getNumElements();
2309 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2310 case Instruction::PtrToInt:
2311 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2312 case Instruction::IntToPtr:
2313 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2314 case Instruction::BitCast:
2315 // BitCast implies a no-op cast of type only. No bits change.
2316 // However, you can't cast pointers to anything but pointers.
2317 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2320 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2321 // these cases, the cast is okay if the source and destination bit widths
2323 return SrcBitSize == DstBitSize;
2327 TruncInst::TruncInst(
2328 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2329 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2330 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2333 TruncInst::TruncInst(
2334 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2335 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2336 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2340 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2341 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2342 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2346 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2347 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2348 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2351 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2352 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2353 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2357 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2358 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2359 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2362 FPTruncInst::FPTruncInst(
2363 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2364 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2365 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2368 FPTruncInst::FPTruncInst(
2369 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2370 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2371 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2374 FPExtInst::FPExtInst(
2375 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2376 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2377 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2380 FPExtInst::FPExtInst(
2381 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2382 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2383 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2386 UIToFPInst::UIToFPInst(
2387 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2388 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2389 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2392 UIToFPInst::UIToFPInst(
2393 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2394 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2395 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2398 SIToFPInst::SIToFPInst(
2399 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2400 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2401 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2404 SIToFPInst::SIToFPInst(
2405 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2406 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2407 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2410 FPToUIInst::FPToUIInst(
2411 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2412 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2413 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2416 FPToUIInst::FPToUIInst(
2417 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2418 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2419 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2422 FPToSIInst::FPToSIInst(
2423 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2424 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2425 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2428 FPToSIInst::FPToSIInst(
2429 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2430 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2431 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2434 PtrToIntInst::PtrToIntInst(
2435 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2436 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2437 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2440 PtrToIntInst::PtrToIntInst(
2441 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2442 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2443 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2446 IntToPtrInst::IntToPtrInst(
2447 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2448 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2449 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2452 IntToPtrInst::IntToPtrInst(
2453 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2454 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2455 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2458 BitCastInst::BitCastInst(
2459 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2460 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2461 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2464 BitCastInst::BitCastInst(
2465 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2466 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2467 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2470 //===----------------------------------------------------------------------===//
2472 //===----------------------------------------------------------------------===//
2474 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2475 Value *LHS, Value *RHS, const std::string &Name,
2476 Instruction *InsertBefore)
2477 : Instruction(ty, op,
2478 OperandTraits<CmpInst>::op_begin(this),
2479 OperandTraits<CmpInst>::operands(this),
2483 SubclassData = predicate;
2487 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2488 Value *LHS, Value *RHS, const std::string &Name,
2489 BasicBlock *InsertAtEnd)
2490 : Instruction(ty, op,
2491 OperandTraits<CmpInst>::op_begin(this),
2492 OperandTraits<CmpInst>::operands(this),
2496 SubclassData = predicate;
2501 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2502 const std::string &Name, Instruction *InsertBefore) {
2503 if (Op == Instruction::ICmp) {
2504 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2507 if (Op == Instruction::FCmp) {
2508 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2511 if (Op == Instruction::VICmp) {
2512 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2515 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2520 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2521 const std::string &Name, BasicBlock *InsertAtEnd) {
2522 if (Op == Instruction::ICmp) {
2523 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2526 if (Op == Instruction::FCmp) {
2527 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2530 if (Op == Instruction::VICmp) {
2531 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2534 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2538 void CmpInst::swapOperands() {
2539 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2542 cast<FCmpInst>(this)->swapOperands();
2545 bool CmpInst::isCommutative() {
2546 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2547 return IC->isCommutative();
2548 return cast<FCmpInst>(this)->isCommutative();
2551 bool CmpInst::isEquality() {
2552 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2553 return IC->isEquality();
2554 return cast<FCmpInst>(this)->isEquality();
2558 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2560 default: assert(!"Unknown cmp predicate!");
2561 case ICMP_EQ: return ICMP_NE;
2562 case ICMP_NE: return ICMP_EQ;
2563 case ICMP_UGT: return ICMP_ULE;
2564 case ICMP_ULT: return ICMP_UGE;
2565 case ICMP_UGE: return ICMP_ULT;
2566 case ICMP_ULE: return ICMP_UGT;
2567 case ICMP_SGT: return ICMP_SLE;
2568 case ICMP_SLT: return ICMP_SGE;
2569 case ICMP_SGE: return ICMP_SLT;
2570 case ICMP_SLE: return ICMP_SGT;
2572 case FCMP_OEQ: return FCMP_UNE;
2573 case FCMP_ONE: return FCMP_UEQ;
2574 case FCMP_OGT: return FCMP_ULE;
2575 case FCMP_OLT: return FCMP_UGE;
2576 case FCMP_OGE: return FCMP_ULT;
2577 case FCMP_OLE: return FCMP_UGT;
2578 case FCMP_UEQ: return FCMP_ONE;
2579 case FCMP_UNE: return FCMP_OEQ;
2580 case FCMP_UGT: return FCMP_OLE;
2581 case FCMP_ULT: return FCMP_OGE;
2582 case FCMP_UGE: return FCMP_OLT;
2583 case FCMP_ULE: return FCMP_OGT;
2584 case FCMP_ORD: return FCMP_UNO;
2585 case FCMP_UNO: return FCMP_ORD;
2586 case FCMP_TRUE: return FCMP_FALSE;
2587 case FCMP_FALSE: return FCMP_TRUE;
2591 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2593 default: assert(! "Unknown icmp predicate!");
2594 case ICMP_EQ: case ICMP_NE:
2595 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2597 case ICMP_UGT: return ICMP_SGT;
2598 case ICMP_ULT: return ICMP_SLT;
2599 case ICMP_UGE: return ICMP_SGE;
2600 case ICMP_ULE: return ICMP_SLE;
2604 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2606 default: assert(! "Unknown icmp predicate!");
2607 case ICMP_EQ: case ICMP_NE:
2608 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2610 case ICMP_SGT: return ICMP_UGT;
2611 case ICMP_SLT: return ICMP_ULT;
2612 case ICMP_SGE: return ICMP_UGE;
2613 case ICMP_SLE: return ICMP_ULE;
2617 bool ICmpInst::isSignedPredicate(Predicate pred) {
2619 default: assert(! "Unknown icmp predicate!");
2620 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2622 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2623 case ICMP_UGE: case ICMP_ULE:
2628 /// Initialize a set of values that all satisfy the condition with C.
2631 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2634 uint32_t BitWidth = C.getBitWidth();
2636 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2637 case ICmpInst::ICMP_EQ: Upper++; break;
2638 case ICmpInst::ICMP_NE: Lower++; break;
2639 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2640 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2641 case ICmpInst::ICMP_UGT:
2642 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2644 case ICmpInst::ICMP_SGT:
2645 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2647 case ICmpInst::ICMP_ULE:
2648 Lower = APInt::getMinValue(BitWidth); Upper++;
2650 case ICmpInst::ICMP_SLE:
2651 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2653 case ICmpInst::ICMP_UGE:
2654 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2656 case ICmpInst::ICMP_SGE:
2657 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2660 return ConstantRange(Lower, Upper);
2663 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2665 default: assert(!"Unknown cmp predicate!");
2666 case ICMP_EQ: case ICMP_NE:
2668 case ICMP_SGT: return ICMP_SLT;
2669 case ICMP_SLT: return ICMP_SGT;
2670 case ICMP_SGE: return ICMP_SLE;
2671 case ICMP_SLE: return ICMP_SGE;
2672 case ICMP_UGT: return ICMP_ULT;
2673 case ICMP_ULT: return ICMP_UGT;
2674 case ICMP_UGE: return ICMP_ULE;
2675 case ICMP_ULE: return ICMP_UGE;
2677 case FCMP_FALSE: case FCMP_TRUE:
2678 case FCMP_OEQ: case FCMP_ONE:
2679 case FCMP_UEQ: case FCMP_UNE:
2680 case FCMP_ORD: case FCMP_UNO:
2682 case FCMP_OGT: return FCMP_OLT;
2683 case FCMP_OLT: return FCMP_OGT;
2684 case FCMP_OGE: return FCMP_OLE;
2685 case FCMP_OLE: return FCMP_OGE;
2686 case FCMP_UGT: return FCMP_ULT;
2687 case FCMP_ULT: return FCMP_UGT;
2688 case FCMP_UGE: return FCMP_ULE;
2689 case FCMP_ULE: return FCMP_UGE;
2693 bool CmpInst::isUnsigned(unsigned short predicate) {
2694 switch (predicate) {
2695 default: return false;
2696 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2697 case ICmpInst::ICMP_UGE: return true;
2701 bool CmpInst::isSigned(unsigned short predicate){
2702 switch (predicate) {
2703 default: return false;
2704 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2705 case ICmpInst::ICMP_SGE: return true;
2709 bool CmpInst::isOrdered(unsigned short predicate) {
2710 switch (predicate) {
2711 default: return false;
2712 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2713 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2714 case FCmpInst::FCMP_ORD: return true;
2718 bool CmpInst::isUnordered(unsigned short predicate) {
2719 switch (predicate) {
2720 default: return false;
2721 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2722 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2723 case FCmpInst::FCMP_UNO: return true;
2727 //===----------------------------------------------------------------------===//
2728 // SwitchInst Implementation
2729 //===----------------------------------------------------------------------===//
2731 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2732 assert(Value && Default);
2733 ReservedSpace = 2+NumCases*2;
2735 OperandList = allocHungoffUses(ReservedSpace);
2737 OperandList[0] = Value;
2738 OperandList[1] = Default;
2741 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2742 /// switch on and a default destination. The number of additional cases can
2743 /// be specified here to make memory allocation more efficient. This
2744 /// constructor can also autoinsert before another instruction.
2745 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2746 Instruction *InsertBefore)
2747 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2748 init(Value, Default, NumCases);
2751 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2752 /// switch on and a default destination. The number of additional cases can
2753 /// be specified here to make memory allocation more efficient. This
2754 /// constructor also autoinserts at the end of the specified BasicBlock.
2755 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2756 BasicBlock *InsertAtEnd)
2757 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2758 init(Value, Default, NumCases);
2761 SwitchInst::SwitchInst(const SwitchInst &SI)
2762 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2763 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2764 Use *OL = OperandList, *InOL = SI.OperandList;
2765 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2767 OL[i+1] = InOL[i+1];
2771 SwitchInst::~SwitchInst() {
2772 dropHungoffUses(OperandList);
2776 /// addCase - Add an entry to the switch instruction...
2778 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2779 unsigned OpNo = NumOperands;
2780 if (OpNo+2 > ReservedSpace)
2781 resizeOperands(0); // Get more space!
2782 // Initialize some new operands.
2783 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2784 NumOperands = OpNo+2;
2785 OperandList[OpNo] = OnVal;
2786 OperandList[OpNo+1] = Dest;
2789 /// removeCase - This method removes the specified successor from the switch
2790 /// instruction. Note that this cannot be used to remove the default
2791 /// destination (successor #0).
2793 void SwitchInst::removeCase(unsigned idx) {
2794 assert(idx != 0 && "Cannot remove the default case!");
2795 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2797 unsigned NumOps = getNumOperands();
2798 Use *OL = OperandList;
2800 // Move everything after this operand down.
2802 // FIXME: we could just swap with the end of the list, then erase. However,
2803 // client might not expect this to happen. The code as it is thrashes the
2804 // use/def lists, which is kinda lame.
2805 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2807 OL[i-2+1] = OL[i+1];
2810 // Nuke the last value.
2811 OL[NumOps-2].set(0);
2812 OL[NumOps-2+1].set(0);
2813 NumOperands = NumOps-2;
2816 /// resizeOperands - resize operands - This adjusts the length of the operands
2817 /// list according to the following behavior:
2818 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2819 /// of operation. This grows the number of ops by 3 times.
2820 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2821 /// 3. If NumOps == NumOperands, trim the reserved space.
2823 void SwitchInst::resizeOperands(unsigned NumOps) {
2824 unsigned e = getNumOperands();
2827 } else if (NumOps*2 > NumOperands) {
2828 // No resize needed.
2829 if (ReservedSpace >= NumOps) return;
2830 } else if (NumOps == NumOperands) {
2831 if (ReservedSpace == NumOps) return;
2836 ReservedSpace = NumOps;
2837 Use *NewOps = allocHungoffUses(NumOps);
2838 Use *OldOps = OperandList;
2839 for (unsigned i = 0; i != e; ++i) {
2840 NewOps[i] = OldOps[i];
2842 OperandList = NewOps;
2843 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2847 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2848 return getSuccessor(idx);
2850 unsigned SwitchInst::getNumSuccessorsV() const {
2851 return getNumSuccessors();
2853 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2854 setSuccessor(idx, B);
2857 //===----------------------------------------------------------------------===//
2858 // GetResultInst Implementation
2859 //===----------------------------------------------------------------------===//
2861 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2862 const std::string &Name,
2863 Instruction *InsertBef)
2864 : UnaryInstruction(cast<StructType>(Aggregate->getType())
2865 ->getElementType(Index),
2866 GetResult, Aggregate, InsertBef),
2868 assert(isValidOperands(Aggregate, Index)
2869 && "Invalid GetResultInst operands!");
2873 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2877 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2878 unsigned NumElements = STy->getNumElements();
2879 if (Index >= NumElements || NumElements == 0)
2882 // getresult aggregate value's element types are restricted to
2883 // avoid nested aggregates.
2884 for (unsigned i = 0; i < NumElements; ++i)
2885 if (!STy->getElementType(i)->isFirstClassType())
2888 // Otherwise, Aggregate is valid.
2894 // Define these methods here so vtables don't get emitted into every translation
2895 // unit that uses these classes.
2897 GetElementPtrInst *GetElementPtrInst::clone() const {
2898 return new(getNumOperands()) GetElementPtrInst(*this);
2901 BinaryOperator *BinaryOperator::clone() const {
2902 return Create(getOpcode(), Op<0>(), Op<1>());
2905 FCmpInst* FCmpInst::clone() const {
2906 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2908 ICmpInst* ICmpInst::clone() const {
2909 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2912 VFCmpInst* VFCmpInst::clone() const {
2913 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2915 VICmpInst* VICmpInst::clone() const {
2916 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2919 ExtractValueInst *ExtractValueInst::clone() const {
2920 return new ExtractValueInst(*this);
2922 InsertValueInst *InsertValueInst::clone() const {
2923 return new InsertValueInst(*this);
2927 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2928 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2929 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2930 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2931 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2932 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2933 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2934 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2935 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2936 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2937 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2938 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2939 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2940 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2941 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2942 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2943 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2944 CallInst *CallInst::clone() const {
2945 return new(getNumOperands()) CallInst(*this);
2947 SelectInst *SelectInst::clone() const {
2948 return new(getNumOperands()) SelectInst(*this);
2950 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2952 ExtractElementInst *ExtractElementInst::clone() const {
2953 return new ExtractElementInst(*this);
2955 InsertElementInst *InsertElementInst::clone() const {
2956 return InsertElementInst::Create(*this);
2958 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2959 return new ShuffleVectorInst(*this);
2961 PHINode *PHINode::clone() const { return new PHINode(*this); }
2962 ReturnInst *ReturnInst::clone() const {
2963 return new(getNumOperands()) ReturnInst(*this);
2965 BranchInst *BranchInst::clone() const {
2966 return new(getNumOperands()) BranchInst(*this);
2968 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2969 InvokeInst *InvokeInst::clone() const {
2970 return new(getNumOperands()) InvokeInst(*this);
2972 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2973 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2974 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }