1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/Instructions.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/Operator.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/MathExtras.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 User::op_iterator CallSite::getCallee() const {
34 Instruction *II(getInstruction());
36 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
37 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
40 //===----------------------------------------------------------------------===//
41 // TerminatorInst Class
42 //===----------------------------------------------------------------------===//
44 // Out of line virtual method, so the vtable, etc has a home.
45 TerminatorInst::~TerminatorInst() {
48 //===----------------------------------------------------------------------===//
49 // UnaryInstruction Class
50 //===----------------------------------------------------------------------===//
52 // Out of line virtual method, so the vtable, etc has a home.
53 UnaryInstruction::~UnaryInstruction() {
56 //===----------------------------------------------------------------------===//
58 //===----------------------------------------------------------------------===//
60 /// areInvalidOperands - Return a string if the specified operands are invalid
61 /// for a select operation, otherwise return null.
62 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
63 if (Op1->getType() != Op2->getType())
64 return "both values to select must have same type";
66 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
68 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
69 return "vector select condition element type must be i1";
70 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
72 return "selected values for vector select must be vectors";
73 if (ET->getNumElements() != VT->getNumElements())
74 return "vector select requires selected vectors to have "
75 "the same vector length as select condition";
76 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
77 return "select condition must be i1 or <n x i1>";
83 //===----------------------------------------------------------------------===//
85 //===----------------------------------------------------------------------===//
87 PHINode::PHINode(const PHINode &PN)
88 : Instruction(PN.getType(), Instruction::PHI,
89 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
90 ReservedSpace(PN.getNumOperands()) {
91 std::copy(PN.op_begin(), PN.op_end(), op_begin());
92 std::copy(PN.block_begin(), PN.block_end(), block_begin());
93 SubclassOptionalData = PN.SubclassOptionalData;
100 Use *PHINode::allocHungoffUses(unsigned N) const {
101 // Allocate the array of Uses of the incoming values, followed by a pointer
102 // (with bottom bit set) to the User, followed by the array of pointers to
103 // the incoming basic blocks.
104 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
105 + N * sizeof(BasicBlock*);
106 Use *Begin = static_cast<Use*>(::operator new(size));
107 Use *End = Begin + N;
108 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
109 return Use::initTags(Begin, End);
112 // removeIncomingValue - Remove an incoming value. This is useful if a
113 // predecessor basic block is deleted.
114 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
115 Value *Removed = getIncomingValue(Idx);
117 // Move everything after this operand down.
119 // FIXME: we could just swap with the end of the list, then erase. However,
120 // clients might not expect this to happen. The code as it is thrashes the
121 // use/def lists, which is kinda lame.
122 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
123 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
125 // Nuke the last value.
129 // If the PHI node is dead, because it has zero entries, nuke it now.
130 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
131 // If anyone is using this PHI, make them use a dummy value instead...
132 replaceAllUsesWith(UndefValue::get(getType()));
138 /// growOperands - grow operands - This grows the operand list in response
139 /// to a push_back style of operation. This grows the number of ops by 1.5
142 void PHINode::growOperands() {
143 unsigned e = getNumOperands();
144 unsigned NumOps = e + e / 2;
145 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
147 Use *OldOps = op_begin();
148 BasicBlock **OldBlocks = block_begin();
150 ReservedSpace = NumOps;
151 OperandList = allocHungoffUses(ReservedSpace);
153 std::copy(OldOps, OldOps + e, op_begin());
154 std::copy(OldBlocks, OldBlocks + e, block_begin());
156 Use::zap(OldOps, OldOps + e, true);
159 /// hasConstantValue - If the specified PHI node always merges together the same
160 /// value, return the value, otherwise return null.
161 Value *PHINode::hasConstantValue() const {
162 // Exploit the fact that phi nodes always have at least one entry.
163 Value *ConstantValue = getIncomingValue(0);
164 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
165 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
166 if (ConstantValue != this)
167 return 0; // Incoming values not all the same.
168 // The case where the first value is this PHI.
169 ConstantValue = getIncomingValue(i);
171 if (ConstantValue == this)
172 return UndefValue::get(getType());
173 return ConstantValue;
176 //===----------------------------------------------------------------------===//
177 // LandingPadInst Implementation
178 //===----------------------------------------------------------------------===//
180 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
181 unsigned NumReservedValues, const Twine &NameStr,
182 Instruction *InsertBefore)
183 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
184 init(PersonalityFn, 1 + NumReservedValues, NameStr);
187 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
188 unsigned NumReservedValues, const Twine &NameStr,
189 BasicBlock *InsertAtEnd)
190 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
191 init(PersonalityFn, 1 + NumReservedValues, NameStr);
194 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
195 : Instruction(LP.getType(), Instruction::LandingPad,
196 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
197 ReservedSpace(LP.getNumOperands()) {
198 Use *OL = OperandList, *InOL = LP.OperandList;
199 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
202 setCleanup(LP.isCleanup());
205 LandingPadInst::~LandingPadInst() {
209 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
210 unsigned NumReservedClauses,
211 const Twine &NameStr,
212 Instruction *InsertBefore) {
213 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
217 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
218 unsigned NumReservedClauses,
219 const Twine &NameStr,
220 BasicBlock *InsertAtEnd) {
221 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
225 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
226 const Twine &NameStr) {
227 ReservedSpace = NumReservedValues;
229 OperandList = allocHungoffUses(ReservedSpace);
230 OperandList[0] = PersFn;
235 /// growOperands - grow operands - This grows the operand list in response to a
236 /// push_back style of operation. This grows the number of ops by 2 times.
237 void LandingPadInst::growOperands(unsigned Size) {
238 unsigned e = getNumOperands();
239 if (ReservedSpace >= e + Size) return;
240 ReservedSpace = (e + Size / 2) * 2;
242 Use *NewOps = allocHungoffUses(ReservedSpace);
243 Use *OldOps = OperandList;
244 for (unsigned i = 0; i != e; ++i)
245 NewOps[i] = OldOps[i];
247 OperandList = NewOps;
248 Use::zap(OldOps, OldOps + e, true);
251 void LandingPadInst::addClause(Value *Val) {
252 unsigned OpNo = getNumOperands();
254 assert(OpNo < ReservedSpace && "Growing didn't work!");
256 OperandList[OpNo] = Val;
259 bool LandingPadInst::hasCatchAll() const {
260 for (unsigned I = 0, E = getNumClauses(); I != E; ++I)
261 if (isCatch(I) && isa<ConstantPointerNull>(getClause(I)))
266 //===----------------------------------------------------------------------===//
267 // CallInst Implementation
268 //===----------------------------------------------------------------------===//
270 CallInst::~CallInst() {
273 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
274 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
279 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
281 assert((Args.size() == FTy->getNumParams() ||
282 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
283 "Calling a function with bad signature!");
285 for (unsigned i = 0; i != Args.size(); ++i)
286 assert((i >= FTy->getNumParams() ||
287 FTy->getParamType(i) == Args[i]->getType()) &&
288 "Calling a function with a bad signature!");
291 std::copy(Args.begin(), Args.end(), op_begin());
295 void CallInst::init(Value *Func, const Twine &NameStr) {
296 assert(NumOperands == 1 && "NumOperands not set up?");
301 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
303 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
309 CallInst::CallInst(Value *Func, const Twine &Name,
310 Instruction *InsertBefore)
311 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
312 ->getElementType())->getReturnType(),
314 OperandTraits<CallInst>::op_end(this) - 1,
319 CallInst::CallInst(Value *Func, const Twine &Name,
320 BasicBlock *InsertAtEnd)
321 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
322 ->getElementType())->getReturnType(),
324 OperandTraits<CallInst>::op_end(this) - 1,
329 CallInst::CallInst(const CallInst &CI)
330 : Instruction(CI.getType(), Instruction::Call,
331 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
332 CI.getNumOperands()) {
333 setAttributes(CI.getAttributes());
334 setTailCall(CI.isTailCall());
335 setCallingConv(CI.getCallingConv());
337 std::copy(CI.op_begin(), CI.op_end(), op_begin());
338 SubclassOptionalData = CI.SubclassOptionalData;
341 void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
342 AttributeSet PAL = getAttributes();
343 PAL = PAL.addAttribute(getContext(), i, attr);
347 void CallInst::removeAttribute(unsigned i, Attribute attr) {
348 AttributeSet PAL = getAttributes();
350 LLVMContext &Context = getContext();
351 PAL = PAL.removeAttributes(Context, i,
352 AttributeSet::get(Context, i, B));
356 bool CallInst::hasFnAttr(Attribute::AttrKind A) const {
357 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
359 if (const Function *F = getCalledFunction())
360 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
364 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
365 if (AttributeList.hasAttribute(i, A))
367 if (const Function *F = getCalledFunction())
368 return F->getAttributes().hasAttribute(i, A);
372 /// IsConstantOne - Return true only if val is constant int 1
373 static bool IsConstantOne(Value *val) {
374 assert(val && "IsConstantOne does not work with NULL val");
375 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
378 static Instruction *createMalloc(Instruction *InsertBefore,
379 BasicBlock *InsertAtEnd, Type *IntPtrTy,
380 Type *AllocTy, Value *AllocSize,
381 Value *ArraySize, Function *MallocF,
383 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
384 "createMalloc needs either InsertBefore or InsertAtEnd");
386 // malloc(type) becomes:
387 // bitcast (i8* malloc(typeSize)) to type*
388 // malloc(type, arraySize) becomes:
389 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
391 ArraySize = ConstantInt::get(IntPtrTy, 1);
392 else if (ArraySize->getType() != IntPtrTy) {
394 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
397 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
401 if (!IsConstantOne(ArraySize)) {
402 if (IsConstantOne(AllocSize)) {
403 AllocSize = ArraySize; // Operand * 1 = Operand
404 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
405 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
407 // Malloc arg is constant product of type size and array size
408 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
410 // Multiply type size by the array size...
412 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
413 "mallocsize", InsertBefore);
415 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
416 "mallocsize", InsertAtEnd);
420 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
421 // Create the call to Malloc.
422 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
423 Module* M = BB->getParent()->getParent();
424 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
425 Value *MallocFunc = MallocF;
427 // prototype malloc as "void *malloc(size_t)"
428 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
429 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
430 CallInst *MCall = NULL;
431 Instruction *Result = NULL;
433 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
435 if (Result->getType() != AllocPtrType)
436 // Create a cast instruction to convert to the right type...
437 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
439 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
441 if (Result->getType() != AllocPtrType) {
442 InsertAtEnd->getInstList().push_back(MCall);
443 // Create a cast instruction to convert to the right type...
444 Result = new BitCastInst(MCall, AllocPtrType, Name);
447 MCall->setTailCall();
448 if (Function *F = dyn_cast<Function>(MallocFunc)) {
449 MCall->setCallingConv(F->getCallingConv());
450 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
452 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
457 /// CreateMalloc - Generate the IR for a call to malloc:
458 /// 1. Compute the malloc call's argument as the specified type's size,
459 /// possibly multiplied by the array size if the array size is not
461 /// 2. Call malloc with that argument.
462 /// 3. Bitcast the result of the malloc call to the specified type.
463 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
464 Type *IntPtrTy, Type *AllocTy,
465 Value *AllocSize, Value *ArraySize,
468 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
469 ArraySize, MallocF, Name);
472 /// CreateMalloc - Generate the IR for a call to malloc:
473 /// 1. Compute the malloc call's argument as the specified type's size,
474 /// possibly multiplied by the array size if the array size is not
476 /// 2. Call malloc with that argument.
477 /// 3. Bitcast the result of the malloc call to the specified type.
478 /// Note: This function does not add the bitcast to the basic block, that is the
479 /// responsibility of the caller.
480 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
481 Type *IntPtrTy, Type *AllocTy,
482 Value *AllocSize, Value *ArraySize,
483 Function *MallocF, const Twine &Name) {
484 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
485 ArraySize, MallocF, Name);
488 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
489 BasicBlock *InsertAtEnd) {
490 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
491 "createFree needs either InsertBefore or InsertAtEnd");
492 assert(Source->getType()->isPointerTy() &&
493 "Can not free something of nonpointer type!");
495 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
496 Module* M = BB->getParent()->getParent();
498 Type *VoidTy = Type::getVoidTy(M->getContext());
499 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
500 // prototype free as "void free(void*)"
501 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
502 CallInst* Result = NULL;
503 Value *PtrCast = Source;
505 if (Source->getType() != IntPtrTy)
506 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
507 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
509 if (Source->getType() != IntPtrTy)
510 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
511 Result = CallInst::Create(FreeFunc, PtrCast, "");
513 Result->setTailCall();
514 if (Function *F = dyn_cast<Function>(FreeFunc))
515 Result->setCallingConv(F->getCallingConv());
520 /// CreateFree - Generate the IR for a call to the builtin free function.
521 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
522 return createFree(Source, InsertBefore, NULL);
525 /// CreateFree - Generate the IR for a call to the builtin free function.
526 /// Note: This function does not add the call to the basic block, that is the
527 /// responsibility of the caller.
528 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
529 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
530 assert(FreeCall && "CreateFree did not create a CallInst");
534 //===----------------------------------------------------------------------===//
535 // InvokeInst Implementation
536 //===----------------------------------------------------------------------===//
538 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
539 ArrayRef<Value *> Args, const Twine &NameStr) {
540 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
543 Op<-1>() = IfException;
547 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
549 assert(((Args.size() == FTy->getNumParams()) ||
550 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
551 "Invoking a function with bad signature");
553 for (unsigned i = 0, e = Args.size(); i != e; i++)
554 assert((i >= FTy->getNumParams() ||
555 FTy->getParamType(i) == Args[i]->getType()) &&
556 "Invoking a function with a bad signature!");
559 std::copy(Args.begin(), Args.end(), op_begin());
563 InvokeInst::InvokeInst(const InvokeInst &II)
564 : TerminatorInst(II.getType(), Instruction::Invoke,
565 OperandTraits<InvokeInst>::op_end(this)
566 - II.getNumOperands(),
567 II.getNumOperands()) {
568 setAttributes(II.getAttributes());
569 setCallingConv(II.getCallingConv());
570 std::copy(II.op_begin(), II.op_end(), op_begin());
571 SubclassOptionalData = II.SubclassOptionalData;
574 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
575 return getSuccessor(idx);
577 unsigned InvokeInst::getNumSuccessorsV() const {
578 return getNumSuccessors();
580 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
581 return setSuccessor(idx, B);
584 bool InvokeInst::hasFnAttr(Attribute::AttrKind A) const {
585 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
587 if (const Function *F = getCalledFunction())
588 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
592 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
593 if (AttributeList.hasAttribute(i, A))
595 if (const Function *F = getCalledFunction())
596 return F->getAttributes().hasAttribute(i, A);
600 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
601 AttributeSet PAL = getAttributes();
602 PAL = PAL.addAttribute(getContext(), i, attr);
606 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
607 AttributeSet PAL = getAttributes();
609 PAL = PAL.removeAttributes(getContext(), i,
610 AttributeSet::get(getContext(), i, B));
614 LandingPadInst *InvokeInst::getLandingPadInst() const {
615 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
618 //===----------------------------------------------------------------------===//
619 // ReturnInst Implementation
620 //===----------------------------------------------------------------------===//
622 ReturnInst::ReturnInst(const ReturnInst &RI)
623 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
624 OperandTraits<ReturnInst>::op_end(this) -
626 RI.getNumOperands()) {
627 if (RI.getNumOperands())
628 Op<0>() = RI.Op<0>();
629 SubclassOptionalData = RI.SubclassOptionalData;
632 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
633 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
634 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
639 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
640 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
641 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
646 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
647 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
648 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
651 unsigned ReturnInst::getNumSuccessorsV() const {
652 return getNumSuccessors();
655 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
656 /// emit the vtable for the class in this translation unit.
657 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
658 llvm_unreachable("ReturnInst has no successors!");
661 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
662 llvm_unreachable("ReturnInst has no successors!");
665 ReturnInst::~ReturnInst() {
668 //===----------------------------------------------------------------------===//
669 // ResumeInst Implementation
670 //===----------------------------------------------------------------------===//
672 ResumeInst::ResumeInst(const ResumeInst &RI)
673 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
674 OperandTraits<ResumeInst>::op_begin(this), 1) {
675 Op<0>() = RI.Op<0>();
678 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
679 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
680 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
684 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
685 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
686 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
690 unsigned ResumeInst::getNumSuccessorsV() const {
691 return getNumSuccessors();
694 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
695 llvm_unreachable("ResumeInst has no successors!");
698 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
699 llvm_unreachable("ResumeInst has no successors!");
702 //===----------------------------------------------------------------------===//
703 // UnreachableInst Implementation
704 //===----------------------------------------------------------------------===//
706 UnreachableInst::UnreachableInst(LLVMContext &Context,
707 Instruction *InsertBefore)
708 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
709 0, 0, InsertBefore) {
711 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
712 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
716 unsigned UnreachableInst::getNumSuccessorsV() const {
717 return getNumSuccessors();
720 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
721 llvm_unreachable("UnreachableInst has no successors!");
724 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
725 llvm_unreachable("UnreachableInst has no successors!");
728 //===----------------------------------------------------------------------===//
729 // BranchInst Implementation
730 //===----------------------------------------------------------------------===//
732 void BranchInst::AssertOK() {
734 assert(getCondition()->getType()->isIntegerTy(1) &&
735 "May only branch on boolean predicates!");
738 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
739 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
740 OperandTraits<BranchInst>::op_end(this) - 1,
742 assert(IfTrue != 0 && "Branch destination may not be null!");
745 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
746 Instruction *InsertBefore)
747 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
748 OperandTraits<BranchInst>::op_end(this) - 3,
758 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
759 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
760 OperandTraits<BranchInst>::op_end(this) - 1,
762 assert(IfTrue != 0 && "Branch destination may not be null!");
766 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
767 BasicBlock *InsertAtEnd)
768 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
769 OperandTraits<BranchInst>::op_end(this) - 3,
780 BranchInst::BranchInst(const BranchInst &BI) :
781 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
782 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
783 BI.getNumOperands()) {
784 Op<-1>() = BI.Op<-1>();
785 if (BI.getNumOperands() != 1) {
786 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
787 Op<-3>() = BI.Op<-3>();
788 Op<-2>() = BI.Op<-2>();
790 SubclassOptionalData = BI.SubclassOptionalData;
793 void BranchInst::swapSuccessors() {
794 assert(isConditional() &&
795 "Cannot swap successors of an unconditional branch");
796 Op<-1>().swap(Op<-2>());
798 // Update profile metadata if present and it matches our structural
800 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
801 if (!ProfileData || ProfileData->getNumOperands() != 3)
804 // The first operand is the name. Fetch them backwards and build a new one.
806 ProfileData->getOperand(0),
807 ProfileData->getOperand(2),
808 ProfileData->getOperand(1)
810 setMetadata(LLVMContext::MD_prof,
811 MDNode::get(ProfileData->getContext(), Ops));
814 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
815 return getSuccessor(idx);
817 unsigned BranchInst::getNumSuccessorsV() const {
818 return getNumSuccessors();
820 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
821 setSuccessor(idx, B);
825 //===----------------------------------------------------------------------===//
826 // AllocaInst Implementation
827 //===----------------------------------------------------------------------===//
829 static Value *getAISize(LLVMContext &Context, Value *Amt) {
831 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
833 assert(!isa<BasicBlock>(Amt) &&
834 "Passed basic block into allocation size parameter! Use other ctor");
835 assert(Amt->getType()->isIntegerTy() &&
836 "Allocation array size is not an integer!");
841 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
842 const Twine &Name, Instruction *InsertBefore)
843 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
844 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
846 assert(!Ty->isVoidTy() && "Cannot allocate void!");
850 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
851 const Twine &Name, BasicBlock *InsertAtEnd)
852 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
853 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
855 assert(!Ty->isVoidTy() && "Cannot allocate void!");
859 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
860 Instruction *InsertBefore)
861 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
862 getAISize(Ty->getContext(), 0), InsertBefore) {
864 assert(!Ty->isVoidTy() && "Cannot allocate void!");
868 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
869 BasicBlock *InsertAtEnd)
870 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
871 getAISize(Ty->getContext(), 0), InsertAtEnd) {
873 assert(!Ty->isVoidTy() && "Cannot allocate void!");
877 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
878 const Twine &Name, Instruction *InsertBefore)
879 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
880 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
882 assert(!Ty->isVoidTy() && "Cannot allocate void!");
886 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
887 const Twine &Name, BasicBlock *InsertAtEnd)
888 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
889 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
891 assert(!Ty->isVoidTy() && "Cannot allocate void!");
895 // Out of line virtual method, so the vtable, etc has a home.
896 AllocaInst::~AllocaInst() {
899 void AllocaInst::setAlignment(unsigned Align) {
900 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
901 assert(Align <= MaximumAlignment &&
902 "Alignment is greater than MaximumAlignment!");
903 setInstructionSubclassData(Log2_32(Align) + 1);
904 assert(getAlignment() == Align && "Alignment representation error!");
907 bool AllocaInst::isArrayAllocation() const {
908 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
913 Type *AllocaInst::getAllocatedType() const {
914 return getType()->getElementType();
917 /// isStaticAlloca - Return true if this alloca is in the entry block of the
918 /// function and is a constant size. If so, the code generator will fold it
919 /// into the prolog/epilog code, so it is basically free.
920 bool AllocaInst::isStaticAlloca() const {
921 // Must be constant size.
922 if (!isa<ConstantInt>(getArraySize())) return false;
924 // Must be in the entry block.
925 const BasicBlock *Parent = getParent();
926 return Parent == &Parent->getParent()->front();
929 //===----------------------------------------------------------------------===//
930 // LoadInst Implementation
931 //===----------------------------------------------------------------------===//
933 void LoadInst::AssertOK() {
934 assert(getOperand(0)->getType()->isPointerTy() &&
935 "Ptr must have pointer type.");
936 assert(!(isAtomic() && getAlignment() == 0) &&
937 "Alignment required for atomic load");
940 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
941 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
942 Load, Ptr, InsertBef) {
945 setAtomic(NotAtomic);
950 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
951 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
952 Load, Ptr, InsertAE) {
955 setAtomic(NotAtomic);
960 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
961 Instruction *InsertBef)
962 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
963 Load, Ptr, InsertBef) {
964 setVolatile(isVolatile);
966 setAtomic(NotAtomic);
971 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
972 BasicBlock *InsertAE)
973 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
974 Load, Ptr, InsertAE) {
975 setVolatile(isVolatile);
977 setAtomic(NotAtomic);
982 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
983 unsigned Align, Instruction *InsertBef)
984 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
985 Load, Ptr, InsertBef) {
986 setVolatile(isVolatile);
988 setAtomic(NotAtomic);
993 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
994 unsigned Align, BasicBlock *InsertAE)
995 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
996 Load, Ptr, InsertAE) {
997 setVolatile(isVolatile);
999 setAtomic(NotAtomic);
1004 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1005 unsigned Align, AtomicOrdering Order,
1006 SynchronizationScope SynchScope,
1007 Instruction *InsertBef)
1008 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1009 Load, Ptr, InsertBef) {
1010 setVolatile(isVolatile);
1011 setAlignment(Align);
1012 setAtomic(Order, SynchScope);
1017 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1018 unsigned Align, AtomicOrdering Order,
1019 SynchronizationScope SynchScope,
1020 BasicBlock *InsertAE)
1021 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1022 Load, Ptr, InsertAE) {
1023 setVolatile(isVolatile);
1024 setAlignment(Align);
1025 setAtomic(Order, SynchScope);
1030 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1031 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1032 Load, Ptr, InsertBef) {
1035 setAtomic(NotAtomic);
1037 if (Name && Name[0]) setName(Name);
1040 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1041 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1042 Load, Ptr, InsertAE) {
1045 setAtomic(NotAtomic);
1047 if (Name && Name[0]) setName(Name);
1050 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1051 Instruction *InsertBef)
1052 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1053 Load, Ptr, InsertBef) {
1054 setVolatile(isVolatile);
1056 setAtomic(NotAtomic);
1058 if (Name && Name[0]) setName(Name);
1061 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1062 BasicBlock *InsertAE)
1063 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1064 Load, Ptr, InsertAE) {
1065 setVolatile(isVolatile);
1067 setAtomic(NotAtomic);
1069 if (Name && Name[0]) setName(Name);
1072 void LoadInst::setAlignment(unsigned Align) {
1073 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1074 assert(Align <= MaximumAlignment &&
1075 "Alignment is greater than MaximumAlignment!");
1076 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1077 ((Log2_32(Align)+1)<<1));
1078 assert(getAlignment() == Align && "Alignment representation error!");
1081 //===----------------------------------------------------------------------===//
1082 // StoreInst Implementation
1083 //===----------------------------------------------------------------------===//
1085 void StoreInst::AssertOK() {
1086 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1087 assert(getOperand(1)->getType()->isPointerTy() &&
1088 "Ptr must have pointer type!");
1089 assert(getOperand(0)->getType() ==
1090 cast<PointerType>(getOperand(1)->getType())->getElementType()
1091 && "Ptr must be a pointer to Val type!");
1092 assert(!(isAtomic() && getAlignment() == 0) &&
1093 "Alignment required for atomic load");
1097 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1098 : Instruction(Type::getVoidTy(val->getContext()), Store,
1099 OperandTraits<StoreInst>::op_begin(this),
1100 OperandTraits<StoreInst>::operands(this),
1106 setAtomic(NotAtomic);
1110 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1111 : Instruction(Type::getVoidTy(val->getContext()), Store,
1112 OperandTraits<StoreInst>::op_begin(this),
1113 OperandTraits<StoreInst>::operands(this),
1119 setAtomic(NotAtomic);
1123 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1124 Instruction *InsertBefore)
1125 : Instruction(Type::getVoidTy(val->getContext()), Store,
1126 OperandTraits<StoreInst>::op_begin(this),
1127 OperandTraits<StoreInst>::operands(this),
1131 setVolatile(isVolatile);
1133 setAtomic(NotAtomic);
1137 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1138 unsigned Align, Instruction *InsertBefore)
1139 : Instruction(Type::getVoidTy(val->getContext()), Store,
1140 OperandTraits<StoreInst>::op_begin(this),
1141 OperandTraits<StoreInst>::operands(this),
1145 setVolatile(isVolatile);
1146 setAlignment(Align);
1147 setAtomic(NotAtomic);
1151 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1152 unsigned Align, AtomicOrdering Order,
1153 SynchronizationScope SynchScope,
1154 Instruction *InsertBefore)
1155 : Instruction(Type::getVoidTy(val->getContext()), Store,
1156 OperandTraits<StoreInst>::op_begin(this),
1157 OperandTraits<StoreInst>::operands(this),
1161 setVolatile(isVolatile);
1162 setAlignment(Align);
1163 setAtomic(Order, SynchScope);
1167 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1168 BasicBlock *InsertAtEnd)
1169 : Instruction(Type::getVoidTy(val->getContext()), Store,
1170 OperandTraits<StoreInst>::op_begin(this),
1171 OperandTraits<StoreInst>::operands(this),
1175 setVolatile(isVolatile);
1177 setAtomic(NotAtomic);
1181 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1182 unsigned Align, BasicBlock *InsertAtEnd)
1183 : Instruction(Type::getVoidTy(val->getContext()), Store,
1184 OperandTraits<StoreInst>::op_begin(this),
1185 OperandTraits<StoreInst>::operands(this),
1189 setVolatile(isVolatile);
1190 setAlignment(Align);
1191 setAtomic(NotAtomic);
1195 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1196 unsigned Align, AtomicOrdering Order,
1197 SynchronizationScope SynchScope,
1198 BasicBlock *InsertAtEnd)
1199 : Instruction(Type::getVoidTy(val->getContext()), Store,
1200 OperandTraits<StoreInst>::op_begin(this),
1201 OperandTraits<StoreInst>::operands(this),
1205 setVolatile(isVolatile);
1206 setAlignment(Align);
1207 setAtomic(Order, SynchScope);
1211 void StoreInst::setAlignment(unsigned Align) {
1212 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1213 assert(Align <= MaximumAlignment &&
1214 "Alignment is greater than MaximumAlignment!");
1215 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1216 ((Log2_32(Align)+1) << 1));
1217 assert(getAlignment() == Align && "Alignment representation error!");
1220 //===----------------------------------------------------------------------===//
1221 // AtomicCmpXchgInst Implementation
1222 //===----------------------------------------------------------------------===//
1224 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1225 AtomicOrdering Ordering,
1226 SynchronizationScope SynchScope) {
1230 setOrdering(Ordering);
1231 setSynchScope(SynchScope);
1233 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1234 "All operands must be non-null!");
1235 assert(getOperand(0)->getType()->isPointerTy() &&
1236 "Ptr must have pointer type!");
1237 assert(getOperand(1)->getType() ==
1238 cast<PointerType>(getOperand(0)->getType())->getElementType()
1239 && "Ptr must be a pointer to Cmp type!");
1240 assert(getOperand(2)->getType() ==
1241 cast<PointerType>(getOperand(0)->getType())->getElementType()
1242 && "Ptr must be a pointer to NewVal type!");
1243 assert(Ordering != NotAtomic &&
1244 "AtomicCmpXchg instructions must be atomic!");
1247 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1248 AtomicOrdering Ordering,
1249 SynchronizationScope SynchScope,
1250 Instruction *InsertBefore)
1251 : Instruction(Cmp->getType(), AtomicCmpXchg,
1252 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1253 OperandTraits<AtomicCmpXchgInst>::operands(this),
1255 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1258 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1259 AtomicOrdering Ordering,
1260 SynchronizationScope SynchScope,
1261 BasicBlock *InsertAtEnd)
1262 : Instruction(Cmp->getType(), AtomicCmpXchg,
1263 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1264 OperandTraits<AtomicCmpXchgInst>::operands(this),
1266 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1269 //===----------------------------------------------------------------------===//
1270 // AtomicRMWInst Implementation
1271 //===----------------------------------------------------------------------===//
1273 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1274 AtomicOrdering Ordering,
1275 SynchronizationScope SynchScope) {
1278 setOperation(Operation);
1279 setOrdering(Ordering);
1280 setSynchScope(SynchScope);
1282 assert(getOperand(0) && getOperand(1) &&
1283 "All operands must be non-null!");
1284 assert(getOperand(0)->getType()->isPointerTy() &&
1285 "Ptr must have pointer type!");
1286 assert(getOperand(1)->getType() ==
1287 cast<PointerType>(getOperand(0)->getType())->getElementType()
1288 && "Ptr must be a pointer to Val type!");
1289 assert(Ordering != NotAtomic &&
1290 "AtomicRMW instructions must be atomic!");
1293 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1294 AtomicOrdering Ordering,
1295 SynchronizationScope SynchScope,
1296 Instruction *InsertBefore)
1297 : Instruction(Val->getType(), AtomicRMW,
1298 OperandTraits<AtomicRMWInst>::op_begin(this),
1299 OperandTraits<AtomicRMWInst>::operands(this),
1301 Init(Operation, Ptr, Val, Ordering, SynchScope);
1304 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1305 AtomicOrdering Ordering,
1306 SynchronizationScope SynchScope,
1307 BasicBlock *InsertAtEnd)
1308 : Instruction(Val->getType(), AtomicRMW,
1309 OperandTraits<AtomicRMWInst>::op_begin(this),
1310 OperandTraits<AtomicRMWInst>::operands(this),
1312 Init(Operation, Ptr, Val, Ordering, SynchScope);
1315 //===----------------------------------------------------------------------===//
1316 // FenceInst Implementation
1317 //===----------------------------------------------------------------------===//
1319 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1320 SynchronizationScope SynchScope,
1321 Instruction *InsertBefore)
1322 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1323 setOrdering(Ordering);
1324 setSynchScope(SynchScope);
1327 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1328 SynchronizationScope SynchScope,
1329 BasicBlock *InsertAtEnd)
1330 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1331 setOrdering(Ordering);
1332 setSynchScope(SynchScope);
1335 //===----------------------------------------------------------------------===//
1336 // GetElementPtrInst Implementation
1337 //===----------------------------------------------------------------------===//
1339 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1340 const Twine &Name) {
1341 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1342 OperandList[0] = Ptr;
1343 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1347 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1348 : Instruction(GEPI.getType(), GetElementPtr,
1349 OperandTraits<GetElementPtrInst>::op_end(this)
1350 - GEPI.getNumOperands(),
1351 GEPI.getNumOperands()) {
1352 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1353 SubclassOptionalData = GEPI.SubclassOptionalData;
1356 /// getIndexedType - Returns the type of the element that would be accessed with
1357 /// a gep instruction with the specified parameters.
1359 /// The Idxs pointer should point to a continuous piece of memory containing the
1360 /// indices, either as Value* or uint64_t.
1362 /// A null type is returned if the indices are invalid for the specified
1365 template <typename IndexTy>
1366 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1367 PointerType *PTy = dyn_cast<PointerType>(Ptr->getScalarType());
1368 if (!PTy) return 0; // Type isn't a pointer type!
1369 Type *Agg = PTy->getElementType();
1371 // Handle the special case of the empty set index set, which is always valid.
1372 if (IdxList.empty())
1375 // If there is at least one index, the top level type must be sized, otherwise
1376 // it cannot be 'stepped over'.
1377 if (!Agg->isSized())
1380 unsigned CurIdx = 1;
1381 for (; CurIdx != IdxList.size(); ++CurIdx) {
1382 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1383 if (!CT || CT->isPointerTy()) return 0;
1384 IndexTy Index = IdxList[CurIdx];
1385 if (!CT->indexValid(Index)) return 0;
1386 Agg = CT->getTypeAtIndex(Index);
1388 return CurIdx == IdxList.size() ? Agg : 0;
1391 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1392 return getIndexedTypeInternal(Ptr, IdxList);
1395 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1396 ArrayRef<Constant *> IdxList) {
1397 return getIndexedTypeInternal(Ptr, IdxList);
1400 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1401 return getIndexedTypeInternal(Ptr, IdxList);
1404 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1405 /// zeros. If so, the result pointer and the first operand have the same
1406 /// value, just potentially different types.
1407 bool GetElementPtrInst::hasAllZeroIndices() const {
1408 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1409 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1410 if (!CI->isZero()) return false;
1418 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1419 /// constant integers. If so, the result pointer and the first operand have
1420 /// a constant offset between them.
1421 bool GetElementPtrInst::hasAllConstantIndices() const {
1422 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1423 if (!isa<ConstantInt>(getOperand(i)))
1429 void GetElementPtrInst::setIsInBounds(bool B) {
1430 cast<GEPOperator>(this)->setIsInBounds(B);
1433 bool GetElementPtrInst::isInBounds() const {
1434 return cast<GEPOperator>(this)->isInBounds();
1437 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1438 APInt &Offset) const {
1439 // Delegate to the generic GEPOperator implementation.
1440 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1443 //===----------------------------------------------------------------------===//
1444 // ExtractElementInst Implementation
1445 //===----------------------------------------------------------------------===//
1447 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1449 Instruction *InsertBef)
1450 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1452 OperandTraits<ExtractElementInst>::op_begin(this),
1454 assert(isValidOperands(Val, Index) &&
1455 "Invalid extractelement instruction operands!");
1461 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1463 BasicBlock *InsertAE)
1464 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1466 OperandTraits<ExtractElementInst>::op_begin(this),
1468 assert(isValidOperands(Val, Index) &&
1469 "Invalid extractelement instruction operands!");
1477 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1478 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1484 //===----------------------------------------------------------------------===//
1485 // InsertElementInst Implementation
1486 //===----------------------------------------------------------------------===//
1488 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1490 Instruction *InsertBef)
1491 : Instruction(Vec->getType(), InsertElement,
1492 OperandTraits<InsertElementInst>::op_begin(this),
1494 assert(isValidOperands(Vec, Elt, Index) &&
1495 "Invalid insertelement instruction operands!");
1502 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1504 BasicBlock *InsertAE)
1505 : Instruction(Vec->getType(), InsertElement,
1506 OperandTraits<InsertElementInst>::op_begin(this),
1508 assert(isValidOperands(Vec, Elt, Index) &&
1509 "Invalid insertelement instruction operands!");
1517 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1518 const Value *Index) {
1519 if (!Vec->getType()->isVectorTy())
1520 return false; // First operand of insertelement must be vector type.
1522 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1523 return false;// Second operand of insertelement must be vector element type.
1525 if (!Index->getType()->isIntegerTy(32))
1526 return false; // Third operand of insertelement must be i32.
1531 //===----------------------------------------------------------------------===//
1532 // ShuffleVectorInst Implementation
1533 //===----------------------------------------------------------------------===//
1535 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1537 Instruction *InsertBefore)
1538 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1539 cast<VectorType>(Mask->getType())->getNumElements()),
1541 OperandTraits<ShuffleVectorInst>::op_begin(this),
1542 OperandTraits<ShuffleVectorInst>::operands(this),
1544 assert(isValidOperands(V1, V2, Mask) &&
1545 "Invalid shuffle vector instruction operands!");
1552 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1554 BasicBlock *InsertAtEnd)
1555 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1556 cast<VectorType>(Mask->getType())->getNumElements()),
1558 OperandTraits<ShuffleVectorInst>::op_begin(this),
1559 OperandTraits<ShuffleVectorInst>::operands(this),
1561 assert(isValidOperands(V1, V2, Mask) &&
1562 "Invalid shuffle vector instruction operands!");
1570 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1571 const Value *Mask) {
1572 // V1 and V2 must be vectors of the same type.
1573 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1576 // Mask must be vector of i32.
1577 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1578 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1581 // Check to see if Mask is valid.
1582 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1585 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1586 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1587 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1588 if (ConstantInt *CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1589 if (CI->uge(V1Size*2))
1591 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1598 if (const ConstantDataSequential *CDS =
1599 dyn_cast<ConstantDataSequential>(Mask)) {
1600 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1601 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1602 if (CDS->getElementAsInteger(i) >= V1Size*2)
1607 // The bitcode reader can create a place holder for a forward reference
1608 // used as the shuffle mask. When this occurs, the shuffle mask will
1609 // fall into this case and fail. To avoid this error, do this bit of
1610 // ugliness to allow such a mask pass.
1611 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1612 if (CE->getOpcode() == Instruction::UserOp1)
1618 /// getMaskValue - Return the index from the shuffle mask for the specified
1619 /// output result. This is either -1 if the element is undef or a number less
1620 /// than 2*numelements.
1621 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1622 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1623 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1624 return CDS->getElementAsInteger(i);
1625 Constant *C = Mask->getAggregateElement(i);
1626 if (isa<UndefValue>(C))
1628 return cast<ConstantInt>(C)->getZExtValue();
1631 /// getShuffleMask - Return the full mask for this instruction, where each
1632 /// element is the element number and undef's are returned as -1.
1633 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1634 SmallVectorImpl<int> &Result) {
1635 unsigned NumElts = Mask->getType()->getVectorNumElements();
1637 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1638 for (unsigned i = 0; i != NumElts; ++i)
1639 Result.push_back(CDS->getElementAsInteger(i));
1642 for (unsigned i = 0; i != NumElts; ++i) {
1643 Constant *C = Mask->getAggregateElement(i);
1644 Result.push_back(isa<UndefValue>(C) ? -1 :
1645 cast<ConstantInt>(C)->getZExtValue());
1650 //===----------------------------------------------------------------------===//
1651 // InsertValueInst Class
1652 //===----------------------------------------------------------------------===//
1654 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1655 const Twine &Name) {
1656 assert(NumOperands == 2 && "NumOperands not initialized?");
1658 // There's no fundamental reason why we require at least one index
1659 // (other than weirdness with &*IdxBegin being invalid; see
1660 // getelementptr's init routine for example). But there's no
1661 // present need to support it.
1662 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1664 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1665 Val->getType() && "Inserted value must match indexed type!");
1669 Indices.append(Idxs.begin(), Idxs.end());
1673 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1674 : Instruction(IVI.getType(), InsertValue,
1675 OperandTraits<InsertValueInst>::op_begin(this), 2),
1676 Indices(IVI.Indices) {
1677 Op<0>() = IVI.getOperand(0);
1678 Op<1>() = IVI.getOperand(1);
1679 SubclassOptionalData = IVI.SubclassOptionalData;
1682 //===----------------------------------------------------------------------===//
1683 // ExtractValueInst Class
1684 //===----------------------------------------------------------------------===//
1686 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1687 assert(NumOperands == 1 && "NumOperands not initialized?");
1689 // There's no fundamental reason why we require at least one index.
1690 // But there's no present need to support it.
1691 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1693 Indices.append(Idxs.begin(), Idxs.end());
1697 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1698 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1699 Indices(EVI.Indices) {
1700 SubclassOptionalData = EVI.SubclassOptionalData;
1703 // getIndexedType - Returns the type of the element that would be extracted
1704 // with an extractvalue instruction with the specified parameters.
1706 // A null type is returned if the indices are invalid for the specified
1709 Type *ExtractValueInst::getIndexedType(Type *Agg,
1710 ArrayRef<unsigned> Idxs) {
1711 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1712 unsigned Index = Idxs[CurIdx];
1713 // We can't use CompositeType::indexValid(Index) here.
1714 // indexValid() always returns true for arrays because getelementptr allows
1715 // out-of-bounds indices. Since we don't allow those for extractvalue and
1716 // insertvalue we need to check array indexing manually.
1717 // Since the only other types we can index into are struct types it's just
1718 // as easy to check those manually as well.
1719 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1720 if (Index >= AT->getNumElements())
1722 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1723 if (Index >= ST->getNumElements())
1726 // Not a valid type to index into.
1730 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1732 return const_cast<Type*>(Agg);
1735 //===----------------------------------------------------------------------===//
1736 // BinaryOperator Class
1737 //===----------------------------------------------------------------------===//
1739 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1740 Type *Ty, const Twine &Name,
1741 Instruction *InsertBefore)
1742 : Instruction(Ty, iType,
1743 OperandTraits<BinaryOperator>::op_begin(this),
1744 OperandTraits<BinaryOperator>::operands(this),
1752 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1753 Type *Ty, const Twine &Name,
1754 BasicBlock *InsertAtEnd)
1755 : Instruction(Ty, iType,
1756 OperandTraits<BinaryOperator>::op_begin(this),
1757 OperandTraits<BinaryOperator>::operands(this),
1766 void BinaryOperator::init(BinaryOps iType) {
1767 Value *LHS = getOperand(0), *RHS = getOperand(1);
1768 (void)LHS; (void)RHS; // Silence warnings.
1769 assert(LHS->getType() == RHS->getType() &&
1770 "Binary operator operand types must match!");
1775 assert(getType() == LHS->getType() &&
1776 "Arithmetic operation should return same type as operands!");
1777 assert(getType()->isIntOrIntVectorTy() &&
1778 "Tried to create an integer operation on a non-integer type!");
1780 case FAdd: case FSub:
1782 assert(getType() == LHS->getType() &&
1783 "Arithmetic operation should return same type as operands!");
1784 assert(getType()->isFPOrFPVectorTy() &&
1785 "Tried to create a floating-point operation on a "
1786 "non-floating-point type!");
1790 assert(getType() == LHS->getType() &&
1791 "Arithmetic operation should return same type as operands!");
1792 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1793 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1794 "Incorrect operand type (not integer) for S/UDIV");
1797 assert(getType() == LHS->getType() &&
1798 "Arithmetic operation should return same type as operands!");
1799 assert(getType()->isFPOrFPVectorTy() &&
1800 "Incorrect operand type (not floating point) for FDIV");
1804 assert(getType() == LHS->getType() &&
1805 "Arithmetic operation should return same type as operands!");
1806 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1807 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1808 "Incorrect operand type (not integer) for S/UREM");
1811 assert(getType() == LHS->getType() &&
1812 "Arithmetic operation should return same type as operands!");
1813 assert(getType()->isFPOrFPVectorTy() &&
1814 "Incorrect operand type (not floating point) for FREM");
1819 assert(getType() == LHS->getType() &&
1820 "Shift operation should return same type as operands!");
1821 assert((getType()->isIntegerTy() ||
1822 (getType()->isVectorTy() &&
1823 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1824 "Tried to create a shift operation on a non-integral type!");
1828 assert(getType() == LHS->getType() &&
1829 "Logical operation should return same type as operands!");
1830 assert((getType()->isIntegerTy() ||
1831 (getType()->isVectorTy() &&
1832 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1833 "Tried to create a logical operation on a non-integral type!");
1841 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1843 Instruction *InsertBefore) {
1844 assert(S1->getType() == S2->getType() &&
1845 "Cannot create binary operator with two operands of differing type!");
1846 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1849 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1851 BasicBlock *InsertAtEnd) {
1852 BinaryOperator *Res = Create(Op, S1, S2, Name);
1853 InsertAtEnd->getInstList().push_back(Res);
1857 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1858 Instruction *InsertBefore) {
1859 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1860 return new BinaryOperator(Instruction::Sub,
1862 Op->getType(), Name, InsertBefore);
1865 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1866 BasicBlock *InsertAtEnd) {
1867 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1868 return new BinaryOperator(Instruction::Sub,
1870 Op->getType(), Name, InsertAtEnd);
1873 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1874 Instruction *InsertBefore) {
1875 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1876 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1879 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1880 BasicBlock *InsertAtEnd) {
1881 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1882 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1885 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1886 Instruction *InsertBefore) {
1887 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1888 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1891 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1892 BasicBlock *InsertAtEnd) {
1893 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1894 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1897 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1898 Instruction *InsertBefore) {
1899 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1900 return new BinaryOperator(Instruction::FSub, zero, Op,
1901 Op->getType(), Name, InsertBefore);
1904 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1905 BasicBlock *InsertAtEnd) {
1906 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1907 return new BinaryOperator(Instruction::FSub, zero, Op,
1908 Op->getType(), Name, InsertAtEnd);
1911 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1912 Instruction *InsertBefore) {
1913 Constant *C = Constant::getAllOnesValue(Op->getType());
1914 return new BinaryOperator(Instruction::Xor, Op, C,
1915 Op->getType(), Name, InsertBefore);
1918 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1919 BasicBlock *InsertAtEnd) {
1920 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
1921 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1922 Op->getType(), Name, InsertAtEnd);
1926 // isConstantAllOnes - Helper function for several functions below
1927 static inline bool isConstantAllOnes(const Value *V) {
1928 if (const Constant *C = dyn_cast<Constant>(V))
1929 return C->isAllOnesValue();
1933 bool BinaryOperator::isNeg(const Value *V) {
1934 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1935 if (Bop->getOpcode() == Instruction::Sub)
1936 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1937 return C->isNegativeZeroValue();
1941 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
1942 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1943 if (Bop->getOpcode() == Instruction::FSub)
1944 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
1945 if (!IgnoreZeroSign)
1946 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
1947 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
1952 bool BinaryOperator::isNot(const Value *V) {
1953 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1954 return (Bop->getOpcode() == Instruction::Xor &&
1955 (isConstantAllOnes(Bop->getOperand(1)) ||
1956 isConstantAllOnes(Bop->getOperand(0))));
1960 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1961 return cast<BinaryOperator>(BinOp)->getOperand(1);
1964 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1965 return getNegArgument(const_cast<Value*>(BinOp));
1968 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1969 return cast<BinaryOperator>(BinOp)->getOperand(1);
1972 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1973 return getFNegArgument(const_cast<Value*>(BinOp));
1976 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1977 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1978 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1979 Value *Op0 = BO->getOperand(0);
1980 Value *Op1 = BO->getOperand(1);
1981 if (isConstantAllOnes(Op0)) return Op1;
1983 assert(isConstantAllOnes(Op1));
1987 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1988 return getNotArgument(const_cast<Value*>(BinOp));
1992 // swapOperands - Exchange the two operands to this instruction. This
1993 // instruction is safe to use on any binary instruction and does not
1994 // modify the semantics of the instruction. If the instruction is
1995 // order dependent (SetLT f.e.) the opcode is changed.
1997 bool BinaryOperator::swapOperands() {
1998 if (!isCommutative())
1999 return true; // Can't commute operands
2000 Op<0>().swap(Op<1>());
2004 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2005 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2008 void BinaryOperator::setHasNoSignedWrap(bool b) {
2009 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2012 void BinaryOperator::setIsExact(bool b) {
2013 cast<PossiblyExactOperator>(this)->setIsExact(b);
2016 bool BinaryOperator::hasNoUnsignedWrap() const {
2017 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2020 bool BinaryOperator::hasNoSignedWrap() const {
2021 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2024 bool BinaryOperator::isExact() const {
2025 return cast<PossiblyExactOperator>(this)->isExact();
2028 //===----------------------------------------------------------------------===//
2029 // FPMathOperator Class
2030 //===----------------------------------------------------------------------===//
2032 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2033 /// An accuracy of 0.0 means that the operation should be performed with the
2034 /// default precision.
2035 float FPMathOperator::getFPAccuracy() const {
2037 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2040 ConstantFP *Accuracy = cast<ConstantFP>(MD->getOperand(0));
2041 return Accuracy->getValueAPF().convertToFloat();
2045 //===----------------------------------------------------------------------===//
2047 //===----------------------------------------------------------------------===//
2049 void CastInst::anchor() {}
2051 // Just determine if this cast only deals with integral->integral conversion.
2052 bool CastInst::isIntegerCast() const {
2053 switch (getOpcode()) {
2054 default: return false;
2055 case Instruction::ZExt:
2056 case Instruction::SExt:
2057 case Instruction::Trunc:
2059 case Instruction::BitCast:
2060 return getOperand(0)->getType()->isIntegerTy() &&
2061 getType()->isIntegerTy();
2065 bool CastInst::isLosslessCast() const {
2066 // Only BitCast can be lossless, exit fast if we're not BitCast
2067 if (getOpcode() != Instruction::BitCast)
2070 // Identity cast is always lossless
2071 Type* SrcTy = getOperand(0)->getType();
2072 Type* DstTy = getType();
2076 // Pointer to pointer is always lossless.
2077 if (SrcTy->isPointerTy())
2078 return DstTy->isPointerTy();
2079 return false; // Other types have no identity values
2082 /// This function determines if the CastInst does not require any bits to be
2083 /// changed in order to effect the cast. Essentially, it identifies cases where
2084 /// no code gen is necessary for the cast, hence the name no-op cast. For
2085 /// example, the following are all no-op casts:
2086 /// # bitcast i32* %x to i8*
2087 /// # bitcast <2 x i32> %x to <4 x i16>
2088 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2089 /// @brief Determine if the described cast is a no-op.
2090 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2095 default: llvm_unreachable("Invalid CastOp");
2096 case Instruction::Trunc:
2097 case Instruction::ZExt:
2098 case Instruction::SExt:
2099 case Instruction::FPTrunc:
2100 case Instruction::FPExt:
2101 case Instruction::UIToFP:
2102 case Instruction::SIToFP:
2103 case Instruction::FPToUI:
2104 case Instruction::FPToSI:
2105 return false; // These always modify bits
2106 case Instruction::BitCast:
2107 return true; // BitCast never modifies bits.
2108 case Instruction::PtrToInt:
2109 return IntPtrTy->getScalarSizeInBits() ==
2110 DestTy->getScalarSizeInBits();
2111 case Instruction::IntToPtr:
2112 return IntPtrTy->getScalarSizeInBits() ==
2113 SrcTy->getScalarSizeInBits();
2117 /// @brief Determine if a cast is a no-op.
2118 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2119 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2122 /// This function determines if a pair of casts can be eliminated and what
2123 /// opcode should be used in the elimination. This assumes that there are two
2124 /// instructions like this:
2125 /// * %F = firstOpcode SrcTy %x to MidTy
2126 /// * %S = secondOpcode MidTy %F to DstTy
2127 /// The function returns a resultOpcode so these two casts can be replaced with:
2128 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2129 /// If no such cast is permited, the function returns 0.
2130 unsigned CastInst::isEliminableCastPair(
2131 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2132 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2133 Type *DstIntPtrTy) {
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
2236 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2238 unsigned PtrSize = SrcIntPtrTy->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 = MidIntPtrTy->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()->isPtrOrPtrVectorTy() && "Invalid cast");
2402 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2405 if (Ty->isIntOrIntVectorTy())
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();
2640 // If this is a cast to the same type then it's trivially true.
2644 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2645 SrcTy->isAggregateType() || DstTy->isAggregateType())
2648 // Get the size of the types in bits, we'll need this later
2649 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2650 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2652 // If these are vector types, get the lengths of the vectors (using zero for
2653 // scalar types means that checking that vector lengths match also checks that
2654 // scalars are not being converted to vectors or vectors to scalars).
2655 unsigned SrcLength = SrcTy->isVectorTy() ?
2656 cast<VectorType>(SrcTy)->getNumElements() : 0;
2657 unsigned DstLength = DstTy->isVectorTy() ?
2658 cast<VectorType>(DstTy)->getNumElements() : 0;
2660 // Switch on the opcode provided
2662 default: return false; // This is an input error
2663 case Instruction::Trunc:
2664 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2665 SrcLength == DstLength && SrcBitSize > DstBitSize;
2666 case Instruction::ZExt:
2667 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2668 SrcLength == DstLength && SrcBitSize < DstBitSize;
2669 case Instruction::SExt:
2670 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2671 SrcLength == DstLength && SrcBitSize < DstBitSize;
2672 case Instruction::FPTrunc:
2673 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2674 SrcLength == DstLength && SrcBitSize > DstBitSize;
2675 case Instruction::FPExt:
2676 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2677 SrcLength == DstLength && SrcBitSize < DstBitSize;
2678 case Instruction::UIToFP:
2679 case Instruction::SIToFP:
2680 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2681 SrcLength == DstLength;
2682 case Instruction::FPToUI:
2683 case Instruction::FPToSI:
2684 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2685 SrcLength == DstLength;
2686 case Instruction::PtrToInt:
2687 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2689 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2690 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2692 return SrcTy->getScalarType()->isPointerTy() &&
2693 DstTy->getScalarType()->isIntegerTy();
2694 case Instruction::IntToPtr:
2695 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2697 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2698 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2700 return SrcTy->getScalarType()->isIntegerTy() &&
2701 DstTy->getScalarType()->isPointerTy();
2702 case Instruction::BitCast:
2703 // BitCast implies a no-op cast of type only. No bits change.
2704 // However, you can't cast pointers to anything but pointers.
2705 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2708 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2709 // these cases, the cast is okay if the source and destination bit widths
2711 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2715 TruncInst::TruncInst(
2716 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2717 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2718 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2721 TruncInst::TruncInst(
2722 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2723 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2724 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2728 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2729 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2730 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2734 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2735 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2736 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2739 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2740 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2741 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2745 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2746 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2747 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2750 FPTruncInst::FPTruncInst(
2751 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2752 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2753 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2756 FPTruncInst::FPTruncInst(
2757 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2758 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2759 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2762 FPExtInst::FPExtInst(
2763 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2764 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2765 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2768 FPExtInst::FPExtInst(
2769 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2770 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2771 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2774 UIToFPInst::UIToFPInst(
2775 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2776 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2777 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2780 UIToFPInst::UIToFPInst(
2781 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2782 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2783 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2786 SIToFPInst::SIToFPInst(
2787 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2788 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2789 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2792 SIToFPInst::SIToFPInst(
2793 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2794 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2795 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2798 FPToUIInst::FPToUIInst(
2799 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2800 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2801 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2804 FPToUIInst::FPToUIInst(
2805 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2806 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2807 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2810 FPToSIInst::FPToSIInst(
2811 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2812 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2813 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2816 FPToSIInst::FPToSIInst(
2817 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2818 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2819 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2822 PtrToIntInst::PtrToIntInst(
2823 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2824 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2825 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2828 PtrToIntInst::PtrToIntInst(
2829 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2830 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2831 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2834 IntToPtrInst::IntToPtrInst(
2835 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2836 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2837 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2840 IntToPtrInst::IntToPtrInst(
2841 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2842 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2843 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2846 BitCastInst::BitCastInst(
2847 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2848 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2849 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2852 BitCastInst::BitCastInst(
2853 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2854 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2855 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2858 //===----------------------------------------------------------------------===//
2860 //===----------------------------------------------------------------------===//
2862 void CmpInst::anchor() {}
2864 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2865 Value *LHS, Value *RHS, const Twine &Name,
2866 Instruction *InsertBefore)
2867 : Instruction(ty, op,
2868 OperandTraits<CmpInst>::op_begin(this),
2869 OperandTraits<CmpInst>::operands(this),
2873 setPredicate((Predicate)predicate);
2877 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2878 Value *LHS, Value *RHS, const Twine &Name,
2879 BasicBlock *InsertAtEnd)
2880 : Instruction(ty, op,
2881 OperandTraits<CmpInst>::op_begin(this),
2882 OperandTraits<CmpInst>::operands(this),
2886 setPredicate((Predicate)predicate);
2891 CmpInst::Create(OtherOps Op, unsigned short predicate,
2892 Value *S1, Value *S2,
2893 const Twine &Name, Instruction *InsertBefore) {
2894 if (Op == Instruction::ICmp) {
2896 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2899 return new ICmpInst(CmpInst::Predicate(predicate),
2904 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2907 return new FCmpInst(CmpInst::Predicate(predicate),
2912 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2913 const Twine &Name, BasicBlock *InsertAtEnd) {
2914 if (Op == Instruction::ICmp) {
2915 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2918 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2922 void CmpInst::swapOperands() {
2923 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2926 cast<FCmpInst>(this)->swapOperands();
2929 bool CmpInst::isCommutative() const {
2930 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2931 return IC->isCommutative();
2932 return cast<FCmpInst>(this)->isCommutative();
2935 bool CmpInst::isEquality() const {
2936 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2937 return IC->isEquality();
2938 return cast<FCmpInst>(this)->isEquality();
2942 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2944 default: llvm_unreachable("Unknown cmp predicate!");
2945 case ICMP_EQ: return ICMP_NE;
2946 case ICMP_NE: return ICMP_EQ;
2947 case ICMP_UGT: return ICMP_ULE;
2948 case ICMP_ULT: return ICMP_UGE;
2949 case ICMP_UGE: return ICMP_ULT;
2950 case ICMP_ULE: return ICMP_UGT;
2951 case ICMP_SGT: return ICMP_SLE;
2952 case ICMP_SLT: return ICMP_SGE;
2953 case ICMP_SGE: return ICMP_SLT;
2954 case ICMP_SLE: return ICMP_SGT;
2956 case FCMP_OEQ: return FCMP_UNE;
2957 case FCMP_ONE: return FCMP_UEQ;
2958 case FCMP_OGT: return FCMP_ULE;
2959 case FCMP_OLT: return FCMP_UGE;
2960 case FCMP_OGE: return FCMP_ULT;
2961 case FCMP_OLE: return FCMP_UGT;
2962 case FCMP_UEQ: return FCMP_ONE;
2963 case FCMP_UNE: return FCMP_OEQ;
2964 case FCMP_UGT: return FCMP_OLE;
2965 case FCMP_ULT: return FCMP_OGE;
2966 case FCMP_UGE: return FCMP_OLT;
2967 case FCMP_ULE: return FCMP_OGT;
2968 case FCMP_ORD: return FCMP_UNO;
2969 case FCMP_UNO: return FCMP_ORD;
2970 case FCMP_TRUE: return FCMP_FALSE;
2971 case FCMP_FALSE: return FCMP_TRUE;
2975 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2977 default: llvm_unreachable("Unknown icmp predicate!");
2978 case ICMP_EQ: case ICMP_NE:
2979 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2981 case ICMP_UGT: return ICMP_SGT;
2982 case ICMP_ULT: return ICMP_SLT;
2983 case ICMP_UGE: return ICMP_SGE;
2984 case ICMP_ULE: return ICMP_SLE;
2988 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2990 default: llvm_unreachable("Unknown icmp predicate!");
2991 case ICMP_EQ: case ICMP_NE:
2992 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2994 case ICMP_SGT: return ICMP_UGT;
2995 case ICMP_SLT: return ICMP_ULT;
2996 case ICMP_SGE: return ICMP_UGE;
2997 case ICMP_SLE: return ICMP_ULE;
3001 /// Initialize a set of values that all satisfy the condition with C.
3004 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3007 uint32_t BitWidth = C.getBitWidth();
3009 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3010 case ICmpInst::ICMP_EQ: ++Upper; break;
3011 case ICmpInst::ICMP_NE: ++Lower; break;
3012 case ICmpInst::ICMP_ULT:
3013 Lower = APInt::getMinValue(BitWidth);
3014 // Check for an empty-set condition.
3016 return ConstantRange(BitWidth, /*isFullSet=*/false);
3018 case ICmpInst::ICMP_SLT:
3019 Lower = APInt::getSignedMinValue(BitWidth);
3020 // Check for an empty-set condition.
3022 return ConstantRange(BitWidth, /*isFullSet=*/false);
3024 case ICmpInst::ICMP_UGT:
3025 ++Lower; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3026 // Check for an empty-set condition.
3028 return ConstantRange(BitWidth, /*isFullSet=*/false);
3030 case ICmpInst::ICMP_SGT:
3031 ++Lower; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3032 // Check for an empty-set condition.
3034 return ConstantRange(BitWidth, /*isFullSet=*/false);
3036 case ICmpInst::ICMP_ULE:
3037 Lower = APInt::getMinValue(BitWidth); ++Upper;
3038 // Check for a full-set condition.
3040 return ConstantRange(BitWidth, /*isFullSet=*/true);
3042 case ICmpInst::ICMP_SLE:
3043 Lower = APInt::getSignedMinValue(BitWidth); ++Upper;
3044 // Check for a full-set condition.
3046 return ConstantRange(BitWidth, /*isFullSet=*/true);
3048 case ICmpInst::ICMP_UGE:
3049 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3050 // Check for a full-set condition.
3052 return ConstantRange(BitWidth, /*isFullSet=*/true);
3054 case ICmpInst::ICMP_SGE:
3055 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3056 // Check for a full-set condition.
3058 return ConstantRange(BitWidth, /*isFullSet=*/true);
3061 return ConstantRange(Lower, Upper);
3064 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3066 default: llvm_unreachable("Unknown cmp predicate!");
3067 case ICMP_EQ: case ICMP_NE:
3069 case ICMP_SGT: return ICMP_SLT;
3070 case ICMP_SLT: return ICMP_SGT;
3071 case ICMP_SGE: return ICMP_SLE;
3072 case ICMP_SLE: return ICMP_SGE;
3073 case ICMP_UGT: return ICMP_ULT;
3074 case ICMP_ULT: return ICMP_UGT;
3075 case ICMP_UGE: return ICMP_ULE;
3076 case ICMP_ULE: return ICMP_UGE;
3078 case FCMP_FALSE: case FCMP_TRUE:
3079 case FCMP_OEQ: case FCMP_ONE:
3080 case FCMP_UEQ: case FCMP_UNE:
3081 case FCMP_ORD: case FCMP_UNO:
3083 case FCMP_OGT: return FCMP_OLT;
3084 case FCMP_OLT: return FCMP_OGT;
3085 case FCMP_OGE: return FCMP_OLE;
3086 case FCMP_OLE: return FCMP_OGE;
3087 case FCMP_UGT: return FCMP_ULT;
3088 case FCMP_ULT: return FCMP_UGT;
3089 case FCMP_UGE: return FCMP_ULE;
3090 case FCMP_ULE: return FCMP_UGE;
3094 bool CmpInst::isUnsigned(unsigned short predicate) {
3095 switch (predicate) {
3096 default: return false;
3097 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3098 case ICmpInst::ICMP_UGE: return true;
3102 bool CmpInst::isSigned(unsigned short predicate) {
3103 switch (predicate) {
3104 default: return false;
3105 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3106 case ICmpInst::ICMP_SGE: return true;
3110 bool CmpInst::isOrdered(unsigned short predicate) {
3111 switch (predicate) {
3112 default: return false;
3113 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3114 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3115 case FCmpInst::FCMP_ORD: return true;
3119 bool CmpInst::isUnordered(unsigned short predicate) {
3120 switch (predicate) {
3121 default: return false;
3122 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3123 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3124 case FCmpInst::FCMP_UNO: return true;
3128 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3130 default: return false;
3131 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3132 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3136 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3138 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3139 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3140 default: return false;
3145 //===----------------------------------------------------------------------===//
3146 // SwitchInst Implementation
3147 //===----------------------------------------------------------------------===//
3149 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3150 assert(Value && Default && NumReserved);
3151 ReservedSpace = NumReserved;
3153 OperandList = allocHungoffUses(ReservedSpace);
3155 OperandList[0] = Value;
3156 OperandList[1] = Default;
3159 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3160 /// switch on and a default destination. The number of additional cases can
3161 /// be specified here to make memory allocation more efficient. This
3162 /// constructor can also autoinsert before another instruction.
3163 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3164 Instruction *InsertBefore)
3165 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3166 0, 0, InsertBefore) {
3167 init(Value, Default, 2+NumCases*2);
3170 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3171 /// switch on and a default destination. The number of additional cases can
3172 /// be specified here to make memory allocation more efficient. This
3173 /// constructor also autoinserts at the end of the specified BasicBlock.
3174 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3175 BasicBlock *InsertAtEnd)
3176 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3177 0, 0, InsertAtEnd) {
3178 init(Value, Default, 2+NumCases*2);
3181 SwitchInst::SwitchInst(const SwitchInst &SI)
3182 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3183 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3184 NumOperands = SI.getNumOperands();
3185 Use *OL = OperandList, *InOL = SI.OperandList;
3186 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3188 OL[i+1] = InOL[i+1];
3190 TheSubsets = SI.TheSubsets;
3191 SubclassOptionalData = SI.SubclassOptionalData;
3194 SwitchInst::~SwitchInst() {
3199 /// addCase - Add an entry to the switch instruction...
3201 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3202 IntegersSubsetToBB Mapping;
3204 // FIXME: Currently we work with ConstantInt based cases.
3205 // So inititalize IntItem container directly from ConstantInt.
3206 Mapping.add(IntItem::fromConstantInt(OnVal));
3207 IntegersSubset CaseRanges = Mapping.getCase();
3208 addCase(CaseRanges, Dest);
3211 void SwitchInst::addCase(IntegersSubset& OnVal, BasicBlock *Dest) {
3212 unsigned NewCaseIdx = getNumCases();
3213 unsigned OpNo = NumOperands;
3214 if (OpNo+2 > ReservedSpace)
3215 growOperands(); // Get more space!
3216 // Initialize some new operands.
3217 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3218 NumOperands = OpNo+2;
3220 SubsetsIt TheSubsetsIt = TheSubsets.insert(TheSubsets.end(), OnVal);
3222 CaseIt Case(this, NewCaseIdx, TheSubsetsIt);
3223 Case.updateCaseValueOperand(OnVal);
3224 Case.setSuccessor(Dest);
3227 /// removeCase - This method removes the specified case and its successor
3228 /// from the switch instruction.
3229 void SwitchInst::removeCase(CaseIt& i) {
3230 unsigned idx = i.getCaseIndex();
3232 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3234 unsigned NumOps = getNumOperands();
3235 Use *OL = OperandList;
3237 // Overwrite this case with the end of the list.
3238 if (2 + (idx + 1) * 2 != NumOps) {
3239 OL[2 + idx * 2] = OL[NumOps - 2];
3240 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3243 // Nuke the last value.
3244 OL[NumOps-2].set(0);
3245 OL[NumOps-2+1].set(0);
3247 // Do the same with TheCases collection:
3248 if (i.SubsetIt != --TheSubsets.end()) {
3249 *i.SubsetIt = TheSubsets.back();
3250 TheSubsets.pop_back();
3252 TheSubsets.pop_back();
3253 i.SubsetIt = TheSubsets.end();
3256 NumOperands = NumOps-2;
3259 /// growOperands - grow operands - This grows the operand list in response
3260 /// to a push_back style of operation. This grows the number of ops by 3 times.
3262 void SwitchInst::growOperands() {
3263 unsigned e = getNumOperands();
3264 unsigned NumOps = e*3;
3266 ReservedSpace = NumOps;
3267 Use *NewOps = allocHungoffUses(NumOps);
3268 Use *OldOps = OperandList;
3269 for (unsigned i = 0; i != e; ++i) {
3270 NewOps[i] = OldOps[i];
3272 OperandList = NewOps;
3273 Use::zap(OldOps, OldOps + e, true);
3277 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3278 return getSuccessor(idx);
3280 unsigned SwitchInst::getNumSuccessorsV() const {
3281 return getNumSuccessors();
3283 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3284 setSuccessor(idx, B);
3287 //===----------------------------------------------------------------------===//
3288 // IndirectBrInst Implementation
3289 //===----------------------------------------------------------------------===//
3291 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3292 assert(Address && Address->getType()->isPointerTy() &&
3293 "Address of indirectbr must be a pointer");
3294 ReservedSpace = 1+NumDests;
3296 OperandList = allocHungoffUses(ReservedSpace);
3298 OperandList[0] = Address;
3302 /// growOperands - grow operands - This grows the operand list in response
3303 /// to a push_back style of operation. This grows the number of ops by 2 times.
3305 void IndirectBrInst::growOperands() {
3306 unsigned e = getNumOperands();
3307 unsigned NumOps = e*2;
3309 ReservedSpace = NumOps;
3310 Use *NewOps = allocHungoffUses(NumOps);
3311 Use *OldOps = OperandList;
3312 for (unsigned i = 0; i != e; ++i)
3313 NewOps[i] = OldOps[i];
3314 OperandList = NewOps;
3315 Use::zap(OldOps, OldOps + e, true);
3318 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3319 Instruction *InsertBefore)
3320 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3321 0, 0, InsertBefore) {
3322 init(Address, NumCases);
3325 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3326 BasicBlock *InsertAtEnd)
3327 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3328 0, 0, InsertAtEnd) {
3329 init(Address, NumCases);
3332 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3333 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3334 allocHungoffUses(IBI.getNumOperands()),
3335 IBI.getNumOperands()) {
3336 Use *OL = OperandList, *InOL = IBI.OperandList;
3337 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3339 SubclassOptionalData = IBI.SubclassOptionalData;
3342 IndirectBrInst::~IndirectBrInst() {
3346 /// addDestination - Add a destination.
3348 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3349 unsigned OpNo = NumOperands;
3350 if (OpNo+1 > ReservedSpace)
3351 growOperands(); // Get more space!
3352 // Initialize some new operands.
3353 assert(OpNo < ReservedSpace && "Growing didn't work!");
3354 NumOperands = OpNo+1;
3355 OperandList[OpNo] = DestBB;
3358 /// removeDestination - This method removes the specified successor from the
3359 /// indirectbr instruction.
3360 void IndirectBrInst::removeDestination(unsigned idx) {
3361 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3363 unsigned NumOps = getNumOperands();
3364 Use *OL = OperandList;
3366 // Replace this value with the last one.
3367 OL[idx+1] = OL[NumOps-1];
3369 // Nuke the last value.
3370 OL[NumOps-1].set(0);
3371 NumOperands = NumOps-1;
3374 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3375 return getSuccessor(idx);
3377 unsigned IndirectBrInst::getNumSuccessorsV() const {
3378 return getNumSuccessors();
3380 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3381 setSuccessor(idx, B);
3384 //===----------------------------------------------------------------------===//
3385 // clone_impl() implementations
3386 //===----------------------------------------------------------------------===//
3388 // Define these methods here so vtables don't get emitted into every translation
3389 // unit that uses these classes.
3391 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3392 return new (getNumOperands()) GetElementPtrInst(*this);
3395 BinaryOperator *BinaryOperator::clone_impl() const {
3396 return Create(getOpcode(), Op<0>(), Op<1>());
3399 FCmpInst* FCmpInst::clone_impl() const {
3400 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3403 ICmpInst* ICmpInst::clone_impl() const {
3404 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3407 ExtractValueInst *ExtractValueInst::clone_impl() const {
3408 return new ExtractValueInst(*this);
3411 InsertValueInst *InsertValueInst::clone_impl() const {
3412 return new InsertValueInst(*this);
3415 AllocaInst *AllocaInst::clone_impl() const {
3416 return new AllocaInst(getAllocatedType(),
3417 (Value*)getOperand(0),
3421 LoadInst *LoadInst::clone_impl() const {
3422 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3423 getAlignment(), getOrdering(), getSynchScope());
3426 StoreInst *StoreInst::clone_impl() const {
3427 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3428 getAlignment(), getOrdering(), getSynchScope());
3432 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3433 AtomicCmpXchgInst *Result =
3434 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3435 getOrdering(), getSynchScope());
3436 Result->setVolatile(isVolatile());
3440 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3441 AtomicRMWInst *Result =
3442 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3443 getOrdering(), getSynchScope());
3444 Result->setVolatile(isVolatile());
3448 FenceInst *FenceInst::clone_impl() const {
3449 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3452 TruncInst *TruncInst::clone_impl() const {
3453 return new TruncInst(getOperand(0), getType());
3456 ZExtInst *ZExtInst::clone_impl() const {
3457 return new ZExtInst(getOperand(0), getType());
3460 SExtInst *SExtInst::clone_impl() const {
3461 return new SExtInst(getOperand(0), getType());
3464 FPTruncInst *FPTruncInst::clone_impl() const {
3465 return new FPTruncInst(getOperand(0), getType());
3468 FPExtInst *FPExtInst::clone_impl() const {
3469 return new FPExtInst(getOperand(0), getType());
3472 UIToFPInst *UIToFPInst::clone_impl() const {
3473 return new UIToFPInst(getOperand(0), getType());
3476 SIToFPInst *SIToFPInst::clone_impl() const {
3477 return new SIToFPInst(getOperand(0), getType());
3480 FPToUIInst *FPToUIInst::clone_impl() const {
3481 return new FPToUIInst(getOperand(0), getType());
3484 FPToSIInst *FPToSIInst::clone_impl() const {
3485 return new FPToSIInst(getOperand(0), getType());
3488 PtrToIntInst *PtrToIntInst::clone_impl() const {
3489 return new PtrToIntInst(getOperand(0), getType());
3492 IntToPtrInst *IntToPtrInst::clone_impl() const {
3493 return new IntToPtrInst(getOperand(0), getType());
3496 BitCastInst *BitCastInst::clone_impl() const {
3497 return new BitCastInst(getOperand(0), getType());
3500 CallInst *CallInst::clone_impl() const {
3501 return new(getNumOperands()) CallInst(*this);
3504 SelectInst *SelectInst::clone_impl() const {
3505 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3508 VAArgInst *VAArgInst::clone_impl() const {
3509 return new VAArgInst(getOperand(0), getType());
3512 ExtractElementInst *ExtractElementInst::clone_impl() const {
3513 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3516 InsertElementInst *InsertElementInst::clone_impl() const {
3517 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3520 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3521 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3524 PHINode *PHINode::clone_impl() const {
3525 return new PHINode(*this);
3528 LandingPadInst *LandingPadInst::clone_impl() const {
3529 return new LandingPadInst(*this);
3532 ReturnInst *ReturnInst::clone_impl() const {
3533 return new(getNumOperands()) ReturnInst(*this);
3536 BranchInst *BranchInst::clone_impl() const {
3537 return new(getNumOperands()) BranchInst(*this);
3540 SwitchInst *SwitchInst::clone_impl() const {
3541 return new SwitchInst(*this);
3544 IndirectBrInst *IndirectBrInst::clone_impl() const {
3545 return new IndirectBrInst(*this);
3549 InvokeInst *InvokeInst::clone_impl() const {
3550 return new(getNumOperands()) InvokeInst(*this);
3553 ResumeInst *ResumeInst::clone_impl() const {
3554 return new(1) ResumeInst(*this);
3557 UnreachableInst *UnreachableInst::clone_impl() const {
3558 LLVMContext &Context = getContext();
3559 return new UnreachableInst(Context);