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/Operator.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/Streams.h"
27 //===----------------------------------------------------------------------===//
29 //===----------------------------------------------------------------------===//
31 #define CALLSITE_DELEGATE_GETTER(METHOD) \
32 Instruction *II(getInstruction()); \
34 ? cast<CallInst>(II)->METHOD \
35 : cast<InvokeInst>(II)->METHOD
37 #define CALLSITE_DELEGATE_SETTER(METHOD) \
38 Instruction *II(getInstruction()); \
40 cast<CallInst>(II)->METHOD; \
42 cast<InvokeInst>(II)->METHOD
44 CallSite::CallSite(Instruction *C) {
45 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
47 I.setInt(isa<CallInst>(C));
49 unsigned CallSite::getCallingConv() const {
50 CALLSITE_DELEGATE_GETTER(getCallingConv());
52 void CallSite::setCallingConv(unsigned CC) {
53 CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
55 const AttrListPtr &CallSite::getAttributes() const {
56 CALLSITE_DELEGATE_GETTER(getAttributes());
58 void CallSite::setAttributes(const AttrListPtr &PAL) {
59 CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
61 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
62 CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
64 uint16_t CallSite::getParamAlignment(uint16_t i) const {
65 CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
67 bool CallSite::doesNotAccessMemory() const {
68 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
70 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
71 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
73 bool CallSite::onlyReadsMemory() const {
74 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
76 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
77 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
79 bool CallSite::doesNotReturn() const {
80 CALLSITE_DELEGATE_GETTER(doesNotReturn());
82 void CallSite::setDoesNotReturn(bool doesNotReturn) {
83 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
85 bool CallSite::doesNotThrow() const {
86 CALLSITE_DELEGATE_GETTER(doesNotThrow());
88 void CallSite::setDoesNotThrow(bool doesNotThrow) {
89 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
92 bool CallSite::hasArgument(const Value *Arg) const {
93 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
99 #undef CALLSITE_DELEGATE_GETTER
100 #undef CALLSITE_DELEGATE_SETTER
102 //===----------------------------------------------------------------------===//
103 // TerminatorInst Class
104 //===----------------------------------------------------------------------===//
106 // Out of line virtual method, so the vtable, etc has a home.
107 TerminatorInst::~TerminatorInst() {
110 //===----------------------------------------------------------------------===//
111 // UnaryInstruction Class
112 //===----------------------------------------------------------------------===//
114 // Out of line virtual method, so the vtable, etc has a home.
115 UnaryInstruction::~UnaryInstruction() {
118 //===----------------------------------------------------------------------===//
120 //===----------------------------------------------------------------------===//
122 /// areInvalidOperands - Return a string if the specified operands are invalid
123 /// for a select operation, otherwise return null.
124 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
125 if (Op1->getType() != Op2->getType())
126 return "both values to select must have same type";
128 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
130 if (VT->getElementType() != Type::Int1Ty)
131 return "vector select condition element type must be i1";
132 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
134 return "selected values for vector select must be vectors";
135 if (ET->getNumElements() != VT->getNumElements())
136 return "vector select requires selected vectors to have "
137 "the same vector length as select condition";
138 } else if (Op0->getType() != Type::Int1Ty) {
139 return "select condition must be i1 or <n x i1>";
145 //===----------------------------------------------------------------------===//
147 //===----------------------------------------------------------------------===//
149 PHINode::PHINode(const PHINode &PN)
150 : Instruction(PN.getType(), Instruction::PHI,
151 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
152 ReservedSpace(PN.getNumOperands()) {
153 Use *OL = OperandList;
154 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
155 OL[i] = PN.getOperand(i);
156 OL[i+1] = PN.getOperand(i+1);
160 PHINode::~PHINode() {
162 dropHungoffUses(OperandList);
165 // removeIncomingValue - Remove an incoming value. This is useful if a
166 // predecessor basic block is deleted.
167 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
168 unsigned NumOps = getNumOperands();
169 Use *OL = OperandList;
170 assert(Idx*2 < NumOps && "BB not in PHI node!");
171 Value *Removed = OL[Idx*2];
173 // Move everything after this operand down.
175 // FIXME: we could just swap with the end of the list, then erase. However,
176 // client might not expect this to happen. The code as it is thrashes the
177 // use/def lists, which is kinda lame.
178 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
183 // Nuke the last value.
185 OL[NumOps-2+1].set(0);
186 NumOperands = NumOps-2;
188 // If the PHI node is dead, because it has zero entries, nuke it now.
189 if (NumOps == 2 && DeletePHIIfEmpty) {
190 // If anyone is using this PHI, make them use a dummy value instead...
191 replaceAllUsesWith(getType()->getContext().getUndef(getType()));
197 /// resizeOperands - resize operands - This adjusts the length of the operands
198 /// list according to the following behavior:
199 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
200 /// of operation. This grows the number of ops by 1.5 times.
201 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
202 /// 3. If NumOps == NumOperands, trim the reserved space.
204 void PHINode::resizeOperands(unsigned NumOps) {
205 unsigned e = getNumOperands();
208 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
209 } else if (NumOps*2 > NumOperands) {
211 if (ReservedSpace >= NumOps) return;
212 } else if (NumOps == NumOperands) {
213 if (ReservedSpace == NumOps) return;
218 ReservedSpace = NumOps;
219 Use *OldOps = OperandList;
220 Use *NewOps = allocHungoffUses(NumOps);
221 std::copy(OldOps, OldOps + e, NewOps);
222 OperandList = NewOps;
223 if (OldOps) Use::zap(OldOps, OldOps + e, true);
226 /// hasConstantValue - If the specified PHI node always merges together the same
227 /// value, return the value, otherwise return null.
229 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
230 // If the PHI node only has one incoming value, eliminate the PHI node...
231 if (getNumIncomingValues() == 1) {
232 if (getIncomingValue(0) != this) // not X = phi X
233 return getIncomingValue(0);
236 getType()->getContext().getUndef(getType()); // Self cycle is dead.
239 // Otherwise if all of the incoming values are the same for the PHI, replace
240 // the PHI node with the incoming value.
243 bool HasUndefInput = false;
244 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
245 if (isa<UndefValue>(getIncomingValue(i))) {
246 HasUndefInput = true;
247 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
248 if (InVal && getIncomingValue(i) != InVal)
249 return 0; // Not the same, bail out.
251 InVal = getIncomingValue(i);
254 // The only case that could cause InVal to be null is if we have a PHI node
255 // that only has entries for itself. In this case, there is no entry into the
256 // loop, so kill the PHI.
258 if (InVal == 0) InVal = getType()->getContext().getUndef(getType());
260 // If we have a PHI node like phi(X, undef, X), where X is defined by some
261 // instruction, we cannot always return X as the result of the PHI node. Only
262 // do this if X is not an instruction (thus it must dominate the PHI block),
263 // or if the client is prepared to deal with this possibility.
264 if (HasUndefInput && !AllowNonDominatingInstruction)
265 if (Instruction *IV = dyn_cast<Instruction>(InVal))
266 // If it's in the entry block, it dominates everything.
267 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
269 return 0; // Cannot guarantee that InVal dominates this PHINode.
271 // All of the incoming values are the same, return the value now.
276 //===----------------------------------------------------------------------===//
277 // CallInst Implementation
278 //===----------------------------------------------------------------------===//
280 CallInst::~CallInst() {
283 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
284 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
285 Use *OL = OperandList;
288 const FunctionType *FTy =
289 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
290 FTy = FTy; // silence warning.
292 assert((NumParams == FTy->getNumParams() ||
293 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
294 "Calling a function with bad signature!");
295 for (unsigned i = 0; i != NumParams; ++i) {
296 assert((i >= FTy->getNumParams() ||
297 FTy->getParamType(i) == Params[i]->getType()) &&
298 "Calling a function with a bad signature!");
303 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
304 assert(NumOperands == 3 && "NumOperands not set up?");
305 Use *OL = OperandList;
310 const FunctionType *FTy =
311 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
312 FTy = FTy; // silence warning.
314 assert((FTy->getNumParams() == 2 ||
315 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
316 "Calling a function with bad signature");
317 assert((0 >= FTy->getNumParams() ||
318 FTy->getParamType(0) == Actual1->getType()) &&
319 "Calling a function with a bad signature!");
320 assert((1 >= FTy->getNumParams() ||
321 FTy->getParamType(1) == Actual2->getType()) &&
322 "Calling a function with a bad signature!");
325 void CallInst::init(Value *Func, Value *Actual) {
326 assert(NumOperands == 2 && "NumOperands not set up?");
327 Use *OL = OperandList;
331 const FunctionType *FTy =
332 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
333 FTy = FTy; // silence warning.
335 assert((FTy->getNumParams() == 1 ||
336 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
337 "Calling a function with bad signature");
338 assert((0 == FTy->getNumParams() ||
339 FTy->getParamType(0) == Actual->getType()) &&
340 "Calling a function with a bad signature!");
343 void CallInst::init(Value *Func) {
344 assert(NumOperands == 1 && "NumOperands not set up?");
345 Use *OL = OperandList;
348 const FunctionType *FTy =
349 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
350 FTy = FTy; // silence warning.
352 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
355 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
356 Instruction *InsertBefore)
357 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
358 ->getElementType())->getReturnType(),
360 OperandTraits<CallInst>::op_end(this) - 2,
366 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
367 BasicBlock *InsertAtEnd)
368 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
369 ->getElementType())->getReturnType(),
371 OperandTraits<CallInst>::op_end(this) - 2,
376 CallInst::CallInst(Value *Func, const std::string &Name,
377 Instruction *InsertBefore)
378 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
379 ->getElementType())->getReturnType(),
381 OperandTraits<CallInst>::op_end(this) - 1,
387 CallInst::CallInst(Value *Func, const std::string &Name,
388 BasicBlock *InsertAtEnd)
389 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
390 ->getElementType())->getReturnType(),
392 OperandTraits<CallInst>::op_end(this) - 1,
398 CallInst::CallInst(const CallInst &CI)
399 : Instruction(CI.getType(), Instruction::Call,
400 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
401 CI.getNumOperands()) {
402 setAttributes(CI.getAttributes());
403 SubclassData = CI.SubclassData;
404 Use *OL = OperandList;
405 Use *InOL = CI.OperandList;
406 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
410 void CallInst::addAttribute(unsigned i, Attributes attr) {
411 AttrListPtr PAL = getAttributes();
412 PAL = PAL.addAttr(i, attr);
416 void CallInst::removeAttribute(unsigned i, Attributes attr) {
417 AttrListPtr PAL = getAttributes();
418 PAL = PAL.removeAttr(i, attr);
422 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
423 if (AttributeList.paramHasAttr(i, attr))
425 if (const Function *F = getCalledFunction())
426 return F->paramHasAttr(i, attr);
431 //===----------------------------------------------------------------------===//
432 // InvokeInst Implementation
433 //===----------------------------------------------------------------------===//
435 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
436 Value* const *Args, unsigned NumArgs) {
437 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
438 Use *OL = OperandList;
442 const FunctionType *FTy =
443 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
444 FTy = FTy; // silence warning.
446 assert(((NumArgs == FTy->getNumParams()) ||
447 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
448 "Calling a function with bad signature");
450 for (unsigned i = 0, e = NumArgs; i != e; i++) {
451 assert((i >= FTy->getNumParams() ||
452 FTy->getParamType(i) == Args[i]->getType()) &&
453 "Invoking a function with a bad signature!");
459 InvokeInst::InvokeInst(const InvokeInst &II)
460 : TerminatorInst(II.getType(), Instruction::Invoke,
461 OperandTraits<InvokeInst>::op_end(this)
462 - II.getNumOperands(),
463 II.getNumOperands()) {
464 setAttributes(II.getAttributes());
465 SubclassData = II.SubclassData;
466 Use *OL = OperandList, *InOL = II.OperandList;
467 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
471 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
472 return getSuccessor(idx);
474 unsigned InvokeInst::getNumSuccessorsV() const {
475 return getNumSuccessors();
477 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
478 return setSuccessor(idx, B);
481 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
482 if (AttributeList.paramHasAttr(i, attr))
484 if (const Function *F = getCalledFunction())
485 return F->paramHasAttr(i, attr);
489 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
490 AttrListPtr PAL = getAttributes();
491 PAL = PAL.addAttr(i, attr);
495 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
496 AttrListPtr PAL = getAttributes();
497 PAL = PAL.removeAttr(i, attr);
502 //===----------------------------------------------------------------------===//
503 // ReturnInst Implementation
504 //===----------------------------------------------------------------------===//
506 ReturnInst::ReturnInst(const ReturnInst &RI)
507 : TerminatorInst(Type::VoidTy, Instruction::Ret,
508 OperandTraits<ReturnInst>::op_end(this) -
510 RI.getNumOperands()) {
511 if (RI.getNumOperands())
512 Op<0>() = RI.Op<0>();
515 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
516 : TerminatorInst(Type::VoidTy, Instruction::Ret,
517 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
522 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
523 : TerminatorInst(Type::VoidTy, Instruction::Ret,
524 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
529 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
530 : TerminatorInst(Type::VoidTy, Instruction::Ret,
531 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
534 unsigned ReturnInst::getNumSuccessorsV() const {
535 return getNumSuccessors();
538 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
539 /// emit the vtable for the class in this translation unit.
540 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
541 llvm_unreachable("ReturnInst has no successors!");
544 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
545 llvm_unreachable("ReturnInst has no successors!");
549 ReturnInst::~ReturnInst() {
552 //===----------------------------------------------------------------------===//
553 // UnwindInst Implementation
554 //===----------------------------------------------------------------------===//
556 UnwindInst::UnwindInst(Instruction *InsertBefore)
557 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
559 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
560 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
564 unsigned UnwindInst::getNumSuccessorsV() const {
565 return getNumSuccessors();
568 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
569 llvm_unreachable("UnwindInst has no successors!");
572 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
573 llvm_unreachable("UnwindInst has no successors!");
577 //===----------------------------------------------------------------------===//
578 // UnreachableInst Implementation
579 //===----------------------------------------------------------------------===//
581 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
582 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
584 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
585 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
588 unsigned UnreachableInst::getNumSuccessorsV() const {
589 return getNumSuccessors();
592 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
593 llvm_unreachable("UnwindInst has no successors!");
596 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
597 llvm_unreachable("UnwindInst has no successors!");
601 //===----------------------------------------------------------------------===//
602 // BranchInst Implementation
603 //===----------------------------------------------------------------------===//
605 void BranchInst::AssertOK() {
607 assert(getCondition()->getType() == Type::Int1Ty &&
608 "May only branch on boolean predicates!");
611 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
612 : TerminatorInst(Type::VoidTy, Instruction::Br,
613 OperandTraits<BranchInst>::op_end(this) - 1,
615 assert(IfTrue != 0 && "Branch destination may not be null!");
618 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
619 Instruction *InsertBefore)
620 : TerminatorInst(Type::VoidTy, Instruction::Br,
621 OperandTraits<BranchInst>::op_end(this) - 3,
631 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
632 : TerminatorInst(Type::VoidTy, Instruction::Br,
633 OperandTraits<BranchInst>::op_end(this) - 1,
635 assert(IfTrue != 0 && "Branch destination may not be null!");
639 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
640 BasicBlock *InsertAtEnd)
641 : TerminatorInst(Type::VoidTy, Instruction::Br,
642 OperandTraits<BranchInst>::op_end(this) - 3,
653 BranchInst::BranchInst(const BranchInst &BI) :
654 TerminatorInst(Type::VoidTy, Instruction::Br,
655 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
656 BI.getNumOperands()) {
657 Op<-1>() = BI.Op<-1>();
658 if (BI.getNumOperands() != 1) {
659 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
660 Op<-3>() = BI.Op<-3>();
661 Op<-2>() = BI.Op<-2>();
666 Use* Use::getPrefix() {
667 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
668 if (PotentialPrefix.getOpaqueValue())
671 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
674 BranchInst::~BranchInst() {
675 if (NumOperands == 1) {
676 if (Use *Prefix = OperandList->getPrefix()) {
679 // mark OperandList to have a special value for scrutiny
680 // by baseclass destructors and operator delete
681 OperandList = Prefix;
684 OperandList = op_begin();
690 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
691 return getSuccessor(idx);
693 unsigned BranchInst::getNumSuccessorsV() const {
694 return getNumSuccessors();
696 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
697 setSuccessor(idx, B);
701 //===----------------------------------------------------------------------===//
702 // AllocationInst Implementation
703 //===----------------------------------------------------------------------===//
705 static Value *getAISize(LLVMContext &Context, Value *Amt) {
707 Amt = Context.getConstantInt(Type::Int32Ty, 1);
709 assert(!isa<BasicBlock>(Amt) &&
710 "Passed basic block into allocation size parameter! Use other ctor");
711 assert(Amt->getType() == Type::Int32Ty &&
712 "Malloc/Allocation array size is not a 32-bit integer!");
717 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
718 unsigned Align, const std::string &Name,
719 Instruction *InsertBefore)
720 : UnaryInstruction(Ty->getContext().getPointerTypeUnqual(Ty), iTy,
721 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
723 assert(Ty != Type::VoidTy && "Cannot allocate void!");
727 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
728 unsigned Align, const std::string &Name,
729 BasicBlock *InsertAtEnd)
730 : UnaryInstruction(Ty->getContext().getPointerTypeUnqual(Ty), iTy,
731 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
733 assert(Ty != Type::VoidTy && "Cannot allocate void!");
737 // Out of line virtual method, so the vtable, etc has a home.
738 AllocationInst::~AllocationInst() {
741 void AllocationInst::setAlignment(unsigned Align) {
742 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
743 SubclassData = Log2_32(Align) + 1;
744 assert(getAlignment() == Align && "Alignment representation error!");
747 bool AllocationInst::isArrayAllocation() const {
748 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
749 return CI->getZExtValue() != 1;
753 const Type *AllocationInst::getAllocatedType() const {
754 return getType()->getElementType();
757 AllocaInst::AllocaInst(const AllocaInst &AI)
758 : AllocationInst(AI.getType()->getElementType(),
759 (Value*)AI.getOperand(0), Instruction::Alloca,
763 /// isStaticAlloca - Return true if this alloca is in the entry block of the
764 /// function and is a constant size. If so, the code generator will fold it
765 /// into the prolog/epilog code, so it is basically free.
766 bool AllocaInst::isStaticAlloca() const {
767 // Must be constant size.
768 if (!isa<ConstantInt>(getArraySize())) return false;
770 // Must be in the entry block.
771 const BasicBlock *Parent = getParent();
772 return Parent == &Parent->getParent()->front();
775 MallocInst::MallocInst(const MallocInst &MI)
776 : AllocationInst(MI.getType()->getElementType(),
777 (Value*)MI.getOperand(0), Instruction::Malloc,
781 //===----------------------------------------------------------------------===//
782 // FreeInst Implementation
783 //===----------------------------------------------------------------------===//
785 void FreeInst::AssertOK() {
786 assert(isa<PointerType>(getOperand(0)->getType()) &&
787 "Can not free something of nonpointer type!");
790 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
791 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
795 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
796 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
801 //===----------------------------------------------------------------------===//
802 // LoadInst Implementation
803 //===----------------------------------------------------------------------===//
805 void LoadInst::AssertOK() {
806 assert(isa<PointerType>(getOperand(0)->getType()) &&
807 "Ptr must have pointer type.");
810 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
811 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
812 Load, Ptr, InsertBef) {
819 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
820 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
821 Load, Ptr, InsertAE) {
828 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
829 Instruction *InsertBef)
830 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
831 Load, Ptr, InsertBef) {
832 setVolatile(isVolatile);
838 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
839 unsigned Align, Instruction *InsertBef)
840 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
841 Load, Ptr, InsertBef) {
842 setVolatile(isVolatile);
848 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
849 unsigned Align, BasicBlock *InsertAE)
850 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
851 Load, Ptr, InsertAE) {
852 setVolatile(isVolatile);
858 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
859 BasicBlock *InsertAE)
860 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
861 Load, Ptr, InsertAE) {
862 setVolatile(isVolatile);
870 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
871 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
872 Load, Ptr, InsertBef) {
876 if (Name && Name[0]) setName(Name);
879 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
880 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
881 Load, Ptr, InsertAE) {
885 if (Name && Name[0]) setName(Name);
888 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
889 Instruction *InsertBef)
890 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
891 Load, Ptr, InsertBef) {
892 setVolatile(isVolatile);
895 if (Name && Name[0]) setName(Name);
898 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
899 BasicBlock *InsertAE)
900 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
901 Load, Ptr, InsertAE) {
902 setVolatile(isVolatile);
905 if (Name && Name[0]) setName(Name);
908 void LoadInst::setAlignment(unsigned Align) {
909 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
910 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
913 //===----------------------------------------------------------------------===//
914 // StoreInst Implementation
915 //===----------------------------------------------------------------------===//
917 void StoreInst::AssertOK() {
918 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
919 assert(isa<PointerType>(getOperand(1)->getType()) &&
920 "Ptr must have pointer type!");
921 assert(getOperand(0)->getType() ==
922 cast<PointerType>(getOperand(1)->getType())->getElementType()
923 && "Ptr must be a pointer to Val type!");
927 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
928 : Instruction(Type::VoidTy, Store,
929 OperandTraits<StoreInst>::op_begin(this),
930 OperandTraits<StoreInst>::operands(this),
939 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
940 : Instruction(Type::VoidTy, Store,
941 OperandTraits<StoreInst>::op_begin(this),
942 OperandTraits<StoreInst>::operands(this),
951 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
952 Instruction *InsertBefore)
953 : Instruction(Type::VoidTy, Store,
954 OperandTraits<StoreInst>::op_begin(this),
955 OperandTraits<StoreInst>::operands(this),
959 setVolatile(isVolatile);
964 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
965 unsigned Align, Instruction *InsertBefore)
966 : Instruction(Type::VoidTy, Store,
967 OperandTraits<StoreInst>::op_begin(this),
968 OperandTraits<StoreInst>::operands(this),
972 setVolatile(isVolatile);
977 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
978 unsigned Align, BasicBlock *InsertAtEnd)
979 : Instruction(Type::VoidTy, Store,
980 OperandTraits<StoreInst>::op_begin(this),
981 OperandTraits<StoreInst>::operands(this),
985 setVolatile(isVolatile);
990 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
991 BasicBlock *InsertAtEnd)
992 : Instruction(Type::VoidTy, Store,
993 OperandTraits<StoreInst>::op_begin(this),
994 OperandTraits<StoreInst>::operands(this),
998 setVolatile(isVolatile);
1003 void StoreInst::setAlignment(unsigned Align) {
1004 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1005 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1008 //===----------------------------------------------------------------------===//
1009 // GetElementPtrInst Implementation
1010 //===----------------------------------------------------------------------===//
1012 static unsigned retrieveAddrSpace(const Value *Val) {
1013 return cast<PointerType>(Val->getType())->getAddressSpace();
1016 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1017 const std::string &Name) {
1018 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1019 Use *OL = OperandList;
1022 for (unsigned i = 0; i != NumIdx; ++i)
1028 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1029 assert(NumOperands == 2 && "NumOperands not initialized?");
1030 Use *OL = OperandList;
1037 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1038 : Instruction(GEPI.getType(), GetElementPtr,
1039 OperandTraits<GetElementPtrInst>::op_end(this)
1040 - GEPI.getNumOperands(),
1041 GEPI.getNumOperands()) {
1042 Use *OL = OperandList;
1043 Use *GEPIOL = GEPI.OperandList;
1044 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1048 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1049 const std::string &Name, Instruction *InBe)
1050 : Instruction(Ptr->getType()->getContext().getPointerType(
1051 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1053 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1055 init(Ptr, Idx, Name);
1058 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1059 const std::string &Name, BasicBlock *IAE)
1060 : Instruction(Ptr->getType()->getContext().getPointerType(
1061 checkType(getIndexedType(Ptr->getType(),Idx)),
1062 retrieveAddrSpace(Ptr)),
1064 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1066 init(Ptr, Idx, Name);
1069 /// getIndexedType - Returns the type of the element that would be accessed with
1070 /// a gep instruction with the specified parameters.
1072 /// The Idxs pointer should point to a continuous piece of memory containing the
1073 /// indices, either as Value* or uint64_t.
1075 /// A null type is returned if the indices are invalid for the specified
1078 template <typename IndexTy>
1079 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1081 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1082 if (!PTy) return 0; // Type isn't a pointer type!
1083 const Type *Agg = PTy->getElementType();
1085 // Handle the special case of the empty set index set, which is always valid.
1089 // If there is at least one index, the top level type must be sized, otherwise
1090 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1091 // that contain opaque types) under the assumption that it will be resolved to
1092 // a sane type later.
1093 if (!Agg->isSized() && !Agg->isAbstract())
1096 unsigned CurIdx = 1;
1097 for (; CurIdx != NumIdx; ++CurIdx) {
1098 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1099 if (!CT || isa<PointerType>(CT)) return 0;
1100 IndexTy Index = Idxs[CurIdx];
1101 if (!CT->indexValid(Index)) return 0;
1102 Agg = CT->getTypeAtIndex(Index);
1104 // If the new type forwards to another type, then it is in the middle
1105 // of being refined to another type (and hence, may have dropped all
1106 // references to what it was using before). So, use the new forwarded
1108 if (const Type *Ty = Agg->getForwardedType())
1111 return CurIdx == NumIdx ? Agg : 0;
1114 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1117 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1120 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1121 uint64_t const *Idxs,
1123 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1126 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1127 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1128 if (!PTy) return 0; // Type isn't a pointer type!
1130 // Check the pointer index.
1131 if (!PTy->indexValid(Idx)) return 0;
1133 return PTy->getElementType();
1137 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1138 /// zeros. If so, the result pointer and the first operand have the same
1139 /// value, just potentially different types.
1140 bool GetElementPtrInst::hasAllZeroIndices() const {
1141 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1142 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1143 if (!CI->isZero()) return false;
1151 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1152 /// constant integers. If so, the result pointer and the first operand have
1153 /// a constant offset between them.
1154 bool GetElementPtrInst::hasAllConstantIndices() const {
1155 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1156 if (!isa<ConstantInt>(getOperand(i)))
1163 //===----------------------------------------------------------------------===//
1164 // ExtractElementInst Implementation
1165 //===----------------------------------------------------------------------===//
1167 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1168 const std::string &Name,
1169 Instruction *InsertBef)
1170 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1172 OperandTraits<ExtractElementInst>::op_begin(this),
1174 assert(isValidOperands(Val, Index) &&
1175 "Invalid extractelement instruction operands!");
1181 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1182 const std::string &Name,
1183 BasicBlock *InsertAE)
1184 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1186 OperandTraits<ExtractElementInst>::op_begin(this),
1188 assert(isValidOperands(Val, Index) &&
1189 "Invalid extractelement instruction operands!");
1197 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1198 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1204 //===----------------------------------------------------------------------===//
1205 // InsertElementInst Implementation
1206 //===----------------------------------------------------------------------===//
1208 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1209 : Instruction(IE.getType(), InsertElement,
1210 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1211 Op<0>() = IE.Op<0>();
1212 Op<1>() = IE.Op<1>();
1213 Op<2>() = IE.Op<2>();
1215 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1216 const std::string &Name,
1217 Instruction *InsertBef)
1218 : Instruction(Vec->getType(), InsertElement,
1219 OperandTraits<InsertElementInst>::op_begin(this),
1221 assert(isValidOperands(Vec, Elt, Index) &&
1222 "Invalid insertelement instruction operands!");
1229 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1230 const std::string &Name,
1231 BasicBlock *InsertAE)
1232 : Instruction(Vec->getType(), InsertElement,
1233 OperandTraits<InsertElementInst>::op_begin(this),
1235 assert(isValidOperands(Vec, Elt, Index) &&
1236 "Invalid insertelement instruction operands!");
1244 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1245 const Value *Index) {
1246 if (!isa<VectorType>(Vec->getType()))
1247 return false; // First operand of insertelement must be vector type.
1249 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1250 return false;// Second operand of insertelement must be vector element type.
1252 if (Index->getType() != Type::Int32Ty)
1253 return false; // Third operand of insertelement must be i32.
1258 //===----------------------------------------------------------------------===//
1259 // ShuffleVectorInst Implementation
1260 //===----------------------------------------------------------------------===//
1262 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1263 : Instruction(SV.getType(), ShuffleVector,
1264 OperandTraits<ShuffleVectorInst>::op_begin(this),
1265 OperandTraits<ShuffleVectorInst>::operands(this)) {
1266 Op<0>() = SV.Op<0>();
1267 Op<1>() = SV.Op<1>();
1268 Op<2>() = SV.Op<2>();
1271 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1272 const std::string &Name,
1273 Instruction *InsertBefore)
1274 : Instruction(V1->getType()->getContext().getVectorType(
1275 cast<VectorType>(V1->getType())->getElementType(),
1276 cast<VectorType>(Mask->getType())->getNumElements()),
1278 OperandTraits<ShuffleVectorInst>::op_begin(this),
1279 OperandTraits<ShuffleVectorInst>::operands(this),
1281 assert(isValidOperands(V1, V2, Mask) &&
1282 "Invalid shuffle vector instruction operands!");
1289 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1290 const std::string &Name,
1291 BasicBlock *InsertAtEnd)
1292 : Instruction(V1->getType(), ShuffleVector,
1293 OperandTraits<ShuffleVectorInst>::op_begin(this),
1294 OperandTraits<ShuffleVectorInst>::operands(this),
1296 assert(isValidOperands(V1, V2, Mask) &&
1297 "Invalid shuffle vector instruction operands!");
1305 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1306 const Value *Mask) {
1307 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1310 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1311 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1312 MaskTy->getElementType() != Type::Int32Ty)
1317 /// getMaskValue - Return the index from the shuffle mask for the specified
1318 /// output result. This is either -1 if the element is undef or a number less
1319 /// than 2*numelements.
1320 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1321 const Constant *Mask = cast<Constant>(getOperand(2));
1322 if (isa<UndefValue>(Mask)) return -1;
1323 if (isa<ConstantAggregateZero>(Mask)) return 0;
1324 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1325 assert(i < MaskCV->getNumOperands() && "Index out of range");
1327 if (isa<UndefValue>(MaskCV->getOperand(i)))
1329 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1332 //===----------------------------------------------------------------------===//
1333 // InsertValueInst Class
1334 //===----------------------------------------------------------------------===//
1336 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1337 unsigned NumIdx, const std::string &Name) {
1338 assert(NumOperands == 2 && "NumOperands not initialized?");
1342 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1346 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1347 const std::string &Name) {
1348 assert(NumOperands == 2 && "NumOperands not initialized?");
1352 Indices.push_back(Idx);
1356 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1357 : Instruction(IVI.getType(), InsertValue,
1358 OperandTraits<InsertValueInst>::op_begin(this), 2),
1359 Indices(IVI.Indices) {
1360 Op<0>() = IVI.getOperand(0);
1361 Op<1>() = IVI.getOperand(1);
1364 InsertValueInst::InsertValueInst(Value *Agg,
1367 const std::string &Name,
1368 Instruction *InsertBefore)
1369 : Instruction(Agg->getType(), InsertValue,
1370 OperandTraits<InsertValueInst>::op_begin(this),
1372 init(Agg, Val, Idx, Name);
1375 InsertValueInst::InsertValueInst(Value *Agg,
1378 const std::string &Name,
1379 BasicBlock *InsertAtEnd)
1380 : Instruction(Agg->getType(), InsertValue,
1381 OperandTraits<InsertValueInst>::op_begin(this),
1383 init(Agg, Val, Idx, Name);
1386 //===----------------------------------------------------------------------===//
1387 // ExtractValueInst Class
1388 //===----------------------------------------------------------------------===//
1390 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1391 const std::string &Name) {
1392 assert(NumOperands == 1 && "NumOperands not initialized?");
1394 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1398 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
1399 assert(NumOperands == 1 && "NumOperands not initialized?");
1401 Indices.push_back(Idx);
1405 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1406 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1407 Indices(EVI.Indices) {
1410 // getIndexedType - Returns the type of the element that would be extracted
1411 // with an extractvalue instruction with the specified parameters.
1413 // A null type is returned if the indices are invalid for the specified
1416 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1417 const unsigned *Idxs,
1419 unsigned CurIdx = 0;
1420 for (; CurIdx != NumIdx; ++CurIdx) {
1421 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1422 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1423 unsigned Index = Idxs[CurIdx];
1424 if (!CT->indexValid(Index)) return 0;
1425 Agg = CT->getTypeAtIndex(Index);
1427 // If the new type forwards to another type, then it is in the middle
1428 // of being refined to another type (and hence, may have dropped all
1429 // references to what it was using before). So, use the new forwarded
1431 if (const Type *Ty = Agg->getForwardedType())
1434 return CurIdx == NumIdx ? Agg : 0;
1437 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1439 return getIndexedType(Agg, &Idx, 1);
1442 //===----------------------------------------------------------------------===//
1443 // BinaryOperator Class
1444 //===----------------------------------------------------------------------===//
1446 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1447 /// type is floating-point, to help provide compatibility with an older API.
1449 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1451 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1452 if (Ty->isFPOrFPVector()) {
1453 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1454 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1455 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1460 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1461 const Type *Ty, const std::string &Name,
1462 Instruction *InsertBefore)
1463 : Instruction(Ty, AdjustIType(iType, Ty),
1464 OperandTraits<BinaryOperator>::op_begin(this),
1465 OperandTraits<BinaryOperator>::operands(this),
1469 init(AdjustIType(iType, Ty));
1473 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1474 const Type *Ty, const std::string &Name,
1475 BasicBlock *InsertAtEnd)
1476 : Instruction(Ty, AdjustIType(iType, Ty),
1477 OperandTraits<BinaryOperator>::op_begin(this),
1478 OperandTraits<BinaryOperator>::operands(this),
1482 init(AdjustIType(iType, Ty));
1487 void BinaryOperator::init(BinaryOps iType) {
1488 Value *LHS = getOperand(0), *RHS = getOperand(1);
1489 LHS = LHS; RHS = RHS; // Silence warnings.
1490 assert(LHS->getType() == RHS->getType() &&
1491 "Binary operator operand types must match!");
1496 assert(getType() == LHS->getType() &&
1497 "Arithmetic operation should return same type as operands!");
1498 assert(getType()->isIntOrIntVector() &&
1499 "Tried to create an integer operation on a non-integer type!");
1501 case FAdd: case FSub:
1503 assert(getType() == LHS->getType() &&
1504 "Arithmetic operation should return same type as operands!");
1505 assert(getType()->isFPOrFPVector() &&
1506 "Tried to create a floating-point operation on a "
1507 "non-floating-point type!");
1511 assert(getType() == LHS->getType() &&
1512 "Arithmetic operation should return same type as operands!");
1513 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1514 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1515 "Incorrect operand type (not integer) for S/UDIV");
1518 assert(getType() == LHS->getType() &&
1519 "Arithmetic operation should return same type as operands!");
1520 assert(getType()->isFPOrFPVector() &&
1521 "Incorrect operand type (not floating point) for FDIV");
1525 assert(getType() == LHS->getType() &&
1526 "Arithmetic operation should return same type as operands!");
1527 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1528 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1529 "Incorrect operand type (not integer) for S/UREM");
1532 assert(getType() == LHS->getType() &&
1533 "Arithmetic operation should return same type as operands!");
1534 assert(getType()->isFPOrFPVector() &&
1535 "Incorrect operand type (not floating point) for FREM");
1540 assert(getType() == LHS->getType() &&
1541 "Shift operation should return same type as operands!");
1542 assert((getType()->isInteger() ||
1543 (isa<VectorType>(getType()) &&
1544 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1545 "Tried to create a shift operation on a non-integral type!");
1549 assert(getType() == LHS->getType() &&
1550 "Logical operation should return same type as operands!");
1551 assert((getType()->isInteger() ||
1552 (isa<VectorType>(getType()) &&
1553 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1554 "Tried to create a logical operation on a non-integral type!");
1562 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1563 const std::string &Name,
1564 Instruction *InsertBefore) {
1565 assert(S1->getType() == S2->getType() &&
1566 "Cannot create binary operator with two operands of differing type!");
1567 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1570 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1571 const std::string &Name,
1572 BasicBlock *InsertAtEnd) {
1573 BinaryOperator *Res = Create(Op, S1, S2, Name);
1574 InsertAtEnd->getInstList().push_back(Res);
1578 BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context,
1579 Value *Op, const std::string &Name,
1580 Instruction *InsertBefore) {
1581 Value *zero = Context.getZeroValueForNegation(Op->getType());
1582 return new BinaryOperator(Instruction::Sub,
1584 Op->getType(), Name, InsertBefore);
1587 BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context,
1588 Value *Op, const std::string &Name,
1589 BasicBlock *InsertAtEnd) {
1590 Value *zero = Context.getZeroValueForNegation(Op->getType());
1591 return new BinaryOperator(Instruction::Sub,
1593 Op->getType(), Name, InsertAtEnd);
1596 BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context,
1597 Value *Op, const std::string &Name,
1598 Instruction *InsertBefore) {
1599 Value *zero = Context.getZeroValueForNegation(Op->getType());
1600 return new BinaryOperator(Instruction::FSub,
1602 Op->getType(), Name, InsertBefore);
1605 BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context,
1606 Value *Op, const std::string &Name,
1607 BasicBlock *InsertAtEnd) {
1608 Value *zero = Context.getZeroValueForNegation(Op->getType());
1609 return new BinaryOperator(Instruction::FSub,
1611 Op->getType(), Name, InsertAtEnd);
1614 BinaryOperator *BinaryOperator::CreateNot(LLVMContext &Context,
1615 Value *Op, const std::string &Name,
1616 Instruction *InsertBefore) {
1618 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1619 C = Context.getAllOnesValue(PTy->getElementType());
1620 C = Context.getConstantVector(
1621 std::vector<Constant*>(PTy->getNumElements(), C));
1623 C = Context.getAllOnesValue(Op->getType());
1626 return new BinaryOperator(Instruction::Xor, Op, C,
1627 Op->getType(), Name, InsertBefore);
1630 BinaryOperator *BinaryOperator::CreateNot(LLVMContext &Context,
1631 Value *Op, const std::string &Name,
1632 BasicBlock *InsertAtEnd) {
1634 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1635 // Create a vector of all ones values.
1636 Constant *Elt = Context.getAllOnesValue(PTy->getElementType());
1637 AllOnes = Context.getConstantVector(
1638 std::vector<Constant*>(PTy->getNumElements(), Elt));
1640 AllOnes = Context.getAllOnesValue(Op->getType());
1643 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1644 Op->getType(), Name, InsertAtEnd);
1648 // isConstantAllOnes - Helper function for several functions below
1649 static inline bool isConstantAllOnes(const Value *V) {
1650 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1651 return CI->isAllOnesValue();
1652 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1653 return CV->isAllOnesValue();
1657 bool BinaryOperator::isNeg(const Value *V) {
1658 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1659 if (Bop->getOpcode() == Instruction::Sub)
1660 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1661 return C->isNegativeZeroValue();
1665 bool BinaryOperator::isFNeg(const Value *V) {
1666 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1667 if (Bop->getOpcode() == Instruction::FSub)
1668 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1669 return C->isNegativeZeroValue();
1673 bool BinaryOperator::isNot(const Value *V) {
1674 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1675 return (Bop->getOpcode() == Instruction::Xor &&
1676 (isConstantAllOnes(Bop->getOperand(1)) ||
1677 isConstantAllOnes(Bop->getOperand(0))));
1681 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1682 return cast<BinaryOperator>(BinOp)->getOperand(1);
1685 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1686 return getNegArgument(const_cast<Value*>(BinOp));
1689 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1690 return cast<BinaryOperator>(BinOp)->getOperand(1);
1693 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1694 return getFNegArgument(const_cast<Value*>(BinOp));
1697 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1698 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1699 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1700 Value *Op0 = BO->getOperand(0);
1701 Value *Op1 = BO->getOperand(1);
1702 if (isConstantAllOnes(Op0)) return Op1;
1704 assert(isConstantAllOnes(Op1));
1708 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1709 return getNotArgument(const_cast<Value*>(BinOp));
1713 // swapOperands - Exchange the two operands to this instruction. This
1714 // instruction is safe to use on any binary instruction and does not
1715 // modify the semantics of the instruction. If the instruction is
1716 // order dependent (SetLT f.e.) the opcode is changed.
1718 bool BinaryOperator::swapOperands() {
1719 if (!isCommutative())
1720 return true; // Can't commute operands
1721 Op<0>().swap(Op<1>());
1725 //===----------------------------------------------------------------------===//
1727 //===----------------------------------------------------------------------===//
1729 // Just determine if this cast only deals with integral->integral conversion.
1730 bool CastInst::isIntegerCast() const {
1731 switch (getOpcode()) {
1732 default: return false;
1733 case Instruction::ZExt:
1734 case Instruction::SExt:
1735 case Instruction::Trunc:
1737 case Instruction::BitCast:
1738 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1742 bool CastInst::isLosslessCast() const {
1743 // Only BitCast can be lossless, exit fast if we're not BitCast
1744 if (getOpcode() != Instruction::BitCast)
1747 // Identity cast is always lossless
1748 const Type* SrcTy = getOperand(0)->getType();
1749 const Type* DstTy = getType();
1753 // Pointer to pointer is always lossless.
1754 if (isa<PointerType>(SrcTy))
1755 return isa<PointerType>(DstTy);
1756 return false; // Other types have no identity values
1759 /// This function determines if the CastInst does not require any bits to be
1760 /// changed in order to effect the cast. Essentially, it identifies cases where
1761 /// no code gen is necessary for the cast, hence the name no-op cast. For
1762 /// example, the following are all no-op casts:
1763 /// # bitcast i32* %x to i8*
1764 /// # bitcast <2 x i32> %x to <4 x i16>
1765 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1766 /// @brief Determine if a cast is a no-op.
1767 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1768 switch (getOpcode()) {
1770 assert(!"Invalid CastOp");
1771 case Instruction::Trunc:
1772 case Instruction::ZExt:
1773 case Instruction::SExt:
1774 case Instruction::FPTrunc:
1775 case Instruction::FPExt:
1776 case Instruction::UIToFP:
1777 case Instruction::SIToFP:
1778 case Instruction::FPToUI:
1779 case Instruction::FPToSI:
1780 return false; // These always modify bits
1781 case Instruction::BitCast:
1782 return true; // BitCast never modifies bits.
1783 case Instruction::PtrToInt:
1784 return IntPtrTy->getScalarSizeInBits() ==
1785 getType()->getScalarSizeInBits();
1786 case Instruction::IntToPtr:
1787 return IntPtrTy->getScalarSizeInBits() ==
1788 getOperand(0)->getType()->getScalarSizeInBits();
1792 /// This function determines if a pair of casts can be eliminated and what
1793 /// opcode should be used in the elimination. This assumes that there are two
1794 /// instructions like this:
1795 /// * %F = firstOpcode SrcTy %x to MidTy
1796 /// * %S = secondOpcode MidTy %F to DstTy
1797 /// The function returns a resultOpcode so these two casts can be replaced with:
1798 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1799 /// If no such cast is permited, the function returns 0.
1800 unsigned CastInst::isEliminableCastPair(
1801 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1802 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1804 // Define the 144 possibilities for these two cast instructions. The values
1805 // in this matrix determine what to do in a given situation and select the
1806 // case in the switch below. The rows correspond to firstOp, the columns
1807 // correspond to secondOp. In looking at the table below, keep in mind
1808 // the following cast properties:
1810 // Size Compare Source Destination
1811 // Operator Src ? Size Type Sign Type Sign
1812 // -------- ------------ ------------------- ---------------------
1813 // TRUNC > Integer Any Integral Any
1814 // ZEXT < Integral Unsigned Integer Any
1815 // SEXT < Integral Signed Integer Any
1816 // FPTOUI n/a FloatPt n/a Integral Unsigned
1817 // FPTOSI n/a FloatPt n/a Integral Signed
1818 // UITOFP n/a Integral Unsigned FloatPt n/a
1819 // SITOFP n/a Integral Signed FloatPt n/a
1820 // FPTRUNC > FloatPt n/a FloatPt n/a
1821 // FPEXT < FloatPt n/a FloatPt n/a
1822 // PTRTOINT n/a Pointer n/a Integral Unsigned
1823 // INTTOPTR n/a Integral Unsigned Pointer n/a
1824 // BITCONVERT = FirstClass n/a FirstClass n/a
1826 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1827 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
1828 // into "fptoui double to i64", but this loses information about the range
1829 // of the produced value (we no longer know the top-part is all zeros).
1830 // Further this conversion is often much more expensive for typical hardware,
1831 // and causes issues when building libgcc. We disallow fptosi+sext for the
1833 const unsigned numCastOps =
1834 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1835 static const uint8_t CastResults[numCastOps][numCastOps] = {
1836 // T F F U S F F P I B -+
1837 // R Z S P P I I T P 2 N T |
1838 // U E E 2 2 2 2 R E I T C +- secondOp
1839 // N X X U S F F N X N 2 V |
1840 // C T T I I P P C T T P T -+
1841 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1842 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1843 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1844 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1845 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1846 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1847 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1848 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1849 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1850 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1851 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1852 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1855 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1856 [secondOp-Instruction::CastOpsBegin];
1859 // categorically disallowed
1862 // allowed, use first cast's opcode
1865 // allowed, use second cast's opcode
1868 // no-op cast in second op implies firstOp as long as the DestTy
1870 if (DstTy->isInteger())
1874 // no-op cast in second op implies firstOp as long as the DestTy
1875 // is floating point
1876 if (DstTy->isFloatingPoint())
1880 // no-op cast in first op implies secondOp as long as the SrcTy
1882 if (SrcTy->isInteger())
1886 // no-op cast in first op implies secondOp as long as the SrcTy
1887 // is a floating point
1888 if (SrcTy->isFloatingPoint())
1892 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1895 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1896 unsigned MidSize = MidTy->getScalarSizeInBits();
1897 if (MidSize >= PtrSize)
1898 return Instruction::BitCast;
1902 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1903 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1904 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1905 unsigned SrcSize = SrcTy->getScalarSizeInBits();
1906 unsigned DstSize = DstTy->getScalarSizeInBits();
1907 if (SrcSize == DstSize)
1908 return Instruction::BitCast;
1909 else if (SrcSize < DstSize)
1913 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1914 return Instruction::ZExt;
1916 // fpext followed by ftrunc is allowed if the bit size returned to is
1917 // the same as the original, in which case its just a bitcast
1919 return Instruction::BitCast;
1920 return 0; // If the types are not the same we can't eliminate it.
1922 // bitcast followed by ptrtoint is allowed as long as the bitcast
1923 // is a pointer to pointer cast.
1924 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1928 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1929 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1933 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1936 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1937 unsigned SrcSize = SrcTy->getScalarSizeInBits();
1938 unsigned DstSize = DstTy->getScalarSizeInBits();
1939 if (SrcSize <= PtrSize && SrcSize == DstSize)
1940 return Instruction::BitCast;
1944 // cast combination can't happen (error in input). This is for all cases
1945 // where the MidTy is not the same for the two cast instructions.
1946 assert(!"Invalid Cast Combination");
1949 assert(!"Error in CastResults table!!!");
1955 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1956 const std::string &Name, Instruction *InsertBefore) {
1957 // Construct and return the appropriate CastInst subclass
1959 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1960 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1961 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1962 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1963 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1964 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1965 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1966 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1967 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1968 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1969 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1970 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1972 assert(!"Invalid opcode provided");
1977 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1978 const std::string &Name, BasicBlock *InsertAtEnd) {
1979 // Construct and return the appropriate CastInst subclass
1981 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1982 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1983 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1984 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1985 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1986 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1987 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1988 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1989 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1990 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1991 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1992 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1994 assert(!"Invalid opcode provided");
1999 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2000 const std::string &Name,
2001 Instruction *InsertBefore) {
2002 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2003 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2004 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2007 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2008 const std::string &Name,
2009 BasicBlock *InsertAtEnd) {
2010 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2011 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2012 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2015 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2016 const std::string &Name,
2017 Instruction *InsertBefore) {
2018 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2019 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2020 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2023 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2024 const std::string &Name,
2025 BasicBlock *InsertAtEnd) {
2026 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2027 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2028 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2031 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2032 const std::string &Name,
2033 Instruction *InsertBefore) {
2034 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2035 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2036 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2039 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2040 const std::string &Name,
2041 BasicBlock *InsertAtEnd) {
2042 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2043 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2044 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2047 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2048 const std::string &Name,
2049 BasicBlock *InsertAtEnd) {
2050 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2051 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2054 if (Ty->isInteger())
2055 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2056 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2059 /// @brief Create a BitCast or a PtrToInt cast instruction
2060 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2061 const std::string &Name,
2062 Instruction *InsertBefore) {
2063 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2064 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2067 if (Ty->isInteger())
2068 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2069 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2072 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2073 bool isSigned, const std::string &Name,
2074 Instruction *InsertBefore) {
2075 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2076 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2077 unsigned DstBits = Ty->getScalarSizeInBits();
2078 Instruction::CastOps opcode =
2079 (SrcBits == DstBits ? Instruction::BitCast :
2080 (SrcBits > DstBits ? Instruction::Trunc :
2081 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2082 return Create(opcode, C, Ty, Name, InsertBefore);
2085 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2086 bool isSigned, const std::string &Name,
2087 BasicBlock *InsertAtEnd) {
2088 assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() &&
2090 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2091 unsigned DstBits = Ty->getScalarSizeInBits();
2092 Instruction::CastOps opcode =
2093 (SrcBits == DstBits ? Instruction::BitCast :
2094 (SrcBits > DstBits ? Instruction::Trunc :
2095 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2096 return Create(opcode, C, Ty, Name, InsertAtEnd);
2099 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2100 const std::string &Name,
2101 Instruction *InsertBefore) {
2102 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2104 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2105 unsigned DstBits = Ty->getScalarSizeInBits();
2106 Instruction::CastOps opcode =
2107 (SrcBits == DstBits ? Instruction::BitCast :
2108 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2109 return Create(opcode, C, Ty, Name, InsertBefore);
2112 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2113 const std::string &Name,
2114 BasicBlock *InsertAtEnd) {
2115 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2117 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2118 unsigned DstBits = Ty->getScalarSizeInBits();
2119 Instruction::CastOps opcode =
2120 (SrcBits == DstBits ? Instruction::BitCast :
2121 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2122 return Create(opcode, C, Ty, Name, InsertAtEnd);
2125 // Check whether it is valid to call getCastOpcode for these types.
2126 // This routine must be kept in sync with getCastOpcode.
2127 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2128 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2131 if (SrcTy == DestTy)
2134 // Get the bit sizes, we'll need these
2135 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2136 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2138 // Run through the possibilities ...
2139 if (DestTy->isInteger()) { // Casting to integral
2140 if (SrcTy->isInteger()) { // Casting from integral
2142 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2144 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2145 // Casting from vector
2146 return DestBits == PTy->getBitWidth();
2147 } else { // Casting from something else
2148 return isa<PointerType>(SrcTy);
2150 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2151 if (SrcTy->isInteger()) { // Casting from integral
2153 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2155 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2156 // Casting from vector
2157 return DestBits == PTy->getBitWidth();
2158 } else { // Casting from something else
2161 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2162 // Casting to vector
2163 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2164 // Casting from vector
2165 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2166 } else { // Casting from something else
2167 return DestPTy->getBitWidth() == SrcBits;
2169 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2170 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2172 } else if (SrcTy->isInteger()) { // Casting from integral
2174 } else { // Casting from something else
2177 } else { // Casting to something else
2182 // Provide a way to get a "cast" where the cast opcode is inferred from the
2183 // types and size of the operand. This, basically, is a parallel of the
2184 // logic in the castIsValid function below. This axiom should hold:
2185 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2186 // should not assert in castIsValid. In other words, this produces a "correct"
2187 // casting opcode for the arguments passed to it.
2188 // This routine must be kept in sync with isCastable.
2189 Instruction::CastOps
2190 CastInst::getCastOpcode(
2191 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2192 // Get the bit sizes, we'll need these
2193 const Type *SrcTy = Src->getType();
2194 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2195 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2197 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2198 "Only first class types are castable!");
2200 // Run through the possibilities ...
2201 if (DestTy->isInteger()) { // Casting to integral
2202 if (SrcTy->isInteger()) { // Casting from integral
2203 if (DestBits < SrcBits)
2204 return Trunc; // int -> smaller int
2205 else if (DestBits > SrcBits) { // its an extension
2207 return SExt; // signed -> SEXT
2209 return ZExt; // unsigned -> ZEXT
2211 return BitCast; // Same size, No-op cast
2213 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2215 return FPToSI; // FP -> sint
2217 return FPToUI; // FP -> uint
2218 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2219 assert(DestBits == PTy->getBitWidth() &&
2220 "Casting vector to integer of different width");
2222 return BitCast; // Same size, no-op cast
2224 assert(isa<PointerType>(SrcTy) &&
2225 "Casting from a value that is not first-class type");
2226 return PtrToInt; // ptr -> int
2228 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2229 if (SrcTy->isInteger()) { // Casting from integral
2231 return SIToFP; // sint -> FP
2233 return UIToFP; // uint -> FP
2234 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2235 if (DestBits < SrcBits) {
2236 return FPTrunc; // FP -> smaller FP
2237 } else if (DestBits > SrcBits) {
2238 return FPExt; // FP -> larger FP
2240 return BitCast; // same size, no-op cast
2242 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2243 assert(DestBits == PTy->getBitWidth() &&
2244 "Casting vector to floating point of different width");
2246 return BitCast; // same size, no-op cast
2248 llvm_unreachable("Casting pointer or non-first class to float");
2250 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2251 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2252 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2253 "Casting vector to vector of different widths");
2255 return BitCast; // vector -> vector
2256 } else if (DestPTy->getBitWidth() == SrcBits) {
2257 return BitCast; // float/int -> vector
2259 assert(!"Illegal cast to vector (wrong type or size)");
2261 } else if (isa<PointerType>(DestTy)) {
2262 if (isa<PointerType>(SrcTy)) {
2263 return BitCast; // ptr -> ptr
2264 } else if (SrcTy->isInteger()) {
2265 return IntToPtr; // int -> ptr
2267 assert(!"Casting pointer to other than pointer or int");
2270 assert(!"Casting to type that is not first-class");
2273 // If we fall through to here we probably hit an assertion cast above
2274 // and assertions are not turned on. Anything we return is an error, so
2275 // BitCast is as good a choice as any.
2279 //===----------------------------------------------------------------------===//
2280 // CastInst SubClass Constructors
2281 //===----------------------------------------------------------------------===//
2283 /// Check that the construction parameters for a CastInst are correct. This
2284 /// could be broken out into the separate constructors but it is useful to have
2285 /// it in one place and to eliminate the redundant code for getting the sizes
2286 /// of the types involved.
2288 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2290 // Check for type sanity on the arguments
2291 const Type *SrcTy = S->getType();
2292 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2295 // Get the size of the types in bits, we'll need this later
2296 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2297 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2299 // Switch on the opcode provided
2301 default: return false; // This is an input error
2302 case Instruction::Trunc:
2303 return SrcTy->isIntOrIntVector() &&
2304 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2305 case Instruction::ZExt:
2306 return SrcTy->isIntOrIntVector() &&
2307 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2308 case Instruction::SExt:
2309 return SrcTy->isIntOrIntVector() &&
2310 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2311 case Instruction::FPTrunc:
2312 return SrcTy->isFPOrFPVector() &&
2313 DstTy->isFPOrFPVector() &&
2314 SrcBitSize > DstBitSize;
2315 case Instruction::FPExt:
2316 return SrcTy->isFPOrFPVector() &&
2317 DstTy->isFPOrFPVector() &&
2318 SrcBitSize < DstBitSize;
2319 case Instruction::UIToFP:
2320 case Instruction::SIToFP:
2321 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2322 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2323 return SVTy->getElementType()->isIntOrIntVector() &&
2324 DVTy->getElementType()->isFPOrFPVector() &&
2325 SVTy->getNumElements() == DVTy->getNumElements();
2328 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2329 case Instruction::FPToUI:
2330 case Instruction::FPToSI:
2331 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2332 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2333 return SVTy->getElementType()->isFPOrFPVector() &&
2334 DVTy->getElementType()->isIntOrIntVector() &&
2335 SVTy->getNumElements() == DVTy->getNumElements();
2338 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2339 case Instruction::PtrToInt:
2340 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2341 case Instruction::IntToPtr:
2342 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2343 case Instruction::BitCast:
2344 // BitCast implies a no-op cast of type only. No bits change.
2345 // However, you can't cast pointers to anything but pointers.
2346 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2349 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2350 // these cases, the cast is okay if the source and destination bit widths
2352 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2356 TruncInst::TruncInst(
2357 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2358 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2359 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2362 TruncInst::TruncInst(
2363 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2364 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2365 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2369 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2370 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2371 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2375 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2376 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2377 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2380 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2381 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2382 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2386 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2387 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2388 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2391 FPTruncInst::FPTruncInst(
2392 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2393 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2394 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2397 FPTruncInst::FPTruncInst(
2398 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2399 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2400 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2403 FPExtInst::FPExtInst(
2404 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2405 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2406 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2409 FPExtInst::FPExtInst(
2410 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2411 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2412 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2415 UIToFPInst::UIToFPInst(
2416 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2417 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2418 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2421 UIToFPInst::UIToFPInst(
2422 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2423 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2424 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2427 SIToFPInst::SIToFPInst(
2428 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2429 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2430 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2433 SIToFPInst::SIToFPInst(
2434 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2435 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2436 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2439 FPToUIInst::FPToUIInst(
2440 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2441 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2442 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2445 FPToUIInst::FPToUIInst(
2446 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2447 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2448 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2451 FPToSIInst::FPToSIInst(
2452 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2453 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2454 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2457 FPToSIInst::FPToSIInst(
2458 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2459 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2460 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2463 PtrToIntInst::PtrToIntInst(
2464 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2465 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2466 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2469 PtrToIntInst::PtrToIntInst(
2470 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2471 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2472 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2475 IntToPtrInst::IntToPtrInst(
2476 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2477 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2478 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2481 IntToPtrInst::IntToPtrInst(
2482 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2483 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2484 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2487 BitCastInst::BitCastInst(
2488 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2489 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2490 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2493 BitCastInst::BitCastInst(
2494 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2495 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2496 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2499 //===----------------------------------------------------------------------===//
2501 //===----------------------------------------------------------------------===//
2503 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2504 Value *LHS, Value *RHS, const std::string &Name,
2505 Instruction *InsertBefore)
2506 : Instruction(ty, op,
2507 OperandTraits<CmpInst>::op_begin(this),
2508 OperandTraits<CmpInst>::operands(this),
2512 SubclassData = predicate;
2516 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2517 Value *LHS, Value *RHS, const std::string &Name,
2518 BasicBlock *InsertAtEnd)
2519 : Instruction(ty, op,
2520 OperandTraits<CmpInst>::op_begin(this),
2521 OperandTraits<CmpInst>::operands(this),
2525 SubclassData = predicate;
2530 CmpInst::Create(LLVMContext &Context, OtherOps Op, unsigned short predicate,
2531 Value *S1, Value *S2,
2532 const std::string &Name, Instruction *InsertBefore) {
2533 if (Op == Instruction::ICmp) {
2535 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2538 return new ICmpInst(Context, CmpInst::Predicate(predicate),
2543 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2546 return new FCmpInst(Context, CmpInst::Predicate(predicate),
2551 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2552 const std::string &Name, BasicBlock *InsertAtEnd) {
2553 if (Op == Instruction::ICmp) {
2554 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2557 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2561 void CmpInst::swapOperands() {
2562 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2565 cast<FCmpInst>(this)->swapOperands();
2568 bool CmpInst::isCommutative() {
2569 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2570 return IC->isCommutative();
2571 return cast<FCmpInst>(this)->isCommutative();
2574 bool CmpInst::isEquality() {
2575 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2576 return IC->isEquality();
2577 return cast<FCmpInst>(this)->isEquality();
2581 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2583 default: assert(!"Unknown cmp predicate!");
2584 case ICMP_EQ: return ICMP_NE;
2585 case ICMP_NE: return ICMP_EQ;
2586 case ICMP_UGT: return ICMP_ULE;
2587 case ICMP_ULT: return ICMP_UGE;
2588 case ICMP_UGE: return ICMP_ULT;
2589 case ICMP_ULE: return ICMP_UGT;
2590 case ICMP_SGT: return ICMP_SLE;
2591 case ICMP_SLT: return ICMP_SGE;
2592 case ICMP_SGE: return ICMP_SLT;
2593 case ICMP_SLE: return ICMP_SGT;
2595 case FCMP_OEQ: return FCMP_UNE;
2596 case FCMP_ONE: return FCMP_UEQ;
2597 case FCMP_OGT: return FCMP_ULE;
2598 case FCMP_OLT: return FCMP_UGE;
2599 case FCMP_OGE: return FCMP_ULT;
2600 case FCMP_OLE: return FCMP_UGT;
2601 case FCMP_UEQ: return FCMP_ONE;
2602 case FCMP_UNE: return FCMP_OEQ;
2603 case FCMP_UGT: return FCMP_OLE;
2604 case FCMP_ULT: return FCMP_OGE;
2605 case FCMP_UGE: return FCMP_OLT;
2606 case FCMP_ULE: return FCMP_OGT;
2607 case FCMP_ORD: return FCMP_UNO;
2608 case FCMP_UNO: return FCMP_ORD;
2609 case FCMP_TRUE: return FCMP_FALSE;
2610 case FCMP_FALSE: return FCMP_TRUE;
2614 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2616 default: assert(! "Unknown icmp predicate!");
2617 case ICMP_EQ: case ICMP_NE:
2618 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2620 case ICMP_UGT: return ICMP_SGT;
2621 case ICMP_ULT: return ICMP_SLT;
2622 case ICMP_UGE: return ICMP_SGE;
2623 case ICMP_ULE: return ICMP_SLE;
2627 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2629 default: assert(! "Unknown icmp predicate!");
2630 case ICMP_EQ: case ICMP_NE:
2631 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2633 case ICMP_SGT: return ICMP_UGT;
2634 case ICMP_SLT: return ICMP_ULT;
2635 case ICMP_SGE: return ICMP_UGE;
2636 case ICMP_SLE: return ICMP_ULE;
2640 bool ICmpInst::isSignedPredicate(Predicate pred) {
2642 default: assert(! "Unknown icmp predicate!");
2643 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2645 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2646 case ICMP_UGE: case ICMP_ULE:
2651 /// Initialize a set of values that all satisfy the condition with C.
2654 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2657 uint32_t BitWidth = C.getBitWidth();
2659 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2660 case ICmpInst::ICMP_EQ: Upper++; break;
2661 case ICmpInst::ICMP_NE: Lower++; break;
2662 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2663 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2664 case ICmpInst::ICMP_UGT:
2665 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2667 case ICmpInst::ICMP_SGT:
2668 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2670 case ICmpInst::ICMP_ULE:
2671 Lower = APInt::getMinValue(BitWidth); Upper++;
2673 case ICmpInst::ICMP_SLE:
2674 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2676 case ICmpInst::ICMP_UGE:
2677 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2679 case ICmpInst::ICMP_SGE:
2680 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2683 return ConstantRange(Lower, Upper);
2686 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2688 default: assert(!"Unknown cmp predicate!");
2689 case ICMP_EQ: case ICMP_NE:
2691 case ICMP_SGT: return ICMP_SLT;
2692 case ICMP_SLT: return ICMP_SGT;
2693 case ICMP_SGE: return ICMP_SLE;
2694 case ICMP_SLE: return ICMP_SGE;
2695 case ICMP_UGT: return ICMP_ULT;
2696 case ICMP_ULT: return ICMP_UGT;
2697 case ICMP_UGE: return ICMP_ULE;
2698 case ICMP_ULE: return ICMP_UGE;
2700 case FCMP_FALSE: case FCMP_TRUE:
2701 case FCMP_OEQ: case FCMP_ONE:
2702 case FCMP_UEQ: case FCMP_UNE:
2703 case FCMP_ORD: case FCMP_UNO:
2705 case FCMP_OGT: return FCMP_OLT;
2706 case FCMP_OLT: return FCMP_OGT;
2707 case FCMP_OGE: return FCMP_OLE;
2708 case FCMP_OLE: return FCMP_OGE;
2709 case FCMP_UGT: return FCMP_ULT;
2710 case FCMP_ULT: return FCMP_UGT;
2711 case FCMP_UGE: return FCMP_ULE;
2712 case FCMP_ULE: return FCMP_UGE;
2716 bool CmpInst::isUnsigned(unsigned short predicate) {
2717 switch (predicate) {
2718 default: return false;
2719 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2720 case ICmpInst::ICMP_UGE: return true;
2724 bool CmpInst::isSigned(unsigned short predicate){
2725 switch (predicate) {
2726 default: return false;
2727 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2728 case ICmpInst::ICMP_SGE: return true;
2732 bool CmpInst::isOrdered(unsigned short predicate) {
2733 switch (predicate) {
2734 default: return false;
2735 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2736 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2737 case FCmpInst::FCMP_ORD: return true;
2741 bool CmpInst::isUnordered(unsigned short predicate) {
2742 switch (predicate) {
2743 default: return false;
2744 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2745 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2746 case FCmpInst::FCMP_UNO: return true;
2750 //===----------------------------------------------------------------------===//
2751 // SwitchInst Implementation
2752 //===----------------------------------------------------------------------===//
2754 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2755 assert(Value && Default);
2756 ReservedSpace = 2+NumCases*2;
2758 OperandList = allocHungoffUses(ReservedSpace);
2760 OperandList[0] = Value;
2761 OperandList[1] = Default;
2764 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2765 /// switch on and a default destination. The number of additional cases can
2766 /// be specified here to make memory allocation more efficient. This
2767 /// constructor can also autoinsert before another instruction.
2768 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2769 Instruction *InsertBefore)
2770 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2771 init(Value, Default, NumCases);
2774 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2775 /// switch on and a default destination. The number of additional cases can
2776 /// be specified here to make memory allocation more efficient. This
2777 /// constructor also autoinserts at the end of the specified BasicBlock.
2778 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2779 BasicBlock *InsertAtEnd)
2780 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2781 init(Value, Default, NumCases);
2784 SwitchInst::SwitchInst(const SwitchInst &SI)
2785 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2786 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2787 Use *OL = OperandList, *InOL = SI.OperandList;
2788 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2790 OL[i+1] = InOL[i+1];
2794 SwitchInst::~SwitchInst() {
2795 dropHungoffUses(OperandList);
2799 /// addCase - Add an entry to the switch instruction...
2801 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2802 unsigned OpNo = NumOperands;
2803 if (OpNo+2 > ReservedSpace)
2804 resizeOperands(0); // Get more space!
2805 // Initialize some new operands.
2806 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2807 NumOperands = OpNo+2;
2808 OperandList[OpNo] = OnVal;
2809 OperandList[OpNo+1] = Dest;
2812 /// removeCase - This method removes the specified successor from the switch
2813 /// instruction. Note that this cannot be used to remove the default
2814 /// destination (successor #0).
2816 void SwitchInst::removeCase(unsigned idx) {
2817 assert(idx != 0 && "Cannot remove the default case!");
2818 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2820 unsigned NumOps = getNumOperands();
2821 Use *OL = OperandList;
2823 // Move everything after this operand down.
2825 // FIXME: we could just swap with the end of the list, then erase. However,
2826 // client might not expect this to happen. The code as it is thrashes the
2827 // use/def lists, which is kinda lame.
2828 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2830 OL[i-2+1] = OL[i+1];
2833 // Nuke the last value.
2834 OL[NumOps-2].set(0);
2835 OL[NumOps-2+1].set(0);
2836 NumOperands = NumOps-2;
2839 /// resizeOperands - resize operands - This adjusts the length of the operands
2840 /// list according to the following behavior:
2841 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2842 /// of operation. This grows the number of ops by 3 times.
2843 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2844 /// 3. If NumOps == NumOperands, trim the reserved space.
2846 void SwitchInst::resizeOperands(unsigned NumOps) {
2847 unsigned e = getNumOperands();
2850 } else if (NumOps*2 > NumOperands) {
2851 // No resize needed.
2852 if (ReservedSpace >= NumOps) return;
2853 } else if (NumOps == NumOperands) {
2854 if (ReservedSpace == NumOps) return;
2859 ReservedSpace = NumOps;
2860 Use *NewOps = allocHungoffUses(NumOps);
2861 Use *OldOps = OperandList;
2862 for (unsigned i = 0; i != e; ++i) {
2863 NewOps[i] = OldOps[i];
2865 OperandList = NewOps;
2866 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2870 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2871 return getSuccessor(idx);
2873 unsigned SwitchInst::getNumSuccessorsV() const {
2874 return getNumSuccessors();
2876 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2877 setSuccessor(idx, B);
2880 // Define these methods here so vtables don't get emitted into every translation
2881 // unit that uses these classes.
2883 GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const {
2884 return new(getNumOperands()) GetElementPtrInst(*this);
2887 BinaryOperator *BinaryOperator::clone(LLVMContext&) const {
2888 return Create(getOpcode(), Op<0>(), Op<1>());
2891 FCmpInst* FCmpInst::clone(LLVMContext &Context) const {
2892 return new FCmpInst(Context, getPredicate(), Op<0>(), Op<1>());
2894 ICmpInst* ICmpInst::clone(LLVMContext &Context) const {
2895 return new ICmpInst(Context, getPredicate(), Op<0>(), Op<1>());
2898 ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const {
2899 return new ExtractValueInst(*this);
2901 InsertValueInst *InsertValueInst::clone(LLVMContext&) const {
2902 return new InsertValueInst(*this);
2905 MallocInst *MallocInst::clone(LLVMContext&) const {
2906 return new MallocInst(*this);
2909 AllocaInst *AllocaInst::clone(LLVMContext&) const {
2910 return new AllocaInst(*this);
2913 FreeInst *FreeInst::clone(LLVMContext&) const {
2914 return new FreeInst(getOperand(0));
2917 LoadInst *LoadInst::clone(LLVMContext&) const {
2918 return new LoadInst(*this);
2921 StoreInst *StoreInst::clone(LLVMContext&) const {
2922 return new StoreInst(*this);
2925 CastInst *TruncInst::clone(LLVMContext&) const {
2926 return new TruncInst(*this);
2929 CastInst *ZExtInst::clone(LLVMContext&) const {
2930 return new ZExtInst(*this);
2933 CastInst *SExtInst::clone(LLVMContext&) const {
2934 return new SExtInst(*this);
2937 CastInst *FPTruncInst::clone(LLVMContext&) const {
2938 return new FPTruncInst(*this);
2941 CastInst *FPExtInst::clone(LLVMContext&) const {
2942 return new FPExtInst(*this);
2945 CastInst *UIToFPInst::clone(LLVMContext&) const {
2946 return new UIToFPInst(*this);
2949 CastInst *SIToFPInst::clone(LLVMContext&) const {
2950 return new SIToFPInst(*this);
2953 CastInst *FPToUIInst::clone(LLVMContext&) const {
2954 return new FPToUIInst(*this);
2957 CastInst *FPToSIInst::clone(LLVMContext&) const {
2958 return new FPToSIInst(*this);
2961 CastInst *PtrToIntInst::clone(LLVMContext&) const {
2962 return new PtrToIntInst(*this);
2965 CastInst *IntToPtrInst::clone(LLVMContext&) const {
2966 return new IntToPtrInst(*this);
2969 CastInst *BitCastInst::clone(LLVMContext&) const {
2970 return new BitCastInst(*this);
2973 CallInst *CallInst::clone(LLVMContext&) const {
2974 return new(getNumOperands()) CallInst(*this);
2977 SelectInst *SelectInst::clone(LLVMContext&) const {
2978 return new(getNumOperands()) SelectInst(*this);
2981 VAArgInst *VAArgInst::clone(LLVMContext&) const {
2982 return new VAArgInst(*this);
2985 ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const {
2986 return new ExtractElementInst(*this);
2989 InsertElementInst *InsertElementInst::clone(LLVMContext&) const {
2990 return InsertElementInst::Create(*this);
2993 ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const {
2994 return new ShuffleVectorInst(*this);
2997 PHINode *PHINode::clone(LLVMContext&) const {
2998 return new PHINode(*this);
3001 ReturnInst *ReturnInst::clone(LLVMContext&) const {
3002 return new(getNumOperands()) ReturnInst(*this);
3005 BranchInst *BranchInst::clone(LLVMContext&) const {
3006 unsigned Ops(getNumOperands());
3007 return new(Ops, Ops == 1) BranchInst(*this);
3010 SwitchInst *SwitchInst::clone(LLVMContext&) const {
3011 return new SwitchInst(*this);
3014 InvokeInst *InvokeInst::clone(LLVMContext&) const {
3015 return new(getNumOperands()) InvokeInst(*this);
3018 UnwindInst *UnwindInst::clone(LLVMContext&) const {
3019 return new UnwindInst();
3022 UnreachableInst *UnreachableInst::clone(LLVMContext&) const {
3023 return new UnreachableInst();