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 "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/MathExtras.h"
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 User::op_iterator CallSite::getCallee() const {
33 Instruction *II(getInstruction());
35 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
36 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
39 //===----------------------------------------------------------------------===//
40 // TerminatorInst Class
41 //===----------------------------------------------------------------------===//
43 // Out of line virtual method, so the vtable, etc has a home.
44 TerminatorInst::~TerminatorInst() {
47 //===----------------------------------------------------------------------===//
48 // UnaryInstruction Class
49 //===----------------------------------------------------------------------===//
51 // Out of line virtual method, so the vtable, etc has a home.
52 UnaryInstruction::~UnaryInstruction() {
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 /// areInvalidOperands - Return a string if the specified operands are invalid
60 /// for a select operation, otherwise return null.
61 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
62 if (Op1->getType() != Op2->getType())
63 return "both values to select must have same type";
65 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
67 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
68 return "vector select condition element type must be i1";
69 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
71 return "selected values for vector select must be vectors";
72 if (ET->getNumElements() != VT->getNumElements())
73 return "vector select requires selected vectors to have "
74 "the same vector length as select condition";
75 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
76 return "select condition must be i1 or <n x i1>";
82 //===----------------------------------------------------------------------===//
84 //===----------------------------------------------------------------------===//
86 PHINode::PHINode(const PHINode &PN)
87 : Instruction(PN.getType(), Instruction::PHI,
88 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
89 ReservedSpace(PN.getNumOperands()) {
90 std::copy(PN.op_begin(), PN.op_end(), op_begin());
91 std::copy(PN.block_begin(), PN.block_end(), block_begin());
92 SubclassOptionalData = PN.SubclassOptionalData;
99 Use *PHINode::allocHungoffUses(unsigned N) const {
100 // Allocate the array of Uses of the incoming values, followed by a pointer
101 // (with bottom bit set) to the User, followed by the array of pointers to
102 // the incoming basic blocks.
103 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
104 + N * sizeof(BasicBlock*);
105 Use *Begin = static_cast<Use*>(::operator new(size));
106 Use *End = Begin + N;
107 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
108 return Use::initTags(Begin, End);
111 // removeIncomingValue - Remove an incoming value. This is useful if a
112 // predecessor basic block is deleted.
113 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
114 Value *Removed = getIncomingValue(Idx);
116 // Move everything after this operand down.
118 // FIXME: we could just swap with the end of the list, then erase. However,
119 // clients might not expect this to happen. The code as it is thrashes the
120 // use/def lists, which is kinda lame.
121 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
122 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
124 // Nuke the last value.
128 // If the PHI node is dead, because it has zero entries, nuke it now.
129 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
130 // If anyone is using this PHI, make them use a dummy value instead...
131 replaceAllUsesWith(UndefValue::get(getType()));
137 /// growOperands - grow operands - This grows the operand list in response
138 /// to a push_back style of operation. This grows the number of ops by 1.5
141 void PHINode::growOperands() {
142 unsigned e = getNumOperands();
143 unsigned NumOps = e + e / 2;
144 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
146 Use *OldOps = op_begin();
147 BasicBlock **OldBlocks = block_begin();
149 ReservedSpace = NumOps;
150 OperandList = allocHungoffUses(ReservedSpace);
152 std::copy(OldOps, OldOps + e, op_begin());
153 std::copy(OldBlocks, OldBlocks + e, block_begin());
155 Use::zap(OldOps, OldOps + e, true);
158 /// hasConstantValue - If the specified PHI node always merges together the same
159 /// value, return the value, otherwise return null.
160 Value *PHINode::hasConstantValue() const {
161 // Exploit the fact that phi nodes always have at least one entry.
162 Value *ConstantValue = getIncomingValue(0);
163 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
164 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
165 if (ConstantValue != this)
166 return 0; // Incoming values not all the same.
167 // The case where the first value is this PHI.
168 ConstantValue = getIncomingValue(i);
170 if (ConstantValue == this)
171 return UndefValue::get(getType());
172 return ConstantValue;
175 //===----------------------------------------------------------------------===//
176 // LandingPadInst Implementation
177 //===----------------------------------------------------------------------===//
179 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
180 unsigned NumReservedValues, const Twine &NameStr,
181 Instruction *InsertBefore)
182 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
183 init(PersonalityFn, 1 + NumReservedValues, NameStr);
186 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
187 unsigned NumReservedValues, const Twine &NameStr,
188 BasicBlock *InsertAtEnd)
189 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
190 init(PersonalityFn, 1 + NumReservedValues, NameStr);
193 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
194 : Instruction(LP.getType(), Instruction::LandingPad,
195 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
196 ReservedSpace(LP.getNumOperands()) {
197 Use *OL = OperandList, *InOL = LP.OperandList;
198 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
201 setCleanup(LP.isCleanup());
204 LandingPadInst::~LandingPadInst() {
208 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
209 unsigned NumReservedClauses,
210 const Twine &NameStr,
211 Instruction *InsertBefore) {
212 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
216 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
217 unsigned NumReservedClauses,
218 const Twine &NameStr,
219 BasicBlock *InsertAtEnd) {
220 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
224 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
225 const Twine &NameStr) {
226 ReservedSpace = NumReservedValues;
228 OperandList = allocHungoffUses(ReservedSpace);
229 OperandList[0] = PersFn;
234 /// growOperands - grow operands - This grows the operand list in response to a
235 /// push_back style of operation. This grows the number of ops by 2 times.
236 void LandingPadInst::growOperands(unsigned Size) {
237 unsigned e = getNumOperands();
238 if (ReservedSpace >= e + Size) return;
239 ReservedSpace = (e + Size / 2) * 2;
241 Use *NewOps = allocHungoffUses(ReservedSpace);
242 Use *OldOps = OperandList;
243 for (unsigned i = 0; i != e; ++i)
244 NewOps[i] = OldOps[i];
246 OperandList = NewOps;
247 Use::zap(OldOps, OldOps + e, true);
250 void LandingPadInst::addClause(Value *Val) {
251 unsigned OpNo = getNumOperands();
253 assert(OpNo < ReservedSpace && "Growing didn't work!");
255 OperandList[OpNo] = Val;
258 //===----------------------------------------------------------------------===//
259 // CallInst Implementation
260 //===----------------------------------------------------------------------===//
262 CallInst::~CallInst() {
265 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
266 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
271 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
273 assert((Args.size() == FTy->getNumParams() ||
274 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
275 "Calling a function with bad signature!");
277 for (unsigned i = 0; i != Args.size(); ++i)
278 assert((i >= FTy->getNumParams() ||
279 FTy->getParamType(i) == Args[i]->getType()) &&
280 "Calling a function with a bad signature!");
283 std::copy(Args.begin(), Args.end(), op_begin());
287 void CallInst::init(Value *Func, const Twine &NameStr) {
288 assert(NumOperands == 1 && "NumOperands not set up?");
293 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
295 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
301 CallInst::CallInst(Value *Func, const Twine &Name,
302 Instruction *InsertBefore)
303 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
304 ->getElementType())->getReturnType(),
306 OperandTraits<CallInst>::op_end(this) - 1,
311 CallInst::CallInst(Value *Func, const Twine &Name,
312 BasicBlock *InsertAtEnd)
313 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
314 ->getElementType())->getReturnType(),
316 OperandTraits<CallInst>::op_end(this) - 1,
321 CallInst::CallInst(const CallInst &CI)
322 : Instruction(CI.getType(), Instruction::Call,
323 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
324 CI.getNumOperands()) {
325 setAttributes(CI.getAttributes());
326 setTailCall(CI.isTailCall());
327 setCallingConv(CI.getCallingConv());
329 std::copy(CI.op_begin(), CI.op_end(), op_begin());
330 SubclassOptionalData = CI.SubclassOptionalData;
333 void CallInst::addAttribute(unsigned i, Attributes attr) {
334 AttrListPtr PAL = getAttributes();
335 PAL = PAL.addAttr(getContext(), i, attr);
339 void CallInst::removeAttribute(unsigned i, Attributes attr) {
340 AttrListPtr PAL = getAttributes();
341 PAL = PAL.removeAttr(getContext(), i, attr);
345 bool CallInst::hasFnAttr(Attributes::AttrVal A) const {
346 if (AttributeList.getParamAttributes(AttrListPtr::FunctionIndex)
349 if (const Function *F = getCalledFunction())
350 return F->getParamAttributes(AttrListPtr::FunctionIndex).hasAttribute(A);
354 bool CallInst::paramHasAttr(unsigned i, Attributes::AttrVal A) const {
355 if (AttributeList.getParamAttributes(i).hasAttribute(A))
357 if (const Function *F = getCalledFunction())
358 return F->getParamAttributes(i).hasAttribute(A);
362 /// IsConstantOne - Return true only if val is constant int 1
363 static bool IsConstantOne(Value *val) {
364 assert(val && "IsConstantOne does not work with NULL val");
365 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
368 static Instruction *createMalloc(Instruction *InsertBefore,
369 BasicBlock *InsertAtEnd, Type *IntPtrTy,
370 Type *AllocTy, Value *AllocSize,
371 Value *ArraySize, Function *MallocF,
373 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
374 "createMalloc needs either InsertBefore or InsertAtEnd");
376 // malloc(type) becomes:
377 // bitcast (i8* malloc(typeSize)) to type*
378 // malloc(type, arraySize) becomes:
379 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
381 ArraySize = ConstantInt::get(IntPtrTy, 1);
382 else if (ArraySize->getType() != IntPtrTy) {
384 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
387 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
391 if (!IsConstantOne(ArraySize)) {
392 if (IsConstantOne(AllocSize)) {
393 AllocSize = ArraySize; // Operand * 1 = Operand
394 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
395 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
397 // Malloc arg is constant product of type size and array size
398 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
400 // Multiply type size by the array size...
402 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
403 "mallocsize", InsertBefore);
405 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
406 "mallocsize", InsertAtEnd);
410 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
411 // Create the call to Malloc.
412 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
413 Module* M = BB->getParent()->getParent();
414 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
415 Value *MallocFunc = MallocF;
417 // prototype malloc as "void *malloc(size_t)"
418 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
419 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
420 CallInst *MCall = NULL;
421 Instruction *Result = NULL;
423 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
425 if (Result->getType() != AllocPtrType)
426 // Create a cast instruction to convert to the right type...
427 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
429 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
431 if (Result->getType() != AllocPtrType) {
432 InsertAtEnd->getInstList().push_back(MCall);
433 // Create a cast instruction to convert to the right type...
434 Result = new BitCastInst(MCall, AllocPtrType, Name);
437 MCall->setTailCall();
438 if (Function *F = dyn_cast<Function>(MallocFunc)) {
439 MCall->setCallingConv(F->getCallingConv());
440 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
442 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
447 /// CreateMalloc - Generate the IR for a call to malloc:
448 /// 1. Compute the malloc call's argument as the specified type's size,
449 /// possibly multiplied by the array size if the array size is not
451 /// 2. Call malloc with that argument.
452 /// 3. Bitcast the result of the malloc call to the specified type.
453 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
454 Type *IntPtrTy, Type *AllocTy,
455 Value *AllocSize, Value *ArraySize,
458 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
459 ArraySize, MallocF, Name);
462 /// CreateMalloc - Generate the IR for a call to malloc:
463 /// 1. Compute the malloc call's argument as the specified type's size,
464 /// possibly multiplied by the array size if the array size is not
466 /// 2. Call malloc with that argument.
467 /// 3. Bitcast the result of the malloc call to the specified type.
468 /// Note: This function does not add the bitcast to the basic block, that is the
469 /// responsibility of the caller.
470 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
471 Type *IntPtrTy, Type *AllocTy,
472 Value *AllocSize, Value *ArraySize,
473 Function *MallocF, const Twine &Name) {
474 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
475 ArraySize, MallocF, Name);
478 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
479 BasicBlock *InsertAtEnd) {
480 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
481 "createFree needs either InsertBefore or InsertAtEnd");
482 assert(Source->getType()->isPointerTy() &&
483 "Can not free something of nonpointer type!");
485 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
486 Module* M = BB->getParent()->getParent();
488 Type *VoidTy = Type::getVoidTy(M->getContext());
489 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
490 // prototype free as "void free(void*)"
491 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
492 CallInst* Result = NULL;
493 Value *PtrCast = Source;
495 if (Source->getType() != IntPtrTy)
496 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
497 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
499 if (Source->getType() != IntPtrTy)
500 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
501 Result = CallInst::Create(FreeFunc, PtrCast, "");
503 Result->setTailCall();
504 if (Function *F = dyn_cast<Function>(FreeFunc))
505 Result->setCallingConv(F->getCallingConv());
510 /// CreateFree - Generate the IR for a call to the builtin free function.
511 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
512 return createFree(Source, InsertBefore, NULL);
515 /// CreateFree - Generate the IR for a call to the builtin free function.
516 /// Note: This function does not add the call to the basic block, that is the
517 /// responsibility of the caller.
518 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
519 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
520 assert(FreeCall && "CreateFree did not create a CallInst");
524 //===----------------------------------------------------------------------===//
525 // InvokeInst Implementation
526 //===----------------------------------------------------------------------===//
528 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
529 ArrayRef<Value *> Args, const Twine &NameStr) {
530 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
533 Op<-1>() = IfException;
537 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
539 assert(((Args.size() == FTy->getNumParams()) ||
540 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
541 "Invoking a function with bad signature");
543 for (unsigned i = 0, e = Args.size(); i != e; i++)
544 assert((i >= FTy->getNumParams() ||
545 FTy->getParamType(i) == Args[i]->getType()) &&
546 "Invoking a function with a bad signature!");
549 std::copy(Args.begin(), Args.end(), op_begin());
553 InvokeInst::InvokeInst(const InvokeInst &II)
554 : TerminatorInst(II.getType(), Instruction::Invoke,
555 OperandTraits<InvokeInst>::op_end(this)
556 - II.getNumOperands(),
557 II.getNumOperands()) {
558 setAttributes(II.getAttributes());
559 setCallingConv(II.getCallingConv());
560 std::copy(II.op_begin(), II.op_end(), op_begin());
561 SubclassOptionalData = II.SubclassOptionalData;
564 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
565 return getSuccessor(idx);
567 unsigned InvokeInst::getNumSuccessorsV() const {
568 return getNumSuccessors();
570 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
571 return setSuccessor(idx, B);
574 bool InvokeInst::hasFnAttr(Attributes::AttrVal A) const {
575 if (AttributeList.getParamAttributes(AttrListPtr::FunctionIndex).
578 if (const Function *F = getCalledFunction())
579 return F->getParamAttributes(AttrListPtr::FunctionIndex).hasAttribute(A);
583 bool InvokeInst::paramHasAttr(unsigned i, Attributes::AttrVal A) const {
584 if (AttributeList.getParamAttributes(i).hasAttribute(A))
586 if (const Function *F = getCalledFunction())
587 return F->getParamAttributes(i).hasAttribute(A);
591 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
592 AttrListPtr PAL = getAttributes();
593 PAL = PAL.addAttr(getContext(), i, attr);
597 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
598 AttrListPtr PAL = getAttributes();
599 PAL = PAL.removeAttr(getContext(), i, attr);
603 LandingPadInst *InvokeInst::getLandingPadInst() const {
604 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
607 //===----------------------------------------------------------------------===//
608 // ReturnInst Implementation
609 //===----------------------------------------------------------------------===//
611 ReturnInst::ReturnInst(const ReturnInst &RI)
612 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
613 OperandTraits<ReturnInst>::op_end(this) -
615 RI.getNumOperands()) {
616 if (RI.getNumOperands())
617 Op<0>() = RI.Op<0>();
618 SubclassOptionalData = RI.SubclassOptionalData;
621 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
622 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
623 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
628 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
629 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
630 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
635 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
636 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
637 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
640 unsigned ReturnInst::getNumSuccessorsV() const {
641 return getNumSuccessors();
644 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
645 /// emit the vtable for the class in this translation unit.
646 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
647 llvm_unreachable("ReturnInst has no successors!");
650 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
651 llvm_unreachable("ReturnInst has no successors!");
654 ReturnInst::~ReturnInst() {
657 //===----------------------------------------------------------------------===//
658 // ResumeInst Implementation
659 //===----------------------------------------------------------------------===//
661 ResumeInst::ResumeInst(const ResumeInst &RI)
662 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
663 OperandTraits<ResumeInst>::op_begin(this), 1) {
664 Op<0>() = RI.Op<0>();
667 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
668 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
669 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
673 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
674 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
675 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
679 unsigned ResumeInst::getNumSuccessorsV() const {
680 return getNumSuccessors();
683 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
684 llvm_unreachable("ResumeInst has no successors!");
687 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
688 llvm_unreachable("ResumeInst has no successors!");
691 //===----------------------------------------------------------------------===//
692 // UnreachableInst Implementation
693 //===----------------------------------------------------------------------===//
695 UnreachableInst::UnreachableInst(LLVMContext &Context,
696 Instruction *InsertBefore)
697 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
698 0, 0, InsertBefore) {
700 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
701 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
705 unsigned UnreachableInst::getNumSuccessorsV() const {
706 return getNumSuccessors();
709 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
710 llvm_unreachable("UnreachableInst has no successors!");
713 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
714 llvm_unreachable("UnreachableInst has no successors!");
717 //===----------------------------------------------------------------------===//
718 // BranchInst Implementation
719 //===----------------------------------------------------------------------===//
721 void BranchInst::AssertOK() {
723 assert(getCondition()->getType()->isIntegerTy(1) &&
724 "May only branch on boolean predicates!");
727 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
728 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
729 OperandTraits<BranchInst>::op_end(this) - 1,
731 assert(IfTrue != 0 && "Branch destination may not be null!");
734 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
735 Instruction *InsertBefore)
736 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
737 OperandTraits<BranchInst>::op_end(this) - 3,
747 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
748 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
749 OperandTraits<BranchInst>::op_end(this) - 1,
751 assert(IfTrue != 0 && "Branch destination may not be null!");
755 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
756 BasicBlock *InsertAtEnd)
757 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
758 OperandTraits<BranchInst>::op_end(this) - 3,
769 BranchInst::BranchInst(const BranchInst &BI) :
770 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
771 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
772 BI.getNumOperands()) {
773 Op<-1>() = BI.Op<-1>();
774 if (BI.getNumOperands() != 1) {
775 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
776 Op<-3>() = BI.Op<-3>();
777 Op<-2>() = BI.Op<-2>();
779 SubclassOptionalData = BI.SubclassOptionalData;
782 void BranchInst::swapSuccessors() {
783 assert(isConditional() &&
784 "Cannot swap successors of an unconditional branch");
785 Op<-1>().swap(Op<-2>());
787 // Update profile metadata if present and it matches our structural
789 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
790 if (!ProfileData || ProfileData->getNumOperands() != 3)
793 // The first operand is the name. Fetch them backwards and build a new one.
795 ProfileData->getOperand(0),
796 ProfileData->getOperand(2),
797 ProfileData->getOperand(1)
799 setMetadata(LLVMContext::MD_prof,
800 MDNode::get(ProfileData->getContext(), Ops));
803 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
804 return getSuccessor(idx);
806 unsigned BranchInst::getNumSuccessorsV() const {
807 return getNumSuccessors();
809 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
810 setSuccessor(idx, B);
814 //===----------------------------------------------------------------------===//
815 // AllocaInst Implementation
816 //===----------------------------------------------------------------------===//
818 static Value *getAISize(LLVMContext &Context, Value *Amt) {
820 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
822 assert(!isa<BasicBlock>(Amt) &&
823 "Passed basic block into allocation size parameter! Use other ctor");
824 assert(Amt->getType()->isIntegerTy() &&
825 "Allocation array size is not an integer!");
830 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
831 const Twine &Name, Instruction *InsertBefore)
832 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
833 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
835 assert(!Ty->isVoidTy() && "Cannot allocate void!");
839 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
840 const Twine &Name, BasicBlock *InsertAtEnd)
841 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
842 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
844 assert(!Ty->isVoidTy() && "Cannot allocate void!");
848 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
849 Instruction *InsertBefore)
850 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
851 getAISize(Ty->getContext(), 0), InsertBefore) {
853 assert(!Ty->isVoidTy() && "Cannot allocate void!");
857 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
858 BasicBlock *InsertAtEnd)
859 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
860 getAISize(Ty->getContext(), 0), InsertAtEnd) {
862 assert(!Ty->isVoidTy() && "Cannot allocate void!");
866 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
867 const Twine &Name, Instruction *InsertBefore)
868 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
869 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
871 assert(!Ty->isVoidTy() && "Cannot allocate void!");
875 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
876 const Twine &Name, BasicBlock *InsertAtEnd)
877 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
878 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
880 assert(!Ty->isVoidTy() && "Cannot allocate void!");
884 // Out of line virtual method, so the vtable, etc has a home.
885 AllocaInst::~AllocaInst() {
888 void AllocaInst::setAlignment(unsigned Align) {
889 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
890 assert(Align <= MaximumAlignment &&
891 "Alignment is greater than MaximumAlignment!");
892 setInstructionSubclassData(Log2_32(Align) + 1);
893 assert(getAlignment() == Align && "Alignment representation error!");
896 bool AllocaInst::isArrayAllocation() const {
897 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
902 Type *AllocaInst::getAllocatedType() const {
903 return getType()->getElementType();
906 /// isStaticAlloca - Return true if this alloca is in the entry block of the
907 /// function and is a constant size. If so, the code generator will fold it
908 /// into the prolog/epilog code, so it is basically free.
909 bool AllocaInst::isStaticAlloca() const {
910 // Must be constant size.
911 if (!isa<ConstantInt>(getArraySize())) return false;
913 // Must be in the entry block.
914 const BasicBlock *Parent = getParent();
915 return Parent == &Parent->getParent()->front();
918 //===----------------------------------------------------------------------===//
919 // LoadInst Implementation
920 //===----------------------------------------------------------------------===//
922 void LoadInst::AssertOK() {
923 assert(getOperand(0)->getType()->isPointerTy() &&
924 "Ptr must have pointer type.");
925 assert(!(isAtomic() && getAlignment() == 0) &&
926 "Alignment required for atomic load");
929 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
930 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
931 Load, Ptr, InsertBef) {
934 setAtomic(NotAtomic);
939 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
940 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
941 Load, Ptr, InsertAE) {
944 setAtomic(NotAtomic);
949 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
950 Instruction *InsertBef)
951 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
952 Load, Ptr, InsertBef) {
953 setVolatile(isVolatile);
955 setAtomic(NotAtomic);
960 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
961 BasicBlock *InsertAE)
962 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
963 Load, Ptr, InsertAE) {
964 setVolatile(isVolatile);
966 setAtomic(NotAtomic);
971 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
972 unsigned Align, Instruction *InsertBef)
973 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
974 Load, Ptr, InsertBef) {
975 setVolatile(isVolatile);
977 setAtomic(NotAtomic);
982 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
983 unsigned Align, BasicBlock *InsertAE)
984 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
985 Load, Ptr, InsertAE) {
986 setVolatile(isVolatile);
988 setAtomic(NotAtomic);
993 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
994 unsigned Align, AtomicOrdering Order,
995 SynchronizationScope SynchScope,
996 Instruction *InsertBef)
997 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
998 Load, Ptr, InsertBef) {
999 setVolatile(isVolatile);
1000 setAlignment(Align);
1001 setAtomic(Order, SynchScope);
1006 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1007 unsigned Align, AtomicOrdering Order,
1008 SynchronizationScope SynchScope,
1009 BasicBlock *InsertAE)
1010 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1011 Load, Ptr, InsertAE) {
1012 setVolatile(isVolatile);
1013 setAlignment(Align);
1014 setAtomic(Order, SynchScope);
1019 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1020 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1021 Load, Ptr, InsertBef) {
1024 setAtomic(NotAtomic);
1026 if (Name && Name[0]) setName(Name);
1029 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1030 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1031 Load, Ptr, InsertAE) {
1034 setAtomic(NotAtomic);
1036 if (Name && Name[0]) setName(Name);
1039 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1040 Instruction *InsertBef)
1041 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1042 Load, Ptr, InsertBef) {
1043 setVolatile(isVolatile);
1045 setAtomic(NotAtomic);
1047 if (Name && Name[0]) setName(Name);
1050 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1051 BasicBlock *InsertAE)
1052 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1053 Load, Ptr, InsertAE) {
1054 setVolatile(isVolatile);
1056 setAtomic(NotAtomic);
1058 if (Name && Name[0]) setName(Name);
1061 void LoadInst::setAlignment(unsigned Align) {
1062 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1063 assert(Align <= MaximumAlignment &&
1064 "Alignment is greater than MaximumAlignment!");
1065 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1066 ((Log2_32(Align)+1)<<1));
1067 assert(getAlignment() == Align && "Alignment representation error!");
1070 //===----------------------------------------------------------------------===//
1071 // StoreInst Implementation
1072 //===----------------------------------------------------------------------===//
1074 void StoreInst::AssertOK() {
1075 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1076 assert(getOperand(1)->getType()->isPointerTy() &&
1077 "Ptr must have pointer type!");
1078 assert(getOperand(0)->getType() ==
1079 cast<PointerType>(getOperand(1)->getType())->getElementType()
1080 && "Ptr must be a pointer to Val type!");
1081 assert(!(isAtomic() && getAlignment() == 0) &&
1082 "Alignment required for atomic load");
1086 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1087 : Instruction(Type::getVoidTy(val->getContext()), Store,
1088 OperandTraits<StoreInst>::op_begin(this),
1089 OperandTraits<StoreInst>::operands(this),
1095 setAtomic(NotAtomic);
1099 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1100 : Instruction(Type::getVoidTy(val->getContext()), Store,
1101 OperandTraits<StoreInst>::op_begin(this),
1102 OperandTraits<StoreInst>::operands(this),
1108 setAtomic(NotAtomic);
1112 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1113 Instruction *InsertBefore)
1114 : Instruction(Type::getVoidTy(val->getContext()), Store,
1115 OperandTraits<StoreInst>::op_begin(this),
1116 OperandTraits<StoreInst>::operands(this),
1120 setVolatile(isVolatile);
1122 setAtomic(NotAtomic);
1126 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1127 unsigned Align, Instruction *InsertBefore)
1128 : Instruction(Type::getVoidTy(val->getContext()), Store,
1129 OperandTraits<StoreInst>::op_begin(this),
1130 OperandTraits<StoreInst>::operands(this),
1134 setVolatile(isVolatile);
1135 setAlignment(Align);
1136 setAtomic(NotAtomic);
1140 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1141 unsigned Align, AtomicOrdering Order,
1142 SynchronizationScope SynchScope,
1143 Instruction *InsertBefore)
1144 : Instruction(Type::getVoidTy(val->getContext()), Store,
1145 OperandTraits<StoreInst>::op_begin(this),
1146 OperandTraits<StoreInst>::operands(this),
1150 setVolatile(isVolatile);
1151 setAlignment(Align);
1152 setAtomic(Order, SynchScope);
1156 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1157 BasicBlock *InsertAtEnd)
1158 : Instruction(Type::getVoidTy(val->getContext()), Store,
1159 OperandTraits<StoreInst>::op_begin(this),
1160 OperandTraits<StoreInst>::operands(this),
1164 setVolatile(isVolatile);
1166 setAtomic(NotAtomic);
1170 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1171 unsigned Align, BasicBlock *InsertAtEnd)
1172 : Instruction(Type::getVoidTy(val->getContext()), Store,
1173 OperandTraits<StoreInst>::op_begin(this),
1174 OperandTraits<StoreInst>::operands(this),
1178 setVolatile(isVolatile);
1179 setAlignment(Align);
1180 setAtomic(NotAtomic);
1184 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1185 unsigned Align, AtomicOrdering Order,
1186 SynchronizationScope SynchScope,
1187 BasicBlock *InsertAtEnd)
1188 : Instruction(Type::getVoidTy(val->getContext()), Store,
1189 OperandTraits<StoreInst>::op_begin(this),
1190 OperandTraits<StoreInst>::operands(this),
1194 setVolatile(isVolatile);
1195 setAlignment(Align);
1196 setAtomic(Order, SynchScope);
1200 void StoreInst::setAlignment(unsigned Align) {
1201 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1202 assert(Align <= MaximumAlignment &&
1203 "Alignment is greater than MaximumAlignment!");
1204 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1205 ((Log2_32(Align)+1) << 1));
1206 assert(getAlignment() == Align && "Alignment representation error!");
1209 //===----------------------------------------------------------------------===//
1210 // AtomicCmpXchgInst Implementation
1211 //===----------------------------------------------------------------------===//
1213 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1214 AtomicOrdering Ordering,
1215 SynchronizationScope SynchScope) {
1219 setOrdering(Ordering);
1220 setSynchScope(SynchScope);
1222 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1223 "All operands must be non-null!");
1224 assert(getOperand(0)->getType()->isPointerTy() &&
1225 "Ptr must have pointer type!");
1226 assert(getOperand(1)->getType() ==
1227 cast<PointerType>(getOperand(0)->getType())->getElementType()
1228 && "Ptr must be a pointer to Cmp type!");
1229 assert(getOperand(2)->getType() ==
1230 cast<PointerType>(getOperand(0)->getType())->getElementType()
1231 && "Ptr must be a pointer to NewVal type!");
1232 assert(Ordering != NotAtomic &&
1233 "AtomicCmpXchg instructions must be atomic!");
1236 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1237 AtomicOrdering Ordering,
1238 SynchronizationScope SynchScope,
1239 Instruction *InsertBefore)
1240 : Instruction(Cmp->getType(), AtomicCmpXchg,
1241 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1242 OperandTraits<AtomicCmpXchgInst>::operands(this),
1244 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1247 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1248 AtomicOrdering Ordering,
1249 SynchronizationScope SynchScope,
1250 BasicBlock *InsertAtEnd)
1251 : Instruction(Cmp->getType(), AtomicCmpXchg,
1252 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1253 OperandTraits<AtomicCmpXchgInst>::operands(this),
1255 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1258 //===----------------------------------------------------------------------===//
1259 // AtomicRMWInst Implementation
1260 //===----------------------------------------------------------------------===//
1262 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1263 AtomicOrdering Ordering,
1264 SynchronizationScope SynchScope) {
1267 setOperation(Operation);
1268 setOrdering(Ordering);
1269 setSynchScope(SynchScope);
1271 assert(getOperand(0) && getOperand(1) &&
1272 "All operands must be non-null!");
1273 assert(getOperand(0)->getType()->isPointerTy() &&
1274 "Ptr must have pointer type!");
1275 assert(getOperand(1)->getType() ==
1276 cast<PointerType>(getOperand(0)->getType())->getElementType()
1277 && "Ptr must be a pointer to Val type!");
1278 assert(Ordering != NotAtomic &&
1279 "AtomicRMW instructions must be atomic!");
1282 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1283 AtomicOrdering Ordering,
1284 SynchronizationScope SynchScope,
1285 Instruction *InsertBefore)
1286 : Instruction(Val->getType(), AtomicRMW,
1287 OperandTraits<AtomicRMWInst>::op_begin(this),
1288 OperandTraits<AtomicRMWInst>::operands(this),
1290 Init(Operation, Ptr, Val, Ordering, SynchScope);
1293 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1294 AtomicOrdering Ordering,
1295 SynchronizationScope SynchScope,
1296 BasicBlock *InsertAtEnd)
1297 : Instruction(Val->getType(), AtomicRMW,
1298 OperandTraits<AtomicRMWInst>::op_begin(this),
1299 OperandTraits<AtomicRMWInst>::operands(this),
1301 Init(Operation, Ptr, Val, Ordering, SynchScope);
1304 //===----------------------------------------------------------------------===//
1305 // FenceInst Implementation
1306 //===----------------------------------------------------------------------===//
1308 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1309 SynchronizationScope SynchScope,
1310 Instruction *InsertBefore)
1311 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1312 setOrdering(Ordering);
1313 setSynchScope(SynchScope);
1316 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1317 SynchronizationScope SynchScope,
1318 BasicBlock *InsertAtEnd)
1319 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1320 setOrdering(Ordering);
1321 setSynchScope(SynchScope);
1324 //===----------------------------------------------------------------------===//
1325 // GetElementPtrInst Implementation
1326 //===----------------------------------------------------------------------===//
1328 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1329 const Twine &Name) {
1330 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1331 OperandList[0] = Ptr;
1332 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1336 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1337 : Instruction(GEPI.getType(), GetElementPtr,
1338 OperandTraits<GetElementPtrInst>::op_end(this)
1339 - GEPI.getNumOperands(),
1340 GEPI.getNumOperands()) {
1341 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1342 SubclassOptionalData = GEPI.SubclassOptionalData;
1345 /// getIndexedType - Returns the type of the element that would be accessed with
1346 /// a gep instruction with the specified parameters.
1348 /// The Idxs pointer should point to a continuous piece of memory containing the
1349 /// indices, either as Value* or uint64_t.
1351 /// A null type is returned if the indices are invalid for the specified
1354 template <typename IndexTy>
1355 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1356 if (Ptr->isVectorTy()) {
1357 assert(IdxList.size() == 1 &&
1358 "GEP with vector pointers must have a single index");
1359 PointerType *PTy = dyn_cast<PointerType>(
1360 cast<VectorType>(Ptr)->getElementType());
1361 assert(PTy && "Gep with invalid vector pointer found");
1362 return PTy->getElementType();
1365 PointerType *PTy = dyn_cast<PointerType>(Ptr);
1366 if (!PTy) return 0; // Type isn't a pointer type!
1367 Type *Agg = PTy->getElementType();
1369 // Handle the special case of the empty set index set, which is always valid.
1370 if (IdxList.empty())
1373 // If there is at least one index, the top level type must be sized, otherwise
1374 // it cannot be 'stepped over'.
1375 if (!Agg->isSized())
1378 unsigned CurIdx = 1;
1379 for (; CurIdx != IdxList.size(); ++CurIdx) {
1380 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1381 if (!CT || CT->isPointerTy()) return 0;
1382 IndexTy Index = IdxList[CurIdx];
1383 if (!CT->indexValid(Index)) return 0;
1384 Agg = CT->getTypeAtIndex(Index);
1386 return CurIdx == IdxList.size() ? Agg : 0;
1389 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1390 return getIndexedTypeInternal(Ptr, IdxList);
1393 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1394 ArrayRef<Constant *> IdxList) {
1395 return getIndexedTypeInternal(Ptr, IdxList);
1398 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1399 return getIndexedTypeInternal(Ptr, IdxList);
1402 unsigned GetElementPtrInst::getAddressSpace(Value *Ptr) {
1403 Type *Ty = Ptr->getType();
1405 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1406 Ty = VTy->getElementType();
1408 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1409 return PTy->getAddressSpace();
1411 llvm_unreachable("Invalid GEP pointer type");
1414 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1415 /// zeros. If so, the result pointer and the first operand have the same
1416 /// value, just potentially different types.
1417 bool GetElementPtrInst::hasAllZeroIndices() const {
1418 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1419 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1420 if (!CI->isZero()) return false;
1428 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1429 /// constant integers. If so, the result pointer and the first operand have
1430 /// a constant offset between them.
1431 bool GetElementPtrInst::hasAllConstantIndices() const {
1432 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1433 if (!isa<ConstantInt>(getOperand(i)))
1439 void GetElementPtrInst::setIsInBounds(bool B) {
1440 cast<GEPOperator>(this)->setIsInBounds(B);
1443 bool GetElementPtrInst::isInBounds() const {
1444 return cast<GEPOperator>(this)->isInBounds();
1447 //===----------------------------------------------------------------------===//
1448 // ExtractElementInst Implementation
1449 //===----------------------------------------------------------------------===//
1451 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1453 Instruction *InsertBef)
1454 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1456 OperandTraits<ExtractElementInst>::op_begin(this),
1458 assert(isValidOperands(Val, Index) &&
1459 "Invalid extractelement instruction operands!");
1465 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1467 BasicBlock *InsertAE)
1468 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1470 OperandTraits<ExtractElementInst>::op_begin(this),
1472 assert(isValidOperands(Val, Index) &&
1473 "Invalid extractelement instruction operands!");
1481 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1482 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1488 //===----------------------------------------------------------------------===//
1489 // InsertElementInst Implementation
1490 //===----------------------------------------------------------------------===//
1492 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1494 Instruction *InsertBef)
1495 : Instruction(Vec->getType(), InsertElement,
1496 OperandTraits<InsertElementInst>::op_begin(this),
1498 assert(isValidOperands(Vec, Elt, Index) &&
1499 "Invalid insertelement instruction operands!");
1506 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1508 BasicBlock *InsertAE)
1509 : Instruction(Vec->getType(), InsertElement,
1510 OperandTraits<InsertElementInst>::op_begin(this),
1512 assert(isValidOperands(Vec, Elt, Index) &&
1513 "Invalid insertelement instruction operands!");
1521 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1522 const Value *Index) {
1523 if (!Vec->getType()->isVectorTy())
1524 return false; // First operand of insertelement must be vector type.
1526 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1527 return false;// Second operand of insertelement must be vector element type.
1529 if (!Index->getType()->isIntegerTy(32))
1530 return false; // Third operand of insertelement must be i32.
1535 //===----------------------------------------------------------------------===//
1536 // ShuffleVectorInst Implementation
1537 //===----------------------------------------------------------------------===//
1539 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1541 Instruction *InsertBefore)
1542 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1543 cast<VectorType>(Mask->getType())->getNumElements()),
1545 OperandTraits<ShuffleVectorInst>::op_begin(this),
1546 OperandTraits<ShuffleVectorInst>::operands(this),
1548 assert(isValidOperands(V1, V2, Mask) &&
1549 "Invalid shuffle vector instruction operands!");
1556 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1558 BasicBlock *InsertAtEnd)
1559 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1560 cast<VectorType>(Mask->getType())->getNumElements()),
1562 OperandTraits<ShuffleVectorInst>::op_begin(this),
1563 OperandTraits<ShuffleVectorInst>::operands(this),
1565 assert(isValidOperands(V1, V2, Mask) &&
1566 "Invalid shuffle vector instruction operands!");
1574 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1575 const Value *Mask) {
1576 // V1 and V2 must be vectors of the same type.
1577 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1580 // Mask must be vector of i32.
1581 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1582 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1585 // Check to see if Mask is valid.
1586 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1589 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1590 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1591 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1592 if (ConstantInt *CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1593 if (CI->uge(V1Size*2))
1595 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1602 if (const ConstantDataSequential *CDS =
1603 dyn_cast<ConstantDataSequential>(Mask)) {
1604 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1605 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1606 if (CDS->getElementAsInteger(i) >= V1Size*2)
1611 // The bitcode reader can create a place holder for a forward reference
1612 // used as the shuffle mask. When this occurs, the shuffle mask will
1613 // fall into this case and fail. To avoid this error, do this bit of
1614 // ugliness to allow such a mask pass.
1615 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1616 if (CE->getOpcode() == Instruction::UserOp1)
1622 /// getMaskValue - Return the index from the shuffle mask for the specified
1623 /// output result. This is either -1 if the element is undef or a number less
1624 /// than 2*numelements.
1625 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1626 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1627 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1628 return CDS->getElementAsInteger(i);
1629 Constant *C = Mask->getAggregateElement(i);
1630 if (isa<UndefValue>(C))
1632 return cast<ConstantInt>(C)->getZExtValue();
1635 /// getShuffleMask - Return the full mask for this instruction, where each
1636 /// element is the element number and undef's are returned as -1.
1637 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1638 SmallVectorImpl<int> &Result) {
1639 unsigned NumElts = Mask->getType()->getVectorNumElements();
1641 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1642 for (unsigned i = 0; i != NumElts; ++i)
1643 Result.push_back(CDS->getElementAsInteger(i));
1646 for (unsigned i = 0; i != NumElts; ++i) {
1647 Constant *C = Mask->getAggregateElement(i);
1648 Result.push_back(isa<UndefValue>(C) ? -1 :
1649 cast<ConstantInt>(C)->getZExtValue());
1654 //===----------------------------------------------------------------------===//
1655 // InsertValueInst Class
1656 //===----------------------------------------------------------------------===//
1658 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1659 const Twine &Name) {
1660 assert(NumOperands == 2 && "NumOperands not initialized?");
1662 // There's no fundamental reason why we require at least one index
1663 // (other than weirdness with &*IdxBegin being invalid; see
1664 // getelementptr's init routine for example). But there's no
1665 // present need to support it.
1666 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1668 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1669 Val->getType() && "Inserted value must match indexed type!");
1673 Indices.append(Idxs.begin(), Idxs.end());
1677 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1678 : Instruction(IVI.getType(), InsertValue,
1679 OperandTraits<InsertValueInst>::op_begin(this), 2),
1680 Indices(IVI.Indices) {
1681 Op<0>() = IVI.getOperand(0);
1682 Op<1>() = IVI.getOperand(1);
1683 SubclassOptionalData = IVI.SubclassOptionalData;
1686 //===----------------------------------------------------------------------===//
1687 // ExtractValueInst Class
1688 //===----------------------------------------------------------------------===//
1690 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1691 assert(NumOperands == 1 && "NumOperands not initialized?");
1693 // There's no fundamental reason why we require at least one index.
1694 // But there's no present need to support it.
1695 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1697 Indices.append(Idxs.begin(), Idxs.end());
1701 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1702 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1703 Indices(EVI.Indices) {
1704 SubclassOptionalData = EVI.SubclassOptionalData;
1707 // getIndexedType - Returns the type of the element that would be extracted
1708 // with an extractvalue instruction with the specified parameters.
1710 // A null type is returned if the indices are invalid for the specified
1713 Type *ExtractValueInst::getIndexedType(Type *Agg,
1714 ArrayRef<unsigned> Idxs) {
1715 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1716 unsigned Index = Idxs[CurIdx];
1717 // We can't use CompositeType::indexValid(Index) here.
1718 // indexValid() always returns true for arrays because getelementptr allows
1719 // out-of-bounds indices. Since we don't allow those for extractvalue and
1720 // insertvalue we need to check array indexing manually.
1721 // Since the only other types we can index into are struct types it's just
1722 // as easy to check those manually as well.
1723 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1724 if (Index >= AT->getNumElements())
1726 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1727 if (Index >= ST->getNumElements())
1730 // Not a valid type to index into.
1734 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1736 return const_cast<Type*>(Agg);
1739 //===----------------------------------------------------------------------===//
1740 // BinaryOperator Class
1741 //===----------------------------------------------------------------------===//
1743 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1744 Type *Ty, const Twine &Name,
1745 Instruction *InsertBefore)
1746 : Instruction(Ty, iType,
1747 OperandTraits<BinaryOperator>::op_begin(this),
1748 OperandTraits<BinaryOperator>::operands(this),
1756 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1757 Type *Ty, const Twine &Name,
1758 BasicBlock *InsertAtEnd)
1759 : Instruction(Ty, iType,
1760 OperandTraits<BinaryOperator>::op_begin(this),
1761 OperandTraits<BinaryOperator>::operands(this),
1770 void BinaryOperator::init(BinaryOps iType) {
1771 Value *LHS = getOperand(0), *RHS = getOperand(1);
1772 (void)LHS; (void)RHS; // Silence warnings.
1773 assert(LHS->getType() == RHS->getType() &&
1774 "Binary operator operand types must match!");
1779 assert(getType() == LHS->getType() &&
1780 "Arithmetic operation should return same type as operands!");
1781 assert(getType()->isIntOrIntVectorTy() &&
1782 "Tried to create an integer operation on a non-integer type!");
1784 case FAdd: case FSub:
1786 assert(getType() == LHS->getType() &&
1787 "Arithmetic operation should return same type as operands!");
1788 assert(getType()->isFPOrFPVectorTy() &&
1789 "Tried to create a floating-point operation on a "
1790 "non-floating-point type!");
1794 assert(getType() == LHS->getType() &&
1795 "Arithmetic operation should return same type as operands!");
1796 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1797 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1798 "Incorrect operand type (not integer) for S/UDIV");
1801 assert(getType() == LHS->getType() &&
1802 "Arithmetic operation should return same type as operands!");
1803 assert(getType()->isFPOrFPVectorTy() &&
1804 "Incorrect operand type (not floating point) for FDIV");
1808 assert(getType() == LHS->getType() &&
1809 "Arithmetic operation should return same type as operands!");
1810 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1811 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1812 "Incorrect operand type (not integer) for S/UREM");
1815 assert(getType() == LHS->getType() &&
1816 "Arithmetic operation should return same type as operands!");
1817 assert(getType()->isFPOrFPVectorTy() &&
1818 "Incorrect operand type (not floating point) for FREM");
1823 assert(getType() == LHS->getType() &&
1824 "Shift operation should return same type as operands!");
1825 assert((getType()->isIntegerTy() ||
1826 (getType()->isVectorTy() &&
1827 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1828 "Tried to create a shift operation on a non-integral type!");
1832 assert(getType() == LHS->getType() &&
1833 "Logical operation should return same type as operands!");
1834 assert((getType()->isIntegerTy() ||
1835 (getType()->isVectorTy() &&
1836 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1837 "Tried to create a logical operation on a non-integral type!");
1845 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1847 Instruction *InsertBefore) {
1848 assert(S1->getType() == S2->getType() &&
1849 "Cannot create binary operator with two operands of differing type!");
1850 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1853 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1855 BasicBlock *InsertAtEnd) {
1856 BinaryOperator *Res = Create(Op, S1, S2, Name);
1857 InsertAtEnd->getInstList().push_back(Res);
1861 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1862 Instruction *InsertBefore) {
1863 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1864 return new BinaryOperator(Instruction::Sub,
1866 Op->getType(), Name, InsertBefore);
1869 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1870 BasicBlock *InsertAtEnd) {
1871 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1872 return new BinaryOperator(Instruction::Sub,
1874 Op->getType(), Name, InsertAtEnd);
1877 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1878 Instruction *InsertBefore) {
1879 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1880 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1883 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1884 BasicBlock *InsertAtEnd) {
1885 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1886 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1889 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1890 Instruction *InsertBefore) {
1891 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1892 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1895 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1896 BasicBlock *InsertAtEnd) {
1897 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1898 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1901 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1902 Instruction *InsertBefore) {
1903 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1904 return new BinaryOperator(Instruction::FSub, zero, Op,
1905 Op->getType(), Name, InsertBefore);
1908 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1909 BasicBlock *InsertAtEnd) {
1910 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1911 return new BinaryOperator(Instruction::FSub, zero, Op,
1912 Op->getType(), Name, InsertAtEnd);
1915 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1916 Instruction *InsertBefore) {
1917 Constant *C = Constant::getAllOnesValue(Op->getType());
1918 return new BinaryOperator(Instruction::Xor, Op, C,
1919 Op->getType(), Name, InsertBefore);
1922 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1923 BasicBlock *InsertAtEnd) {
1924 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
1925 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1926 Op->getType(), Name, InsertAtEnd);
1930 // isConstantAllOnes - Helper function for several functions below
1931 static inline bool isConstantAllOnes(const Value *V) {
1932 if (const Constant *C = dyn_cast<Constant>(V))
1933 return C->isAllOnesValue();
1937 bool BinaryOperator::isNeg(const Value *V) {
1938 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1939 if (Bop->getOpcode() == Instruction::Sub)
1940 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1941 return C->isNegativeZeroValue();
1945 bool BinaryOperator::isFNeg(const Value *V) {
1946 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1947 if (Bop->getOpcode() == Instruction::FSub)
1948 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1949 return C->isNegativeZeroValue();
1953 bool BinaryOperator::isNot(const Value *V) {
1954 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1955 return (Bop->getOpcode() == Instruction::Xor &&
1956 (isConstantAllOnes(Bop->getOperand(1)) ||
1957 isConstantAllOnes(Bop->getOperand(0))));
1961 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1962 return cast<BinaryOperator>(BinOp)->getOperand(1);
1965 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1966 return getNegArgument(const_cast<Value*>(BinOp));
1969 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1970 return cast<BinaryOperator>(BinOp)->getOperand(1);
1973 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1974 return getFNegArgument(const_cast<Value*>(BinOp));
1977 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1978 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1979 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1980 Value *Op0 = BO->getOperand(0);
1981 Value *Op1 = BO->getOperand(1);
1982 if (isConstantAllOnes(Op0)) return Op1;
1984 assert(isConstantAllOnes(Op1));
1988 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1989 return getNotArgument(const_cast<Value*>(BinOp));
1993 // swapOperands - Exchange the two operands to this instruction. This
1994 // instruction is safe to use on any binary instruction and does not
1995 // modify the semantics of the instruction. If the instruction is
1996 // order dependent (SetLT f.e.) the opcode is changed.
1998 bool BinaryOperator::swapOperands() {
1999 if (!isCommutative())
2000 return true; // Can't commute operands
2001 Op<0>().swap(Op<1>());
2005 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2006 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2009 void BinaryOperator::setHasNoSignedWrap(bool b) {
2010 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2013 void BinaryOperator::setIsExact(bool b) {
2014 cast<PossiblyExactOperator>(this)->setIsExact(b);
2017 bool BinaryOperator::hasNoUnsignedWrap() const {
2018 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2021 bool BinaryOperator::hasNoSignedWrap() const {
2022 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2025 bool BinaryOperator::isExact() const {
2026 return cast<PossiblyExactOperator>(this)->isExact();
2029 //===----------------------------------------------------------------------===//
2030 // FPMathOperator Class
2031 //===----------------------------------------------------------------------===//
2033 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2034 /// An accuracy of 0.0 means that the operation should be performed with the
2035 /// default precision.
2036 float FPMathOperator::getFPAccuracy() const {
2038 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2041 ConstantFP *Accuracy = cast<ConstantFP>(MD->getOperand(0));
2042 return Accuracy->getValueAPF().convertToFloat();
2046 //===----------------------------------------------------------------------===//
2048 //===----------------------------------------------------------------------===//
2050 void CastInst::anchor() {}
2052 // Just determine if this cast only deals with integral->integral conversion.
2053 bool CastInst::isIntegerCast() const {
2054 switch (getOpcode()) {
2055 default: return false;
2056 case Instruction::ZExt:
2057 case Instruction::SExt:
2058 case Instruction::Trunc:
2060 case Instruction::BitCast:
2061 return getOperand(0)->getType()->isIntegerTy() &&
2062 getType()->isIntegerTy();
2066 bool CastInst::isLosslessCast() const {
2067 // Only BitCast can be lossless, exit fast if we're not BitCast
2068 if (getOpcode() != Instruction::BitCast)
2071 // Identity cast is always lossless
2072 Type* SrcTy = getOperand(0)->getType();
2073 Type* DstTy = getType();
2077 // Pointer to pointer is always lossless.
2078 if (SrcTy->isPointerTy())
2079 return DstTy->isPointerTy();
2080 return false; // Other types have no identity values
2083 /// This function determines if the CastInst does not require any bits to be
2084 /// changed in order to effect the cast. Essentially, it identifies cases where
2085 /// no code gen is necessary for the cast, hence the name no-op cast. For
2086 /// example, the following are all no-op casts:
2087 /// # bitcast i32* %x to i8*
2088 /// # bitcast <2 x i32> %x to <4 x i16>
2089 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2090 /// @brief Determine if the described cast is a no-op.
2091 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2096 default: llvm_unreachable("Invalid CastOp");
2097 case Instruction::Trunc:
2098 case Instruction::ZExt:
2099 case Instruction::SExt:
2100 case Instruction::FPTrunc:
2101 case Instruction::FPExt:
2102 case Instruction::UIToFP:
2103 case Instruction::SIToFP:
2104 case Instruction::FPToUI:
2105 case Instruction::FPToSI:
2106 return false; // These always modify bits
2107 case Instruction::BitCast:
2108 return true; // BitCast never modifies bits.
2109 case Instruction::PtrToInt:
2110 return IntPtrTy->getScalarSizeInBits() ==
2111 DestTy->getScalarSizeInBits();
2112 case Instruction::IntToPtr:
2113 return IntPtrTy->getScalarSizeInBits() ==
2114 SrcTy->getScalarSizeInBits();
2118 /// @brief Determine if a cast is a no-op.
2119 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2120 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2123 /// This function determines if a pair of casts can be eliminated and what
2124 /// opcode should be used in the elimination. This assumes that there are two
2125 /// instructions like this:
2126 /// * %F = firstOpcode SrcTy %x to MidTy
2127 /// * %S = secondOpcode MidTy %F to DstTy
2128 /// The function returns a resultOpcode so these two casts can be replaced with:
2129 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2130 /// If no such cast is permited, the function returns 0.
2131 unsigned CastInst::isEliminableCastPair(
2132 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2133 Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy) {
2134 // Define the 144 possibilities for these two cast instructions. The values
2135 // in this matrix determine what to do in a given situation and select the
2136 // case in the switch below. The rows correspond to firstOp, the columns
2137 // correspond to secondOp. In looking at the table below, keep in mind
2138 // the following cast properties:
2140 // Size Compare Source Destination
2141 // Operator Src ? Size Type Sign Type Sign
2142 // -------- ------------ ------------------- ---------------------
2143 // TRUNC > Integer Any Integral Any
2144 // ZEXT < Integral Unsigned Integer Any
2145 // SEXT < Integral Signed Integer Any
2146 // FPTOUI n/a FloatPt n/a Integral Unsigned
2147 // FPTOSI n/a FloatPt n/a Integral Signed
2148 // UITOFP n/a Integral Unsigned FloatPt n/a
2149 // SITOFP n/a Integral Signed FloatPt n/a
2150 // FPTRUNC > FloatPt n/a FloatPt n/a
2151 // FPEXT < FloatPt n/a FloatPt n/a
2152 // PTRTOINT n/a Pointer n/a Integral Unsigned
2153 // INTTOPTR n/a Integral Unsigned Pointer n/a
2154 // BITCAST = FirstClass n/a FirstClass n/a
2156 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2157 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2158 // into "fptoui double to i64", but this loses information about the range
2159 // of the produced value (we no longer know the top-part is all zeros).
2160 // Further this conversion is often much more expensive for typical hardware,
2161 // and causes issues when building libgcc. We disallow fptosi+sext for the
2163 const unsigned numCastOps =
2164 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2165 static const uint8_t CastResults[numCastOps][numCastOps] = {
2166 // T F F U S F F P I B -+
2167 // R Z S P P I I T P 2 N T |
2168 // U E E 2 2 2 2 R E I T C +- secondOp
2169 // N X X U S F F N X N 2 V |
2170 // C T T I I P P C T T P T -+
2171 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2172 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2173 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2174 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2175 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2176 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2177 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2178 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2179 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2180 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2181 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2182 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2185 // If either of the casts are a bitcast from scalar to vector, disallow the
2186 // merging. However, bitcast of A->B->A are allowed.
2187 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2188 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2189 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2191 // Check if any of the bitcasts convert scalars<->vectors.
2192 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2193 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2194 // Unless we are bitcasing to the original type, disallow optimizations.
2195 if (!chainedBitcast) return 0;
2197 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2198 [secondOp-Instruction::CastOpsBegin];
2201 // categorically disallowed
2204 // allowed, use first cast's opcode
2207 // allowed, use second cast's opcode
2210 // no-op cast in second op implies firstOp as long as the DestTy
2211 // is integer and we are not converting between a vector and a
2213 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2217 // no-op cast in second op implies firstOp as long as the DestTy
2218 // is floating point.
2219 if (DstTy->isFloatingPointTy())
2223 // no-op cast in first op implies secondOp as long as the SrcTy
2225 if (SrcTy->isIntegerTy())
2229 // no-op cast in first op implies secondOp as long as the SrcTy
2230 // is a floating point.
2231 if (SrcTy->isFloatingPointTy())
2235 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2238 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2239 unsigned MidSize = MidTy->getScalarSizeInBits();
2240 if (MidSize >= PtrSize)
2241 return Instruction::BitCast;
2245 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2246 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2247 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2248 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2249 unsigned DstSize = DstTy->getScalarSizeInBits();
2250 if (SrcSize == DstSize)
2251 return Instruction::BitCast;
2252 else if (SrcSize < DstSize)
2256 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2257 return Instruction::ZExt;
2259 // fpext followed by ftrunc is allowed if the bit size returned to is
2260 // the same as the original, in which case its just a bitcast
2262 return Instruction::BitCast;
2263 return 0; // If the types are not the same we can't eliminate it.
2265 // bitcast followed by ptrtoint is allowed as long as the bitcast
2266 // is a pointer to pointer cast.
2267 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2271 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2272 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2276 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2279 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2280 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2281 unsigned DstSize = DstTy->getScalarSizeInBits();
2282 if (SrcSize <= PtrSize && SrcSize == DstSize)
2283 return Instruction::BitCast;
2287 // cast combination can't happen (error in input). This is for all cases
2288 // where the MidTy is not the same for the two cast instructions.
2289 llvm_unreachable("Invalid Cast Combination");
2291 llvm_unreachable("Error in CastResults table!!!");
2295 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2296 const Twine &Name, Instruction *InsertBefore) {
2297 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2298 // Construct and return the appropriate CastInst subclass
2300 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2301 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2302 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2303 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2304 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2305 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2306 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2307 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2308 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2309 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2310 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2311 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2312 default: llvm_unreachable("Invalid opcode provided");
2316 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2317 const Twine &Name, BasicBlock *InsertAtEnd) {
2318 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2319 // Construct and return the appropriate CastInst subclass
2321 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2322 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2323 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2324 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2325 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2326 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2327 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2328 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2329 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2330 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2331 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2332 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2333 default: llvm_unreachable("Invalid opcode provided");
2337 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2339 Instruction *InsertBefore) {
2340 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2341 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2342 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2345 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2347 BasicBlock *InsertAtEnd) {
2348 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2349 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2350 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2353 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2355 Instruction *InsertBefore) {
2356 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2357 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2358 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2361 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2363 BasicBlock *InsertAtEnd) {
2364 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2365 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2366 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2369 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2371 Instruction *InsertBefore) {
2372 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2373 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2374 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2377 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2379 BasicBlock *InsertAtEnd) {
2380 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2381 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2382 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2385 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2387 BasicBlock *InsertAtEnd) {
2388 assert(S->getType()->isPointerTy() && "Invalid cast");
2389 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2392 if (Ty->isIntegerTy())
2393 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2394 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2397 /// @brief Create a BitCast or a PtrToInt cast instruction
2398 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2400 Instruction *InsertBefore) {
2401 assert(S->getType()->isPointerTy() && "Invalid cast");
2402 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2405 if (Ty->isIntegerTy())
2406 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2407 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2410 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2411 bool isSigned, const Twine &Name,
2412 Instruction *InsertBefore) {
2413 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2414 "Invalid integer cast");
2415 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2416 unsigned DstBits = Ty->getScalarSizeInBits();
2417 Instruction::CastOps opcode =
2418 (SrcBits == DstBits ? Instruction::BitCast :
2419 (SrcBits > DstBits ? Instruction::Trunc :
2420 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2421 return Create(opcode, C, Ty, Name, InsertBefore);
2424 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2425 bool isSigned, const Twine &Name,
2426 BasicBlock *InsertAtEnd) {
2427 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2429 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2430 unsigned DstBits = Ty->getScalarSizeInBits();
2431 Instruction::CastOps opcode =
2432 (SrcBits == DstBits ? Instruction::BitCast :
2433 (SrcBits > DstBits ? Instruction::Trunc :
2434 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2435 return Create(opcode, C, Ty, Name, InsertAtEnd);
2438 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2440 Instruction *InsertBefore) {
2441 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2443 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2444 unsigned DstBits = Ty->getScalarSizeInBits();
2445 Instruction::CastOps opcode =
2446 (SrcBits == DstBits ? Instruction::BitCast :
2447 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2448 return Create(opcode, C, Ty, Name, InsertBefore);
2451 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2453 BasicBlock *InsertAtEnd) {
2454 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2456 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2457 unsigned DstBits = Ty->getScalarSizeInBits();
2458 Instruction::CastOps opcode =
2459 (SrcBits == DstBits ? Instruction::BitCast :
2460 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2461 return Create(opcode, C, Ty, Name, InsertAtEnd);
2464 // Check whether it is valid to call getCastOpcode for these types.
2465 // This routine must be kept in sync with getCastOpcode.
2466 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2467 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2470 if (SrcTy == DestTy)
2473 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2474 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2475 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2476 // An element by element cast. Valid if casting the elements is valid.
2477 SrcTy = SrcVecTy->getElementType();
2478 DestTy = DestVecTy->getElementType();
2481 // Get the bit sizes, we'll need these
2482 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2483 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2485 // Run through the possibilities ...
2486 if (DestTy->isIntegerTy()) { // Casting to integral
2487 if (SrcTy->isIntegerTy()) { // Casting from integral
2489 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2491 } else if (SrcTy->isVectorTy()) { // Casting from vector
2492 return DestBits == SrcBits;
2493 } else { // Casting from something else
2494 return SrcTy->isPointerTy();
2496 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2497 if (SrcTy->isIntegerTy()) { // Casting from integral
2499 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2501 } else if (SrcTy->isVectorTy()) { // Casting from vector
2502 return DestBits == SrcBits;
2503 } else { // Casting from something else
2506 } else if (DestTy->isVectorTy()) { // Casting to vector
2507 return DestBits == SrcBits;
2508 } else if (DestTy->isPointerTy()) { // Casting to pointer
2509 if (SrcTy->isPointerTy()) { // Casting from pointer
2511 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2513 } else { // Casting from something else
2516 } else if (DestTy->isX86_MMXTy()) {
2517 if (SrcTy->isVectorTy()) {
2518 return DestBits == SrcBits; // 64-bit vector to MMX
2522 } else { // Casting to something else
2527 // Provide a way to get a "cast" where the cast opcode is inferred from the
2528 // types and size of the operand. This, basically, is a parallel of the
2529 // logic in the castIsValid function below. This axiom should hold:
2530 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2531 // should not assert in castIsValid. In other words, this produces a "correct"
2532 // casting opcode for the arguments passed to it.
2533 // This routine must be kept in sync with isCastable.
2534 Instruction::CastOps
2535 CastInst::getCastOpcode(
2536 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2537 Type *SrcTy = Src->getType();
2539 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2540 "Only first class types are castable!");
2542 if (SrcTy == DestTy)
2545 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2546 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2547 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2548 // An element by element cast. Find the appropriate opcode based on the
2550 SrcTy = SrcVecTy->getElementType();
2551 DestTy = DestVecTy->getElementType();
2554 // Get the bit sizes, we'll need these
2555 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2556 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2558 // Run through the possibilities ...
2559 if (DestTy->isIntegerTy()) { // Casting to integral
2560 if (SrcTy->isIntegerTy()) { // Casting from integral
2561 if (DestBits < SrcBits)
2562 return Trunc; // int -> smaller int
2563 else if (DestBits > SrcBits) { // its an extension
2565 return SExt; // signed -> SEXT
2567 return ZExt; // unsigned -> ZEXT
2569 return BitCast; // Same size, No-op cast
2571 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2573 return FPToSI; // FP -> sint
2575 return FPToUI; // FP -> uint
2576 } else if (SrcTy->isVectorTy()) {
2577 assert(DestBits == SrcBits &&
2578 "Casting vector to integer of different width");
2579 return BitCast; // Same size, no-op cast
2581 assert(SrcTy->isPointerTy() &&
2582 "Casting from a value that is not first-class type");
2583 return PtrToInt; // ptr -> int
2585 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2586 if (SrcTy->isIntegerTy()) { // Casting from integral
2588 return SIToFP; // sint -> FP
2590 return UIToFP; // uint -> FP
2591 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2592 if (DestBits < SrcBits) {
2593 return FPTrunc; // FP -> smaller FP
2594 } else if (DestBits > SrcBits) {
2595 return FPExt; // FP -> larger FP
2597 return BitCast; // same size, no-op cast
2599 } else if (SrcTy->isVectorTy()) {
2600 assert(DestBits == SrcBits &&
2601 "Casting vector to floating point of different width");
2602 return BitCast; // same size, no-op cast
2604 llvm_unreachable("Casting pointer or non-first class to float");
2605 } else if (DestTy->isVectorTy()) {
2606 assert(DestBits == SrcBits &&
2607 "Illegal cast to vector (wrong type or size)");
2609 } else if (DestTy->isPointerTy()) {
2610 if (SrcTy->isPointerTy()) {
2611 return BitCast; // ptr -> ptr
2612 } else if (SrcTy->isIntegerTy()) {
2613 return IntToPtr; // int -> ptr
2615 llvm_unreachable("Casting pointer to other than pointer or int");
2616 } else if (DestTy->isX86_MMXTy()) {
2617 if (SrcTy->isVectorTy()) {
2618 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2619 return BitCast; // 64-bit vector to MMX
2621 llvm_unreachable("Illegal cast to X86_MMX");
2623 llvm_unreachable("Casting to type that is not first-class");
2626 //===----------------------------------------------------------------------===//
2627 // CastInst SubClass Constructors
2628 //===----------------------------------------------------------------------===//
2630 /// Check that the construction parameters for a CastInst are correct. This
2631 /// could be broken out into the separate constructors but it is useful to have
2632 /// it in one place and to eliminate the redundant code for getting the sizes
2633 /// of the types involved.
2635 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2637 // Check for type sanity on the arguments
2638 Type *SrcTy = S->getType();
2639 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2640 SrcTy->isAggregateType() || DstTy->isAggregateType())
2643 // Get the size of the types in bits, we'll need this later
2644 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2645 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2647 // If these are vector types, get the lengths of the vectors (using zero for
2648 // scalar types means that checking that vector lengths match also checks that
2649 // scalars are not being converted to vectors or vectors to scalars).
2650 unsigned SrcLength = SrcTy->isVectorTy() ?
2651 cast<VectorType>(SrcTy)->getNumElements() : 0;
2652 unsigned DstLength = DstTy->isVectorTy() ?
2653 cast<VectorType>(DstTy)->getNumElements() : 0;
2655 // Switch on the opcode provided
2657 default: return false; // This is an input error
2658 case Instruction::Trunc:
2659 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2660 SrcLength == DstLength && SrcBitSize > DstBitSize;
2661 case Instruction::ZExt:
2662 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2663 SrcLength == DstLength && SrcBitSize < DstBitSize;
2664 case Instruction::SExt:
2665 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2666 SrcLength == DstLength && SrcBitSize < DstBitSize;
2667 case Instruction::FPTrunc:
2668 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2669 SrcLength == DstLength && SrcBitSize > DstBitSize;
2670 case Instruction::FPExt:
2671 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2672 SrcLength == DstLength && SrcBitSize < DstBitSize;
2673 case Instruction::UIToFP:
2674 case Instruction::SIToFP:
2675 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2676 SrcLength == DstLength;
2677 case Instruction::FPToUI:
2678 case Instruction::FPToSI:
2679 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2680 SrcLength == DstLength;
2681 case Instruction::PtrToInt:
2682 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2684 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2685 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2687 return SrcTy->getScalarType()->isPointerTy() &&
2688 DstTy->getScalarType()->isIntegerTy();
2689 case Instruction::IntToPtr:
2690 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2692 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2693 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2695 return SrcTy->getScalarType()->isIntegerTy() &&
2696 DstTy->getScalarType()->isPointerTy();
2697 case Instruction::BitCast:
2698 // BitCast implies a no-op cast of type only. No bits change.
2699 // However, you can't cast pointers to anything but pointers.
2700 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2703 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2704 // these cases, the cast is okay if the source and destination bit widths
2706 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2710 TruncInst::TruncInst(
2711 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2712 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2713 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2716 TruncInst::TruncInst(
2717 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2718 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2719 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2723 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2724 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2725 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2729 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2730 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2731 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2734 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2735 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2736 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2740 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2741 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2742 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2745 FPTruncInst::FPTruncInst(
2746 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2747 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2748 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2751 FPTruncInst::FPTruncInst(
2752 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2753 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2754 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2757 FPExtInst::FPExtInst(
2758 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2759 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2760 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2763 FPExtInst::FPExtInst(
2764 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2765 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2766 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2769 UIToFPInst::UIToFPInst(
2770 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2771 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2772 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2775 UIToFPInst::UIToFPInst(
2776 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2777 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2778 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2781 SIToFPInst::SIToFPInst(
2782 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2783 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2784 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2787 SIToFPInst::SIToFPInst(
2788 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2789 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2790 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2793 FPToUIInst::FPToUIInst(
2794 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2795 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2796 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2799 FPToUIInst::FPToUIInst(
2800 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2801 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2802 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2805 FPToSIInst::FPToSIInst(
2806 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2807 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2808 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2811 FPToSIInst::FPToSIInst(
2812 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2813 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2814 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2817 PtrToIntInst::PtrToIntInst(
2818 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2819 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2820 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2823 PtrToIntInst::PtrToIntInst(
2824 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2825 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2826 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2829 IntToPtrInst::IntToPtrInst(
2830 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2831 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2832 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2835 IntToPtrInst::IntToPtrInst(
2836 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2837 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2838 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2841 BitCastInst::BitCastInst(
2842 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2843 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2844 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2847 BitCastInst::BitCastInst(
2848 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2849 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2850 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2853 //===----------------------------------------------------------------------===//
2855 //===----------------------------------------------------------------------===//
2857 void CmpInst::anchor() {}
2859 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2860 Value *LHS, Value *RHS, const Twine &Name,
2861 Instruction *InsertBefore)
2862 : Instruction(ty, op,
2863 OperandTraits<CmpInst>::op_begin(this),
2864 OperandTraits<CmpInst>::operands(this),
2868 setPredicate((Predicate)predicate);
2872 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2873 Value *LHS, Value *RHS, const Twine &Name,
2874 BasicBlock *InsertAtEnd)
2875 : Instruction(ty, op,
2876 OperandTraits<CmpInst>::op_begin(this),
2877 OperandTraits<CmpInst>::operands(this),
2881 setPredicate((Predicate)predicate);
2886 CmpInst::Create(OtherOps Op, unsigned short predicate,
2887 Value *S1, Value *S2,
2888 const Twine &Name, Instruction *InsertBefore) {
2889 if (Op == Instruction::ICmp) {
2891 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2894 return new ICmpInst(CmpInst::Predicate(predicate),
2899 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2902 return new FCmpInst(CmpInst::Predicate(predicate),
2907 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2908 const Twine &Name, BasicBlock *InsertAtEnd) {
2909 if (Op == Instruction::ICmp) {
2910 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2913 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2917 void CmpInst::swapOperands() {
2918 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2921 cast<FCmpInst>(this)->swapOperands();
2924 bool CmpInst::isCommutative() const {
2925 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2926 return IC->isCommutative();
2927 return cast<FCmpInst>(this)->isCommutative();
2930 bool CmpInst::isEquality() const {
2931 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2932 return IC->isEquality();
2933 return cast<FCmpInst>(this)->isEquality();
2937 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2939 default: llvm_unreachable("Unknown cmp predicate!");
2940 case ICMP_EQ: return ICMP_NE;
2941 case ICMP_NE: return ICMP_EQ;
2942 case ICMP_UGT: return ICMP_ULE;
2943 case ICMP_ULT: return ICMP_UGE;
2944 case ICMP_UGE: return ICMP_ULT;
2945 case ICMP_ULE: return ICMP_UGT;
2946 case ICMP_SGT: return ICMP_SLE;
2947 case ICMP_SLT: return ICMP_SGE;
2948 case ICMP_SGE: return ICMP_SLT;
2949 case ICMP_SLE: return ICMP_SGT;
2951 case FCMP_OEQ: return FCMP_UNE;
2952 case FCMP_ONE: return FCMP_UEQ;
2953 case FCMP_OGT: return FCMP_ULE;
2954 case FCMP_OLT: return FCMP_UGE;
2955 case FCMP_OGE: return FCMP_ULT;
2956 case FCMP_OLE: return FCMP_UGT;
2957 case FCMP_UEQ: return FCMP_ONE;
2958 case FCMP_UNE: return FCMP_OEQ;
2959 case FCMP_UGT: return FCMP_OLE;
2960 case FCMP_ULT: return FCMP_OGE;
2961 case FCMP_UGE: return FCMP_OLT;
2962 case FCMP_ULE: return FCMP_OGT;
2963 case FCMP_ORD: return FCMP_UNO;
2964 case FCMP_UNO: return FCMP_ORD;
2965 case FCMP_TRUE: return FCMP_FALSE;
2966 case FCMP_FALSE: return FCMP_TRUE;
2970 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2972 default: llvm_unreachable("Unknown icmp predicate!");
2973 case ICMP_EQ: case ICMP_NE:
2974 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2976 case ICMP_UGT: return ICMP_SGT;
2977 case ICMP_ULT: return ICMP_SLT;
2978 case ICMP_UGE: return ICMP_SGE;
2979 case ICMP_ULE: return ICMP_SLE;
2983 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2985 default: llvm_unreachable("Unknown icmp predicate!");
2986 case ICMP_EQ: case ICMP_NE:
2987 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2989 case ICMP_SGT: return ICMP_UGT;
2990 case ICMP_SLT: return ICMP_ULT;
2991 case ICMP_SGE: return ICMP_UGE;
2992 case ICMP_SLE: return ICMP_ULE;
2996 /// Initialize a set of values that all satisfy the condition with C.
2999 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3002 uint32_t BitWidth = C.getBitWidth();
3004 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3005 case ICmpInst::ICMP_EQ: Upper++; break;
3006 case ICmpInst::ICMP_NE: Lower++; break;
3007 case ICmpInst::ICMP_ULT:
3008 Lower = APInt::getMinValue(BitWidth);
3009 // Check for an empty-set condition.
3011 return ConstantRange(BitWidth, /*isFullSet=*/false);
3013 case ICmpInst::ICMP_SLT:
3014 Lower = APInt::getSignedMinValue(BitWidth);
3015 // Check for an empty-set condition.
3017 return ConstantRange(BitWidth, /*isFullSet=*/false);
3019 case ICmpInst::ICMP_UGT:
3020 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3021 // Check for an empty-set condition.
3023 return ConstantRange(BitWidth, /*isFullSet=*/false);
3025 case ICmpInst::ICMP_SGT:
3026 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3027 // Check for an empty-set condition.
3029 return ConstantRange(BitWidth, /*isFullSet=*/false);
3031 case ICmpInst::ICMP_ULE:
3032 Lower = APInt::getMinValue(BitWidth); Upper++;
3033 // Check for a full-set condition.
3035 return ConstantRange(BitWidth, /*isFullSet=*/true);
3037 case ICmpInst::ICMP_SLE:
3038 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
3039 // Check for a full-set condition.
3041 return ConstantRange(BitWidth, /*isFullSet=*/true);
3043 case ICmpInst::ICMP_UGE:
3044 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3045 // Check for a full-set condition.
3047 return ConstantRange(BitWidth, /*isFullSet=*/true);
3049 case ICmpInst::ICMP_SGE:
3050 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3051 // Check for a full-set condition.
3053 return ConstantRange(BitWidth, /*isFullSet=*/true);
3056 return ConstantRange(Lower, Upper);
3059 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3061 default: llvm_unreachable("Unknown cmp predicate!");
3062 case ICMP_EQ: case ICMP_NE:
3064 case ICMP_SGT: return ICMP_SLT;
3065 case ICMP_SLT: return ICMP_SGT;
3066 case ICMP_SGE: return ICMP_SLE;
3067 case ICMP_SLE: return ICMP_SGE;
3068 case ICMP_UGT: return ICMP_ULT;
3069 case ICMP_ULT: return ICMP_UGT;
3070 case ICMP_UGE: return ICMP_ULE;
3071 case ICMP_ULE: return ICMP_UGE;
3073 case FCMP_FALSE: case FCMP_TRUE:
3074 case FCMP_OEQ: case FCMP_ONE:
3075 case FCMP_UEQ: case FCMP_UNE:
3076 case FCMP_ORD: case FCMP_UNO:
3078 case FCMP_OGT: return FCMP_OLT;
3079 case FCMP_OLT: return FCMP_OGT;
3080 case FCMP_OGE: return FCMP_OLE;
3081 case FCMP_OLE: return FCMP_OGE;
3082 case FCMP_UGT: return FCMP_ULT;
3083 case FCMP_ULT: return FCMP_UGT;
3084 case FCMP_UGE: return FCMP_ULE;
3085 case FCMP_ULE: return FCMP_UGE;
3089 bool CmpInst::isUnsigned(unsigned short predicate) {
3090 switch (predicate) {
3091 default: return false;
3092 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3093 case ICmpInst::ICMP_UGE: return true;
3097 bool CmpInst::isSigned(unsigned short predicate) {
3098 switch (predicate) {
3099 default: return false;
3100 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3101 case ICmpInst::ICMP_SGE: return true;
3105 bool CmpInst::isOrdered(unsigned short predicate) {
3106 switch (predicate) {
3107 default: return false;
3108 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3109 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3110 case FCmpInst::FCMP_ORD: return true;
3114 bool CmpInst::isUnordered(unsigned short predicate) {
3115 switch (predicate) {
3116 default: return false;
3117 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3118 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3119 case FCmpInst::FCMP_UNO: return true;
3123 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3125 default: return false;
3126 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3127 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3131 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3133 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3134 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3135 default: return false;
3140 //===----------------------------------------------------------------------===//
3141 // SwitchInst Implementation
3142 //===----------------------------------------------------------------------===//
3144 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3145 assert(Value && Default && NumReserved);
3146 ReservedSpace = NumReserved;
3148 OperandList = allocHungoffUses(ReservedSpace);
3150 OperandList[0] = Value;
3151 OperandList[1] = Default;
3154 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3155 /// switch on and a default destination. The number of additional cases can
3156 /// be specified here to make memory allocation more efficient. This
3157 /// constructor can also autoinsert before another instruction.
3158 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3159 Instruction *InsertBefore)
3160 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3161 0, 0, InsertBefore) {
3162 init(Value, Default, 2+NumCases*2);
3165 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3166 /// switch on and a default destination. The number of additional cases can
3167 /// be specified here to make memory allocation more efficient. This
3168 /// constructor also autoinserts at the end of the specified BasicBlock.
3169 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3170 BasicBlock *InsertAtEnd)
3171 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3172 0, 0, InsertAtEnd) {
3173 init(Value, Default, 2+NumCases*2);
3176 SwitchInst::SwitchInst(const SwitchInst &SI)
3177 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3178 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3179 NumOperands = SI.getNumOperands();
3180 Use *OL = OperandList, *InOL = SI.OperandList;
3181 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3183 OL[i+1] = InOL[i+1];
3185 TheSubsets = SI.TheSubsets;
3186 SubclassOptionalData = SI.SubclassOptionalData;
3189 SwitchInst::~SwitchInst() {
3194 /// addCase - Add an entry to the switch instruction...
3196 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3197 IntegersSubsetToBB Mapping;
3199 // FIXME: Currently we work with ConstantInt based cases.
3200 // So inititalize IntItem container directly from ConstantInt.
3201 Mapping.add(IntItem::fromConstantInt(OnVal));
3202 IntegersSubset CaseRanges = Mapping.getCase();
3203 addCase(CaseRanges, Dest);
3206 void SwitchInst::addCase(IntegersSubset& OnVal, BasicBlock *Dest) {
3207 unsigned NewCaseIdx = getNumCases();
3208 unsigned OpNo = NumOperands;
3209 if (OpNo+2 > ReservedSpace)
3210 growOperands(); // Get more space!
3211 // Initialize some new operands.
3212 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3213 NumOperands = OpNo+2;
3215 SubsetsIt TheSubsetsIt = TheSubsets.insert(TheSubsets.end(), OnVal);
3217 CaseIt Case(this, NewCaseIdx, TheSubsetsIt);
3218 Case.updateCaseValueOperand(OnVal);
3219 Case.setSuccessor(Dest);
3222 /// removeCase - This method removes the specified case and its successor
3223 /// from the switch instruction.
3224 void SwitchInst::removeCase(CaseIt& i) {
3225 unsigned idx = i.getCaseIndex();
3227 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3229 unsigned NumOps = getNumOperands();
3230 Use *OL = OperandList;
3232 // Overwrite this case with the end of the list.
3233 if (2 + (idx + 1) * 2 != NumOps) {
3234 OL[2 + idx * 2] = OL[NumOps - 2];
3235 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3238 // Nuke the last value.
3239 OL[NumOps-2].set(0);
3240 OL[NumOps-2+1].set(0);
3242 // Do the same with TheCases collection:
3243 if (i.SubsetIt != --TheSubsets.end()) {
3244 *i.SubsetIt = TheSubsets.back();
3245 TheSubsets.pop_back();
3247 TheSubsets.pop_back();
3248 i.SubsetIt = TheSubsets.end();
3251 NumOperands = NumOps-2;
3254 /// growOperands - grow operands - This grows the operand list in response
3255 /// to a push_back style of operation. This grows the number of ops by 3 times.
3257 void SwitchInst::growOperands() {
3258 unsigned e = getNumOperands();
3259 unsigned NumOps = e*3;
3261 ReservedSpace = NumOps;
3262 Use *NewOps = allocHungoffUses(NumOps);
3263 Use *OldOps = OperandList;
3264 for (unsigned i = 0; i != e; ++i) {
3265 NewOps[i] = OldOps[i];
3267 OperandList = NewOps;
3268 Use::zap(OldOps, OldOps + e, true);
3272 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3273 return getSuccessor(idx);
3275 unsigned SwitchInst::getNumSuccessorsV() const {
3276 return getNumSuccessors();
3278 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3279 setSuccessor(idx, B);
3282 //===----------------------------------------------------------------------===//
3283 // IndirectBrInst Implementation
3284 //===----------------------------------------------------------------------===//
3286 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3287 assert(Address && Address->getType()->isPointerTy() &&
3288 "Address of indirectbr must be a pointer");
3289 ReservedSpace = 1+NumDests;
3291 OperandList = allocHungoffUses(ReservedSpace);
3293 OperandList[0] = Address;
3297 /// growOperands - grow operands - This grows the operand list in response
3298 /// to a push_back style of operation. This grows the number of ops by 2 times.
3300 void IndirectBrInst::growOperands() {
3301 unsigned e = getNumOperands();
3302 unsigned NumOps = e*2;
3304 ReservedSpace = NumOps;
3305 Use *NewOps = allocHungoffUses(NumOps);
3306 Use *OldOps = OperandList;
3307 for (unsigned i = 0; i != e; ++i)
3308 NewOps[i] = OldOps[i];
3309 OperandList = NewOps;
3310 Use::zap(OldOps, OldOps + e, true);
3313 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3314 Instruction *InsertBefore)
3315 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3316 0, 0, InsertBefore) {
3317 init(Address, NumCases);
3320 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3321 BasicBlock *InsertAtEnd)
3322 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3323 0, 0, InsertAtEnd) {
3324 init(Address, NumCases);
3327 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3328 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3329 allocHungoffUses(IBI.getNumOperands()),
3330 IBI.getNumOperands()) {
3331 Use *OL = OperandList, *InOL = IBI.OperandList;
3332 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3334 SubclassOptionalData = IBI.SubclassOptionalData;
3337 IndirectBrInst::~IndirectBrInst() {
3341 /// addDestination - Add a destination.
3343 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3344 unsigned OpNo = NumOperands;
3345 if (OpNo+1 > ReservedSpace)
3346 growOperands(); // Get more space!
3347 // Initialize some new operands.
3348 assert(OpNo < ReservedSpace && "Growing didn't work!");
3349 NumOperands = OpNo+1;
3350 OperandList[OpNo] = DestBB;
3353 /// removeDestination - This method removes the specified successor from the
3354 /// indirectbr instruction.
3355 void IndirectBrInst::removeDestination(unsigned idx) {
3356 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3358 unsigned NumOps = getNumOperands();
3359 Use *OL = OperandList;
3361 // Replace this value with the last one.
3362 OL[idx+1] = OL[NumOps-1];
3364 // Nuke the last value.
3365 OL[NumOps-1].set(0);
3366 NumOperands = NumOps-1;
3369 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3370 return getSuccessor(idx);
3372 unsigned IndirectBrInst::getNumSuccessorsV() const {
3373 return getNumSuccessors();
3375 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3376 setSuccessor(idx, B);
3379 //===----------------------------------------------------------------------===//
3380 // clone_impl() implementations
3381 //===----------------------------------------------------------------------===//
3383 // Define these methods here so vtables don't get emitted into every translation
3384 // unit that uses these classes.
3386 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3387 return new (getNumOperands()) GetElementPtrInst(*this);
3390 BinaryOperator *BinaryOperator::clone_impl() const {
3391 return Create(getOpcode(), Op<0>(), Op<1>());
3394 FCmpInst* FCmpInst::clone_impl() const {
3395 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3398 ICmpInst* ICmpInst::clone_impl() const {
3399 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3402 ExtractValueInst *ExtractValueInst::clone_impl() const {
3403 return new ExtractValueInst(*this);
3406 InsertValueInst *InsertValueInst::clone_impl() const {
3407 return new InsertValueInst(*this);
3410 AllocaInst *AllocaInst::clone_impl() const {
3411 return new AllocaInst(getAllocatedType(),
3412 (Value*)getOperand(0),
3416 LoadInst *LoadInst::clone_impl() const {
3417 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3418 getAlignment(), getOrdering(), getSynchScope());
3421 StoreInst *StoreInst::clone_impl() const {
3422 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3423 getAlignment(), getOrdering(), getSynchScope());
3427 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3428 AtomicCmpXchgInst *Result =
3429 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3430 getOrdering(), getSynchScope());
3431 Result->setVolatile(isVolatile());
3435 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3436 AtomicRMWInst *Result =
3437 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3438 getOrdering(), getSynchScope());
3439 Result->setVolatile(isVolatile());
3443 FenceInst *FenceInst::clone_impl() const {
3444 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3447 TruncInst *TruncInst::clone_impl() const {
3448 return new TruncInst(getOperand(0), getType());
3451 ZExtInst *ZExtInst::clone_impl() const {
3452 return new ZExtInst(getOperand(0), getType());
3455 SExtInst *SExtInst::clone_impl() const {
3456 return new SExtInst(getOperand(0), getType());
3459 FPTruncInst *FPTruncInst::clone_impl() const {
3460 return new FPTruncInst(getOperand(0), getType());
3463 FPExtInst *FPExtInst::clone_impl() const {
3464 return new FPExtInst(getOperand(0), getType());
3467 UIToFPInst *UIToFPInst::clone_impl() const {
3468 return new UIToFPInst(getOperand(0), getType());
3471 SIToFPInst *SIToFPInst::clone_impl() const {
3472 return new SIToFPInst(getOperand(0), getType());
3475 FPToUIInst *FPToUIInst::clone_impl() const {
3476 return new FPToUIInst(getOperand(0), getType());
3479 FPToSIInst *FPToSIInst::clone_impl() const {
3480 return new FPToSIInst(getOperand(0), getType());
3483 PtrToIntInst *PtrToIntInst::clone_impl() const {
3484 return new PtrToIntInst(getOperand(0), getType());
3487 IntToPtrInst *IntToPtrInst::clone_impl() const {
3488 return new IntToPtrInst(getOperand(0), getType());
3491 BitCastInst *BitCastInst::clone_impl() const {
3492 return new BitCastInst(getOperand(0), getType());
3495 CallInst *CallInst::clone_impl() const {
3496 return new(getNumOperands()) CallInst(*this);
3499 SelectInst *SelectInst::clone_impl() const {
3500 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3503 VAArgInst *VAArgInst::clone_impl() const {
3504 return new VAArgInst(getOperand(0), getType());
3507 ExtractElementInst *ExtractElementInst::clone_impl() const {
3508 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3511 InsertElementInst *InsertElementInst::clone_impl() const {
3512 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3515 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3516 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3519 PHINode *PHINode::clone_impl() const {
3520 return new PHINode(*this);
3523 LandingPadInst *LandingPadInst::clone_impl() const {
3524 return new LandingPadInst(*this);
3527 ReturnInst *ReturnInst::clone_impl() const {
3528 return new(getNumOperands()) ReturnInst(*this);
3531 BranchInst *BranchInst::clone_impl() const {
3532 return new(getNumOperands()) BranchInst(*this);
3535 SwitchInst *SwitchInst::clone_impl() const {
3536 return new SwitchInst(*this);
3539 IndirectBrInst *IndirectBrInst::clone_impl() const {
3540 return new IndirectBrInst(*this);
3544 InvokeInst *InvokeInst::clone_impl() const {
3545 return new(getNumOperands()) InvokeInst(*this);
3548 ResumeInst *ResumeInst::clone_impl() const {
3549 return new(1) ResumeInst(*this);
3552 UnreachableInst *UnreachableInst::clone_impl() const {
3553 LLVMContext &Context = getContext();
3554 return new UnreachableInst(Context);