1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/MathExtras.h"
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 User::op_iterator CallSite::getCallee() const {
33 Instruction *II(getInstruction());
35 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
36 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
39 //===----------------------------------------------------------------------===//
40 // TerminatorInst Class
41 //===----------------------------------------------------------------------===//
43 // Out of line virtual method, so the vtable, etc has a home.
44 TerminatorInst::~TerminatorInst() {
47 //===----------------------------------------------------------------------===//
48 // UnaryInstruction Class
49 //===----------------------------------------------------------------------===//
51 // Out of line virtual method, so the vtable, etc has a home.
52 UnaryInstruction::~UnaryInstruction() {
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 /// areInvalidOperands - Return a string if the specified operands are invalid
60 /// for a select operation, otherwise return null.
61 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
62 if (Op1->getType() != Op2->getType())
63 return "both values to select must have same type";
65 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
67 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
68 return "vector select condition element type must be i1";
69 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
71 return "selected values for vector select must be vectors";
72 if (ET->getNumElements() != VT->getNumElements())
73 return "vector select requires selected vectors to have "
74 "the same vector length as select condition";
75 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
76 return "select condition must be i1 or <n x i1>";
82 //===----------------------------------------------------------------------===//
84 //===----------------------------------------------------------------------===//
86 PHINode::PHINode(const PHINode &PN)
87 : Instruction(PN.getType(), Instruction::PHI,
88 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
89 ReservedSpace(PN.getNumOperands()) {
90 std::copy(PN.op_begin(), PN.op_end(), op_begin());
91 std::copy(PN.block_begin(), PN.block_end(), block_begin());
92 SubclassOptionalData = PN.SubclassOptionalData;
99 Use *PHINode::allocHungoffUses(unsigned N) const {
100 // Allocate the array of Uses of the incoming values, followed by a pointer
101 // (with bottom bit set) to the User, followed by the array of pointers to
102 // the incoming basic blocks.
103 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
104 + N * sizeof(BasicBlock*);
105 Use *Begin = static_cast<Use*>(::operator new(size));
106 Use *End = Begin + N;
107 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
108 return Use::initTags(Begin, End);
111 // removeIncomingValue - Remove an incoming value. This is useful if a
112 // predecessor basic block is deleted.
113 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
114 Value *Removed = getIncomingValue(Idx);
116 // Move everything after this operand down.
118 // FIXME: we could just swap with the end of the list, then erase. However,
119 // clients might not expect this to happen. The code as it is thrashes the
120 // use/def lists, which is kinda lame.
121 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
122 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
124 // Nuke the last value.
128 // If the PHI node is dead, because it has zero entries, nuke it now.
129 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
130 // If anyone is using this PHI, make them use a dummy value instead...
131 replaceAllUsesWith(UndefValue::get(getType()));
137 /// growOperands - grow operands - This grows the operand list in response
138 /// to a push_back style of operation. This grows the number of ops by 1.5
141 void PHINode::growOperands() {
142 unsigned e = getNumOperands();
143 unsigned NumOps = e + e / 2;
144 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
146 Use *OldOps = op_begin();
147 BasicBlock **OldBlocks = block_begin();
149 ReservedSpace = NumOps;
150 OperandList = allocHungoffUses(ReservedSpace);
152 std::copy(OldOps, OldOps + e, op_begin());
153 std::copy(OldBlocks, OldBlocks + e, block_begin());
155 Use::zap(OldOps, OldOps + e, true);
158 /// hasConstantValue - If the specified PHI node always merges together the same
159 /// value, return the value, otherwise return null.
160 Value *PHINode::hasConstantValue() const {
161 // Exploit the fact that phi nodes always have at least one entry.
162 Value *ConstantValue = getIncomingValue(0);
163 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
164 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
165 if (ConstantValue != this)
166 return 0; // Incoming values not all the same.
167 // The case where the first value is this PHI.
168 ConstantValue = getIncomingValue(i);
170 if (ConstantValue == this)
171 return UndefValue::get(getType());
172 return ConstantValue;
175 //===----------------------------------------------------------------------===//
176 // LandingPadInst Implementation
177 //===----------------------------------------------------------------------===//
179 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
180 unsigned NumReservedValues, const Twine &NameStr,
181 Instruction *InsertBefore)
182 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
183 init(PersonalityFn, 1 + NumReservedValues, NameStr);
186 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
187 unsigned NumReservedValues, const Twine &NameStr,
188 BasicBlock *InsertAtEnd)
189 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
190 init(PersonalityFn, 1 + NumReservedValues, NameStr);
193 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
194 : Instruction(LP.getType(), Instruction::LandingPad,
195 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
196 ReservedSpace(LP.getNumOperands()) {
197 Use *OL = OperandList, *InOL = LP.OperandList;
198 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
201 setCleanup(LP.isCleanup());
204 LandingPadInst::~LandingPadInst() {
208 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
209 unsigned NumReservedClauses,
210 const Twine &NameStr,
211 Instruction *InsertBefore) {
212 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
216 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
217 unsigned NumReservedClauses,
218 const Twine &NameStr,
219 BasicBlock *InsertAtEnd) {
220 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
224 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
225 const Twine &NameStr) {
226 ReservedSpace = NumReservedValues;
228 OperandList = allocHungoffUses(ReservedSpace);
229 OperandList[0] = PersFn;
234 /// growOperands - grow operands - This grows the operand list in response to a
235 /// push_back style of operation. This grows the number of ops by 2 times.
236 void LandingPadInst::growOperands(unsigned Size) {
237 unsigned e = getNumOperands();
238 if (ReservedSpace >= e + Size) return;
239 ReservedSpace = (e + Size / 2) * 2;
241 Use *NewOps = allocHungoffUses(ReservedSpace);
242 Use *OldOps = OperandList;
243 for (unsigned i = 0; i != e; ++i)
244 NewOps[i] = OldOps[i];
246 OperandList = NewOps;
247 Use::zap(OldOps, OldOps + e, true);
250 void LandingPadInst::addClause(Value *Val) {
251 unsigned OpNo = getNumOperands();
253 assert(OpNo < ReservedSpace && "Growing didn't work!");
255 OperandList[OpNo] = Val;
258 //===----------------------------------------------------------------------===//
259 // CallInst Implementation
260 //===----------------------------------------------------------------------===//
262 CallInst::~CallInst() {
265 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
266 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
271 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
273 assert((Args.size() == FTy->getNumParams() ||
274 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
275 "Calling a function with bad signature!");
277 for (unsigned i = 0; i != Args.size(); ++i)
278 assert((i >= FTy->getNumParams() ||
279 FTy->getParamType(i) == Args[i]->getType()) &&
280 "Calling a function with a bad signature!");
283 std::copy(Args.begin(), Args.end(), op_begin());
287 void CallInst::init(Value *Func, const Twine &NameStr) {
288 assert(NumOperands == 1 && "NumOperands not set up?");
293 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
295 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
301 CallInst::CallInst(Value *Func, const Twine &Name,
302 Instruction *InsertBefore)
303 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
304 ->getElementType())->getReturnType(),
306 OperandTraits<CallInst>::op_end(this) - 1,
311 CallInst::CallInst(Value *Func, const Twine &Name,
312 BasicBlock *InsertAtEnd)
313 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
314 ->getElementType())->getReturnType(),
316 OperandTraits<CallInst>::op_end(this) - 1,
321 CallInst::CallInst(const CallInst &CI)
322 : Instruction(CI.getType(), Instruction::Call,
323 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
324 CI.getNumOperands()) {
325 setAttributes(CI.getAttributes());
326 setTailCall(CI.isTailCall());
327 setCallingConv(CI.getCallingConv());
329 std::copy(CI.op_begin(), CI.op_end(), op_begin());
330 SubclassOptionalData = CI.SubclassOptionalData;
333 void CallInst::addAttribute(unsigned i, Attributes attr) {
334 AttrListPtr PAL = getAttributes();
335 PAL = PAL.addAttr(i, attr);
339 void CallInst::removeAttribute(unsigned i, Attributes attr) {
340 AttrListPtr PAL = getAttributes();
341 PAL = PAL.removeAttr(i, attr);
345 bool CallInst::fnHasNoAliasAttr() const {
346 if (AttributeList.getParamAttributes(~0U).hasNoAliasAttr())
348 if (const Function *F = getCalledFunction())
349 return F->getParamAttributes(~0U).hasNoAliasAttr();
352 bool CallInst::fnHasNoInlineAttr() const {
353 if (AttributeList.getParamAttributes(~0U).hasNoInlineAttr())
355 if (const Function *F = getCalledFunction())
356 return F->getParamAttributes(~0U).hasNoInlineAttr();
359 bool CallInst::fnHasNoReturnAttr() const {
360 if (AttributeList.getParamAttributes(~0U).hasNoReturnAttr())
362 if (const Function *F = getCalledFunction())
363 return F->getParamAttributes(~0U).hasNoReturnAttr();
366 bool CallInst::fnHasNoUnwindAttr() const {
367 if (AttributeList.getParamAttributes(~0U).hasNoUnwindAttr())
369 if (const Function *F = getCalledFunction())
370 return F->getParamAttributes(~0U).hasNoUnwindAttr();
373 bool CallInst::fnHasReadNoneAttr() const {
374 if (AttributeList.getParamAttributes(~0U).hasReadNoneAttr())
376 if (const Function *F = getCalledFunction())
377 return F->getParamAttributes(~0U).hasReadNoneAttr();
380 bool CallInst::fnHasReadOnlyAttr() const {
381 if (AttributeList.getParamAttributes(~0U).hasReadOnlyAttr())
383 if (const Function *F = getCalledFunction())
384 return F->getParamAttributes(~0U).hasReadOnlyAttr();
387 bool CallInst::fnHasReturnsTwiceAttr() const {
388 if (AttributeList.getParamAttributes(~0U).hasReturnsTwiceAttr())
390 if (const Function *F = getCalledFunction())
391 return F->getParamAttributes(~0U).hasReturnsTwiceAttr();
395 bool CallInst::paramHasSExtAttr(unsigned i) const {
396 if (AttributeList.getParamAttributes(i).hasSExtAttr())
398 if (const Function *F = getCalledFunction())
399 return F->getParamAttributes(i).hasSExtAttr();
403 bool CallInst::paramHasZExtAttr(unsigned i) const {
404 if (AttributeList.getParamAttributes(i).hasZExtAttr())
406 if (const Function *F = getCalledFunction())
407 return F->getParamAttributes(i).hasZExtAttr();
411 bool CallInst::paramHasInRegAttr(unsigned i) const {
412 if (AttributeList.getParamAttributes(i).hasInRegAttr())
414 if (const Function *F = getCalledFunction())
415 return F->getParamAttributes(i).hasInRegAttr();
419 bool CallInst::paramHasStructRetAttr(unsigned i) const {
420 if (AttributeList.getParamAttributes(i).hasStructRetAttr())
422 if (const Function *F = getCalledFunction())
423 return F->getParamAttributes(i).hasStructRetAttr();
427 bool CallInst::paramHasNestAttr(unsigned i) const {
428 if (AttributeList.getParamAttributes(i).hasNestAttr())
430 if (const Function *F = getCalledFunction())
431 return F->getParamAttributes(i).hasNestAttr();
435 bool CallInst::paramHasByValAttr(unsigned i) const {
436 if (AttributeList.getParamAttributes(i).hasByValAttr())
438 if (const Function *F = getCalledFunction())
439 return F->getParamAttributes(i).hasByValAttr();
443 bool CallInst::paramHasNoAliasAttr(unsigned i) const {
444 if (AttributeList.getParamAttributes(i).hasNoAliasAttr())
446 if (const Function *F = getCalledFunction())
447 return F->getParamAttributes(i).hasNoAliasAttr();
451 bool CallInst::paramHasNoCaptureAttr(unsigned i) const {
452 if (AttributeList.getParamAttributes(i).hasNoCaptureAttr())
454 if (const Function *F = getCalledFunction())
455 return F->getParamAttributes(i).hasNoCaptureAttr();
459 /// IsConstantOne - Return true only if val is constant int 1
460 static bool IsConstantOne(Value *val) {
461 assert(val && "IsConstantOne does not work with NULL val");
462 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
465 static Instruction *createMalloc(Instruction *InsertBefore,
466 BasicBlock *InsertAtEnd, Type *IntPtrTy,
467 Type *AllocTy, Value *AllocSize,
468 Value *ArraySize, Function *MallocF,
470 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
471 "createMalloc needs either InsertBefore or InsertAtEnd");
473 // malloc(type) becomes:
474 // bitcast (i8* malloc(typeSize)) to type*
475 // malloc(type, arraySize) becomes:
476 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
478 ArraySize = ConstantInt::get(IntPtrTy, 1);
479 else if (ArraySize->getType() != IntPtrTy) {
481 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
484 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
488 if (!IsConstantOne(ArraySize)) {
489 if (IsConstantOne(AllocSize)) {
490 AllocSize = ArraySize; // Operand * 1 = Operand
491 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
492 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
494 // Malloc arg is constant product of type size and array size
495 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
497 // Multiply type size by the array size...
499 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
500 "mallocsize", InsertBefore);
502 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
503 "mallocsize", InsertAtEnd);
507 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
508 // Create the call to Malloc.
509 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
510 Module* M = BB->getParent()->getParent();
511 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
512 Value *MallocFunc = MallocF;
514 // prototype malloc as "void *malloc(size_t)"
515 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
516 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
517 CallInst *MCall = NULL;
518 Instruction *Result = NULL;
520 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
522 if (Result->getType() != AllocPtrType)
523 // Create a cast instruction to convert to the right type...
524 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
526 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
528 if (Result->getType() != AllocPtrType) {
529 InsertAtEnd->getInstList().push_back(MCall);
530 // Create a cast instruction to convert to the right type...
531 Result = new BitCastInst(MCall, AllocPtrType, Name);
534 MCall->setTailCall();
535 if (Function *F = dyn_cast<Function>(MallocFunc)) {
536 MCall->setCallingConv(F->getCallingConv());
537 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
539 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
544 /// CreateMalloc - Generate the IR for a call to malloc:
545 /// 1. Compute the malloc call's argument as the specified type's size,
546 /// possibly multiplied by the array size if the array size is not
548 /// 2. Call malloc with that argument.
549 /// 3. Bitcast the result of the malloc call to the specified type.
550 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
551 Type *IntPtrTy, Type *AllocTy,
552 Value *AllocSize, Value *ArraySize,
555 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
556 ArraySize, MallocF, Name);
559 /// CreateMalloc - Generate the IR for a call to malloc:
560 /// 1. Compute the malloc call's argument as the specified type's size,
561 /// possibly multiplied by the array size if the array size is not
563 /// 2. Call malloc with that argument.
564 /// 3. Bitcast the result of the malloc call to the specified type.
565 /// Note: This function does not add the bitcast to the basic block, that is the
566 /// responsibility of the caller.
567 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
568 Type *IntPtrTy, Type *AllocTy,
569 Value *AllocSize, Value *ArraySize,
570 Function *MallocF, const Twine &Name) {
571 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
572 ArraySize, MallocF, Name);
575 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
576 BasicBlock *InsertAtEnd) {
577 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
578 "createFree needs either InsertBefore or InsertAtEnd");
579 assert(Source->getType()->isPointerTy() &&
580 "Can not free something of nonpointer type!");
582 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
583 Module* M = BB->getParent()->getParent();
585 Type *VoidTy = Type::getVoidTy(M->getContext());
586 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
587 // prototype free as "void free(void*)"
588 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
589 CallInst* Result = NULL;
590 Value *PtrCast = Source;
592 if (Source->getType() != IntPtrTy)
593 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
594 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
596 if (Source->getType() != IntPtrTy)
597 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
598 Result = CallInst::Create(FreeFunc, PtrCast, "");
600 Result->setTailCall();
601 if (Function *F = dyn_cast<Function>(FreeFunc))
602 Result->setCallingConv(F->getCallingConv());
607 /// CreateFree - Generate the IR for a call to the builtin free function.
608 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
609 return createFree(Source, InsertBefore, NULL);
612 /// CreateFree - Generate the IR for a call to the builtin free function.
613 /// Note: This function does not add the call to the basic block, that is the
614 /// responsibility of the caller.
615 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
616 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
617 assert(FreeCall && "CreateFree did not create a CallInst");
621 //===----------------------------------------------------------------------===//
622 // InvokeInst Implementation
623 //===----------------------------------------------------------------------===//
625 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
626 ArrayRef<Value *> Args, const Twine &NameStr) {
627 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
630 Op<-1>() = IfException;
634 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
636 assert(((Args.size() == FTy->getNumParams()) ||
637 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
638 "Invoking a function with bad signature");
640 for (unsigned i = 0, e = Args.size(); i != e; i++)
641 assert((i >= FTy->getNumParams() ||
642 FTy->getParamType(i) == Args[i]->getType()) &&
643 "Invoking a function with a bad signature!");
646 std::copy(Args.begin(), Args.end(), op_begin());
650 InvokeInst::InvokeInst(const InvokeInst &II)
651 : TerminatorInst(II.getType(), Instruction::Invoke,
652 OperandTraits<InvokeInst>::op_end(this)
653 - II.getNumOperands(),
654 II.getNumOperands()) {
655 setAttributes(II.getAttributes());
656 setCallingConv(II.getCallingConv());
657 std::copy(II.op_begin(), II.op_end(), op_begin());
658 SubclassOptionalData = II.SubclassOptionalData;
661 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
662 return getSuccessor(idx);
664 unsigned InvokeInst::getNumSuccessorsV() const {
665 return getNumSuccessors();
667 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
668 return setSuccessor(idx, B);
671 bool InvokeInst::fnHasNoAliasAttr() const {
672 if (AttributeList.getParamAttributes(~0U).hasNoAliasAttr())
674 if (const Function *F = getCalledFunction())
675 return F->getParamAttributes(~0U).hasNoAliasAttr();
678 bool InvokeInst::fnHasNoInlineAttr() const {
679 if (AttributeList.getParamAttributes(~0U).hasNoInlineAttr())
681 if (const Function *F = getCalledFunction())
682 return F->getParamAttributes(~0U).hasNoInlineAttr();
685 bool InvokeInst::fnHasNoReturnAttr() const {
686 if (AttributeList.getParamAttributes(~0U).hasNoReturnAttr())
688 if (const Function *F = getCalledFunction())
689 return F->getParamAttributes(~0U).hasNoReturnAttr();
692 bool InvokeInst::fnHasNoUnwindAttr() const {
693 if (AttributeList.getParamAttributes(~0U).hasNoUnwindAttr())
695 if (const Function *F = getCalledFunction())
696 return F->getParamAttributes(~0U).hasNoUnwindAttr();
699 bool InvokeInst::fnHasReadNoneAttr() const {
700 if (AttributeList.getParamAttributes(~0U).hasReadNoneAttr())
702 if (const Function *F = getCalledFunction())
703 return F->getParamAttributes(~0U).hasReadNoneAttr();
706 bool InvokeInst::fnHasReadOnlyAttr() const {
707 if (AttributeList.getParamAttributes(~0U).hasReadOnlyAttr())
709 if (const Function *F = getCalledFunction())
710 return F->getParamAttributes(~0U).hasReadOnlyAttr();
713 bool InvokeInst::fnHasReturnsTwiceAttr() const {
714 if (AttributeList.getParamAttributes(~0U).hasReturnsTwiceAttr())
716 if (const Function *F = getCalledFunction())
717 return F->getParamAttributes(~0U).hasReturnsTwiceAttr();
721 bool InvokeInst::paramHasSExtAttr(unsigned i) const {
722 if (AttributeList.getParamAttributes(i).hasSExtAttr())
724 if (const Function *F = getCalledFunction())
725 return F->getParamAttributes(i).hasSExtAttr();
729 bool InvokeInst::paramHasZExtAttr(unsigned i) const {
730 if (AttributeList.getParamAttributes(i).hasZExtAttr())
732 if (const Function *F = getCalledFunction())
733 return F->getParamAttributes(i).hasZExtAttr();
737 bool InvokeInst::paramHasInRegAttr(unsigned i) const {
738 if (AttributeList.getParamAttributes(i).hasInRegAttr())
740 if (const Function *F = getCalledFunction())
741 return F->getParamAttributes(i).hasInRegAttr();
745 bool InvokeInst::paramHasStructRetAttr(unsigned i) const {
746 if (AttributeList.getParamAttributes(i).hasStructRetAttr())
748 if (const Function *F = getCalledFunction())
749 return F->getParamAttributes(i).hasStructRetAttr();
753 bool InvokeInst::paramHasNestAttr(unsigned i) const {
754 if (AttributeList.getParamAttributes(i).hasNestAttr())
756 if (const Function *F = getCalledFunction())
757 return F->getParamAttributes(i).hasNestAttr();
761 bool InvokeInst::paramHasByValAttr(unsigned i) const {
762 if (AttributeList.getParamAttributes(i).hasByValAttr())
764 if (const Function *F = getCalledFunction())
765 return F->getParamAttributes(i).hasByValAttr();
769 bool InvokeInst::paramHasNoAliasAttr(unsigned i) const {
770 if (AttributeList.getParamAttributes(i).hasNoAliasAttr())
772 if (const Function *F = getCalledFunction())
773 return F->getParamAttributes(i).hasNoAliasAttr();
777 bool InvokeInst::paramHasNoCaptureAttr(unsigned i) const {
778 if (AttributeList.getParamAttributes(i).hasNoCaptureAttr())
780 if (const Function *F = getCalledFunction())
781 return F->getParamAttributes(i).hasNoCaptureAttr();
785 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
786 AttrListPtr PAL = getAttributes();
787 PAL = PAL.addAttr(i, attr);
791 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
792 AttrListPtr PAL = getAttributes();
793 PAL = PAL.removeAttr(i, attr);
797 LandingPadInst *InvokeInst::getLandingPadInst() const {
798 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
801 //===----------------------------------------------------------------------===//
802 // ReturnInst Implementation
803 //===----------------------------------------------------------------------===//
805 ReturnInst::ReturnInst(const ReturnInst &RI)
806 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
807 OperandTraits<ReturnInst>::op_end(this) -
809 RI.getNumOperands()) {
810 if (RI.getNumOperands())
811 Op<0>() = RI.Op<0>();
812 SubclassOptionalData = RI.SubclassOptionalData;
815 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
816 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
817 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
822 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
823 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
824 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
829 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
830 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
831 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
834 unsigned ReturnInst::getNumSuccessorsV() const {
835 return getNumSuccessors();
838 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
839 /// emit the vtable for the class in this translation unit.
840 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
841 llvm_unreachable("ReturnInst has no successors!");
844 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
845 llvm_unreachable("ReturnInst has no successors!");
848 ReturnInst::~ReturnInst() {
851 //===----------------------------------------------------------------------===//
852 // ResumeInst Implementation
853 //===----------------------------------------------------------------------===//
855 ResumeInst::ResumeInst(const ResumeInst &RI)
856 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
857 OperandTraits<ResumeInst>::op_begin(this), 1) {
858 Op<0>() = RI.Op<0>();
861 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
862 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
863 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
867 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
868 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
869 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
873 unsigned ResumeInst::getNumSuccessorsV() const {
874 return getNumSuccessors();
877 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
878 llvm_unreachable("ResumeInst has no successors!");
881 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
882 llvm_unreachable("ResumeInst has no successors!");
885 //===----------------------------------------------------------------------===//
886 // UnreachableInst Implementation
887 //===----------------------------------------------------------------------===//
889 UnreachableInst::UnreachableInst(LLVMContext &Context,
890 Instruction *InsertBefore)
891 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
892 0, 0, InsertBefore) {
894 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
895 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
899 unsigned UnreachableInst::getNumSuccessorsV() const {
900 return getNumSuccessors();
903 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
904 llvm_unreachable("UnreachableInst has no successors!");
907 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
908 llvm_unreachable("UnreachableInst has no successors!");
911 //===----------------------------------------------------------------------===//
912 // BranchInst Implementation
913 //===----------------------------------------------------------------------===//
915 void BranchInst::AssertOK() {
917 assert(getCondition()->getType()->isIntegerTy(1) &&
918 "May only branch on boolean predicates!");
921 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
922 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
923 OperandTraits<BranchInst>::op_end(this) - 1,
925 assert(IfTrue != 0 && "Branch destination may not be null!");
928 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
929 Instruction *InsertBefore)
930 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
931 OperandTraits<BranchInst>::op_end(this) - 3,
941 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
942 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
943 OperandTraits<BranchInst>::op_end(this) - 1,
945 assert(IfTrue != 0 && "Branch destination may not be null!");
949 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
950 BasicBlock *InsertAtEnd)
951 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
952 OperandTraits<BranchInst>::op_end(this) - 3,
963 BranchInst::BranchInst(const BranchInst &BI) :
964 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
965 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
966 BI.getNumOperands()) {
967 Op<-1>() = BI.Op<-1>();
968 if (BI.getNumOperands() != 1) {
969 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
970 Op<-3>() = BI.Op<-3>();
971 Op<-2>() = BI.Op<-2>();
973 SubclassOptionalData = BI.SubclassOptionalData;
976 void BranchInst::swapSuccessors() {
977 assert(isConditional() &&
978 "Cannot swap successors of an unconditional branch");
979 Op<-1>().swap(Op<-2>());
981 // Update profile metadata if present and it matches our structural
983 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
984 if (!ProfileData || ProfileData->getNumOperands() != 3)
987 // The first operand is the name. Fetch them backwards and build a new one.
989 ProfileData->getOperand(0),
990 ProfileData->getOperand(2),
991 ProfileData->getOperand(1)
993 setMetadata(LLVMContext::MD_prof,
994 MDNode::get(ProfileData->getContext(), Ops));
997 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
998 return getSuccessor(idx);
1000 unsigned BranchInst::getNumSuccessorsV() const {
1001 return getNumSuccessors();
1003 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1004 setSuccessor(idx, B);
1008 //===----------------------------------------------------------------------===//
1009 // AllocaInst Implementation
1010 //===----------------------------------------------------------------------===//
1012 static Value *getAISize(LLVMContext &Context, Value *Amt) {
1014 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1016 assert(!isa<BasicBlock>(Amt) &&
1017 "Passed basic block into allocation size parameter! Use other ctor");
1018 assert(Amt->getType()->isIntegerTy() &&
1019 "Allocation array size is not an integer!");
1024 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
1025 const Twine &Name, Instruction *InsertBefore)
1026 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1027 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
1029 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1033 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
1034 const Twine &Name, BasicBlock *InsertAtEnd)
1035 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1036 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
1038 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1042 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
1043 Instruction *InsertBefore)
1044 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1045 getAISize(Ty->getContext(), 0), InsertBefore) {
1047 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1051 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
1052 BasicBlock *InsertAtEnd)
1053 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1054 getAISize(Ty->getContext(), 0), InsertAtEnd) {
1056 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1060 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1061 const Twine &Name, Instruction *InsertBefore)
1062 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1063 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
1064 setAlignment(Align);
1065 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1069 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1070 const Twine &Name, BasicBlock *InsertAtEnd)
1071 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1072 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
1073 setAlignment(Align);
1074 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1078 // Out of line virtual method, so the vtable, etc has a home.
1079 AllocaInst::~AllocaInst() {
1082 void AllocaInst::setAlignment(unsigned Align) {
1083 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1084 assert(Align <= MaximumAlignment &&
1085 "Alignment is greater than MaximumAlignment!");
1086 setInstructionSubclassData(Log2_32(Align) + 1);
1087 assert(getAlignment() == Align && "Alignment representation error!");
1090 bool AllocaInst::isArrayAllocation() const {
1091 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1092 return !CI->isOne();
1096 Type *AllocaInst::getAllocatedType() const {
1097 return getType()->getElementType();
1100 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1101 /// function and is a constant size. If so, the code generator will fold it
1102 /// into the prolog/epilog code, so it is basically free.
1103 bool AllocaInst::isStaticAlloca() const {
1104 // Must be constant size.
1105 if (!isa<ConstantInt>(getArraySize())) return false;
1107 // Must be in the entry block.
1108 const BasicBlock *Parent = getParent();
1109 return Parent == &Parent->getParent()->front();
1112 //===----------------------------------------------------------------------===//
1113 // LoadInst Implementation
1114 //===----------------------------------------------------------------------===//
1116 void LoadInst::AssertOK() {
1117 assert(getOperand(0)->getType()->isPointerTy() &&
1118 "Ptr must have pointer type.");
1119 assert(!(isAtomic() && getAlignment() == 0) &&
1120 "Alignment required for atomic load");
1123 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1124 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1125 Load, Ptr, InsertBef) {
1128 setAtomic(NotAtomic);
1133 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1134 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1135 Load, Ptr, InsertAE) {
1138 setAtomic(NotAtomic);
1143 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1144 Instruction *InsertBef)
1145 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1146 Load, Ptr, InsertBef) {
1147 setVolatile(isVolatile);
1149 setAtomic(NotAtomic);
1154 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1155 BasicBlock *InsertAE)
1156 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1157 Load, Ptr, InsertAE) {
1158 setVolatile(isVolatile);
1160 setAtomic(NotAtomic);
1165 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1166 unsigned Align, Instruction *InsertBef)
1167 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1168 Load, Ptr, InsertBef) {
1169 setVolatile(isVolatile);
1170 setAlignment(Align);
1171 setAtomic(NotAtomic);
1176 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1177 unsigned Align, BasicBlock *InsertAE)
1178 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1179 Load, Ptr, InsertAE) {
1180 setVolatile(isVolatile);
1181 setAlignment(Align);
1182 setAtomic(NotAtomic);
1187 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1188 unsigned Align, AtomicOrdering Order,
1189 SynchronizationScope SynchScope,
1190 Instruction *InsertBef)
1191 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1192 Load, Ptr, InsertBef) {
1193 setVolatile(isVolatile);
1194 setAlignment(Align);
1195 setAtomic(Order, SynchScope);
1200 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1201 unsigned Align, AtomicOrdering Order,
1202 SynchronizationScope SynchScope,
1203 BasicBlock *InsertAE)
1204 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1205 Load, Ptr, InsertAE) {
1206 setVolatile(isVolatile);
1207 setAlignment(Align);
1208 setAtomic(Order, SynchScope);
1213 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1214 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1215 Load, Ptr, InsertBef) {
1218 setAtomic(NotAtomic);
1220 if (Name && Name[0]) setName(Name);
1223 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1224 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1225 Load, Ptr, InsertAE) {
1228 setAtomic(NotAtomic);
1230 if (Name && Name[0]) setName(Name);
1233 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1234 Instruction *InsertBef)
1235 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1236 Load, Ptr, InsertBef) {
1237 setVolatile(isVolatile);
1239 setAtomic(NotAtomic);
1241 if (Name && Name[0]) setName(Name);
1244 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1245 BasicBlock *InsertAE)
1246 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1247 Load, Ptr, InsertAE) {
1248 setVolatile(isVolatile);
1250 setAtomic(NotAtomic);
1252 if (Name && Name[0]) setName(Name);
1255 void LoadInst::setAlignment(unsigned Align) {
1256 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1257 assert(Align <= MaximumAlignment &&
1258 "Alignment is greater than MaximumAlignment!");
1259 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1260 ((Log2_32(Align)+1)<<1));
1261 assert(getAlignment() == Align && "Alignment representation error!");
1264 //===----------------------------------------------------------------------===//
1265 // StoreInst Implementation
1266 //===----------------------------------------------------------------------===//
1268 void StoreInst::AssertOK() {
1269 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1270 assert(getOperand(1)->getType()->isPointerTy() &&
1271 "Ptr must have pointer type!");
1272 assert(getOperand(0)->getType() ==
1273 cast<PointerType>(getOperand(1)->getType())->getElementType()
1274 && "Ptr must be a pointer to Val type!");
1275 assert(!(isAtomic() && getAlignment() == 0) &&
1276 "Alignment required for atomic load");
1280 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1281 : Instruction(Type::getVoidTy(val->getContext()), Store,
1282 OperandTraits<StoreInst>::op_begin(this),
1283 OperandTraits<StoreInst>::operands(this),
1289 setAtomic(NotAtomic);
1293 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1294 : Instruction(Type::getVoidTy(val->getContext()), Store,
1295 OperandTraits<StoreInst>::op_begin(this),
1296 OperandTraits<StoreInst>::operands(this),
1302 setAtomic(NotAtomic);
1306 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1307 Instruction *InsertBefore)
1308 : Instruction(Type::getVoidTy(val->getContext()), Store,
1309 OperandTraits<StoreInst>::op_begin(this),
1310 OperandTraits<StoreInst>::operands(this),
1314 setVolatile(isVolatile);
1316 setAtomic(NotAtomic);
1320 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1321 unsigned Align, Instruction *InsertBefore)
1322 : Instruction(Type::getVoidTy(val->getContext()), Store,
1323 OperandTraits<StoreInst>::op_begin(this),
1324 OperandTraits<StoreInst>::operands(this),
1328 setVolatile(isVolatile);
1329 setAlignment(Align);
1330 setAtomic(NotAtomic);
1334 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1335 unsigned Align, AtomicOrdering Order,
1336 SynchronizationScope SynchScope,
1337 Instruction *InsertBefore)
1338 : Instruction(Type::getVoidTy(val->getContext()), Store,
1339 OperandTraits<StoreInst>::op_begin(this),
1340 OperandTraits<StoreInst>::operands(this),
1344 setVolatile(isVolatile);
1345 setAlignment(Align);
1346 setAtomic(Order, SynchScope);
1350 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1351 BasicBlock *InsertAtEnd)
1352 : Instruction(Type::getVoidTy(val->getContext()), Store,
1353 OperandTraits<StoreInst>::op_begin(this),
1354 OperandTraits<StoreInst>::operands(this),
1358 setVolatile(isVolatile);
1360 setAtomic(NotAtomic);
1364 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1365 unsigned Align, BasicBlock *InsertAtEnd)
1366 : Instruction(Type::getVoidTy(val->getContext()), Store,
1367 OperandTraits<StoreInst>::op_begin(this),
1368 OperandTraits<StoreInst>::operands(this),
1372 setVolatile(isVolatile);
1373 setAlignment(Align);
1374 setAtomic(NotAtomic);
1378 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1379 unsigned Align, AtomicOrdering Order,
1380 SynchronizationScope SynchScope,
1381 BasicBlock *InsertAtEnd)
1382 : Instruction(Type::getVoidTy(val->getContext()), Store,
1383 OperandTraits<StoreInst>::op_begin(this),
1384 OperandTraits<StoreInst>::operands(this),
1388 setVolatile(isVolatile);
1389 setAlignment(Align);
1390 setAtomic(Order, SynchScope);
1394 void StoreInst::setAlignment(unsigned Align) {
1395 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1396 assert(Align <= MaximumAlignment &&
1397 "Alignment is greater than MaximumAlignment!");
1398 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1399 ((Log2_32(Align)+1) << 1));
1400 assert(getAlignment() == Align && "Alignment representation error!");
1403 //===----------------------------------------------------------------------===//
1404 // AtomicCmpXchgInst Implementation
1405 //===----------------------------------------------------------------------===//
1407 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1408 AtomicOrdering Ordering,
1409 SynchronizationScope SynchScope) {
1413 setOrdering(Ordering);
1414 setSynchScope(SynchScope);
1416 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1417 "All operands must be non-null!");
1418 assert(getOperand(0)->getType()->isPointerTy() &&
1419 "Ptr must have pointer type!");
1420 assert(getOperand(1)->getType() ==
1421 cast<PointerType>(getOperand(0)->getType())->getElementType()
1422 && "Ptr must be a pointer to Cmp type!");
1423 assert(getOperand(2)->getType() ==
1424 cast<PointerType>(getOperand(0)->getType())->getElementType()
1425 && "Ptr must be a pointer to NewVal type!");
1426 assert(Ordering != NotAtomic &&
1427 "AtomicCmpXchg instructions must be atomic!");
1430 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1431 AtomicOrdering Ordering,
1432 SynchronizationScope SynchScope,
1433 Instruction *InsertBefore)
1434 : Instruction(Cmp->getType(), AtomicCmpXchg,
1435 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1436 OperandTraits<AtomicCmpXchgInst>::operands(this),
1438 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1441 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1442 AtomicOrdering Ordering,
1443 SynchronizationScope SynchScope,
1444 BasicBlock *InsertAtEnd)
1445 : Instruction(Cmp->getType(), AtomicCmpXchg,
1446 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1447 OperandTraits<AtomicCmpXchgInst>::operands(this),
1449 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1452 //===----------------------------------------------------------------------===//
1453 // AtomicRMWInst Implementation
1454 //===----------------------------------------------------------------------===//
1456 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1457 AtomicOrdering Ordering,
1458 SynchronizationScope SynchScope) {
1461 setOperation(Operation);
1462 setOrdering(Ordering);
1463 setSynchScope(SynchScope);
1465 assert(getOperand(0) && getOperand(1) &&
1466 "All operands must be non-null!");
1467 assert(getOperand(0)->getType()->isPointerTy() &&
1468 "Ptr must have pointer type!");
1469 assert(getOperand(1)->getType() ==
1470 cast<PointerType>(getOperand(0)->getType())->getElementType()
1471 && "Ptr must be a pointer to Val type!");
1472 assert(Ordering != NotAtomic &&
1473 "AtomicRMW instructions must be atomic!");
1476 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1477 AtomicOrdering Ordering,
1478 SynchronizationScope SynchScope,
1479 Instruction *InsertBefore)
1480 : Instruction(Val->getType(), AtomicRMW,
1481 OperandTraits<AtomicRMWInst>::op_begin(this),
1482 OperandTraits<AtomicRMWInst>::operands(this),
1484 Init(Operation, Ptr, Val, Ordering, SynchScope);
1487 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1488 AtomicOrdering Ordering,
1489 SynchronizationScope SynchScope,
1490 BasicBlock *InsertAtEnd)
1491 : Instruction(Val->getType(), AtomicRMW,
1492 OperandTraits<AtomicRMWInst>::op_begin(this),
1493 OperandTraits<AtomicRMWInst>::operands(this),
1495 Init(Operation, Ptr, Val, Ordering, SynchScope);
1498 //===----------------------------------------------------------------------===//
1499 // FenceInst Implementation
1500 //===----------------------------------------------------------------------===//
1502 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1503 SynchronizationScope SynchScope,
1504 Instruction *InsertBefore)
1505 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1506 setOrdering(Ordering);
1507 setSynchScope(SynchScope);
1510 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1511 SynchronizationScope SynchScope,
1512 BasicBlock *InsertAtEnd)
1513 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1514 setOrdering(Ordering);
1515 setSynchScope(SynchScope);
1518 //===----------------------------------------------------------------------===//
1519 // GetElementPtrInst Implementation
1520 //===----------------------------------------------------------------------===//
1522 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1523 const Twine &Name) {
1524 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1525 OperandList[0] = Ptr;
1526 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1530 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1531 : Instruction(GEPI.getType(), GetElementPtr,
1532 OperandTraits<GetElementPtrInst>::op_end(this)
1533 - GEPI.getNumOperands(),
1534 GEPI.getNumOperands()) {
1535 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1536 SubclassOptionalData = GEPI.SubclassOptionalData;
1539 /// getIndexedType - Returns the type of the element that would be accessed with
1540 /// a gep instruction with the specified parameters.
1542 /// The Idxs pointer should point to a continuous piece of memory containing the
1543 /// indices, either as Value* or uint64_t.
1545 /// A null type is returned if the indices are invalid for the specified
1548 template <typename IndexTy>
1549 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1550 if (Ptr->isVectorTy()) {
1551 assert(IdxList.size() == 1 &&
1552 "GEP with vector pointers must have a single index");
1553 PointerType *PTy = dyn_cast<PointerType>(
1554 cast<VectorType>(Ptr)->getElementType());
1555 assert(PTy && "Gep with invalid vector pointer found");
1556 return PTy->getElementType();
1559 PointerType *PTy = dyn_cast<PointerType>(Ptr);
1560 if (!PTy) return 0; // Type isn't a pointer type!
1561 Type *Agg = PTy->getElementType();
1563 // Handle the special case of the empty set index set, which is always valid.
1564 if (IdxList.empty())
1567 // If there is at least one index, the top level type must be sized, otherwise
1568 // it cannot be 'stepped over'.
1569 if (!Agg->isSized())
1572 unsigned CurIdx = 1;
1573 for (; CurIdx != IdxList.size(); ++CurIdx) {
1574 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1575 if (!CT || CT->isPointerTy()) return 0;
1576 IndexTy Index = IdxList[CurIdx];
1577 if (!CT->indexValid(Index)) return 0;
1578 Agg = CT->getTypeAtIndex(Index);
1580 return CurIdx == IdxList.size() ? Agg : 0;
1583 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1584 return getIndexedTypeInternal(Ptr, IdxList);
1587 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1588 ArrayRef<Constant *> IdxList) {
1589 return getIndexedTypeInternal(Ptr, IdxList);
1592 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1593 return getIndexedTypeInternal(Ptr, IdxList);
1596 unsigned GetElementPtrInst::getAddressSpace(Value *Ptr) {
1597 Type *Ty = Ptr->getType();
1599 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1600 Ty = VTy->getElementType();
1602 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1603 return PTy->getAddressSpace();
1605 llvm_unreachable("Invalid GEP pointer type");
1608 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1609 /// zeros. If so, the result pointer and the first operand have the same
1610 /// value, just potentially different types.
1611 bool GetElementPtrInst::hasAllZeroIndices() const {
1612 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1613 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1614 if (!CI->isZero()) return false;
1622 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1623 /// constant integers. If so, the result pointer and the first operand have
1624 /// a constant offset between them.
1625 bool GetElementPtrInst::hasAllConstantIndices() const {
1626 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1627 if (!isa<ConstantInt>(getOperand(i)))
1633 void GetElementPtrInst::setIsInBounds(bool B) {
1634 cast<GEPOperator>(this)->setIsInBounds(B);
1637 bool GetElementPtrInst::isInBounds() const {
1638 return cast<GEPOperator>(this)->isInBounds();
1641 //===----------------------------------------------------------------------===//
1642 // ExtractElementInst Implementation
1643 //===----------------------------------------------------------------------===//
1645 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1647 Instruction *InsertBef)
1648 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1650 OperandTraits<ExtractElementInst>::op_begin(this),
1652 assert(isValidOperands(Val, Index) &&
1653 "Invalid extractelement instruction operands!");
1659 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1661 BasicBlock *InsertAE)
1662 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1664 OperandTraits<ExtractElementInst>::op_begin(this),
1666 assert(isValidOperands(Val, Index) &&
1667 "Invalid extractelement instruction operands!");
1675 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1676 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1682 //===----------------------------------------------------------------------===//
1683 // InsertElementInst Implementation
1684 //===----------------------------------------------------------------------===//
1686 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1688 Instruction *InsertBef)
1689 : Instruction(Vec->getType(), InsertElement,
1690 OperandTraits<InsertElementInst>::op_begin(this),
1692 assert(isValidOperands(Vec, Elt, Index) &&
1693 "Invalid insertelement instruction operands!");
1700 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1702 BasicBlock *InsertAE)
1703 : Instruction(Vec->getType(), InsertElement,
1704 OperandTraits<InsertElementInst>::op_begin(this),
1706 assert(isValidOperands(Vec, Elt, Index) &&
1707 "Invalid insertelement instruction operands!");
1715 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1716 const Value *Index) {
1717 if (!Vec->getType()->isVectorTy())
1718 return false; // First operand of insertelement must be vector type.
1720 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1721 return false;// Second operand of insertelement must be vector element type.
1723 if (!Index->getType()->isIntegerTy(32))
1724 return false; // Third operand of insertelement must be i32.
1729 //===----------------------------------------------------------------------===//
1730 // ShuffleVectorInst Implementation
1731 //===----------------------------------------------------------------------===//
1733 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1735 Instruction *InsertBefore)
1736 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1737 cast<VectorType>(Mask->getType())->getNumElements()),
1739 OperandTraits<ShuffleVectorInst>::op_begin(this),
1740 OperandTraits<ShuffleVectorInst>::operands(this),
1742 assert(isValidOperands(V1, V2, Mask) &&
1743 "Invalid shuffle vector instruction operands!");
1750 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1752 BasicBlock *InsertAtEnd)
1753 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1754 cast<VectorType>(Mask->getType())->getNumElements()),
1756 OperandTraits<ShuffleVectorInst>::op_begin(this),
1757 OperandTraits<ShuffleVectorInst>::operands(this),
1759 assert(isValidOperands(V1, V2, Mask) &&
1760 "Invalid shuffle vector instruction operands!");
1768 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1769 const Value *Mask) {
1770 // V1 and V2 must be vectors of the same type.
1771 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1774 // Mask must be vector of i32.
1775 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1776 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1779 // Check to see if Mask is valid.
1780 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1783 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1784 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1785 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1786 if (ConstantInt *CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1787 if (CI->uge(V1Size*2))
1789 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1796 if (const ConstantDataSequential *CDS =
1797 dyn_cast<ConstantDataSequential>(Mask)) {
1798 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1799 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1800 if (CDS->getElementAsInteger(i) >= V1Size*2)
1805 // The bitcode reader can create a place holder for a forward reference
1806 // used as the shuffle mask. When this occurs, the shuffle mask will
1807 // fall into this case and fail. To avoid this error, do this bit of
1808 // ugliness to allow such a mask pass.
1809 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1810 if (CE->getOpcode() == Instruction::UserOp1)
1816 /// getMaskValue - Return the index from the shuffle mask for the specified
1817 /// output result. This is either -1 if the element is undef or a number less
1818 /// than 2*numelements.
1819 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1820 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1821 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1822 return CDS->getElementAsInteger(i);
1823 Constant *C = Mask->getAggregateElement(i);
1824 if (isa<UndefValue>(C))
1826 return cast<ConstantInt>(C)->getZExtValue();
1829 /// getShuffleMask - Return the full mask for this instruction, where each
1830 /// element is the element number and undef's are returned as -1.
1831 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1832 SmallVectorImpl<int> &Result) {
1833 unsigned NumElts = Mask->getType()->getVectorNumElements();
1835 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1836 for (unsigned i = 0; i != NumElts; ++i)
1837 Result.push_back(CDS->getElementAsInteger(i));
1840 for (unsigned i = 0; i != NumElts; ++i) {
1841 Constant *C = Mask->getAggregateElement(i);
1842 Result.push_back(isa<UndefValue>(C) ? -1 :
1843 cast<ConstantInt>(C)->getZExtValue());
1848 //===----------------------------------------------------------------------===//
1849 // InsertValueInst Class
1850 //===----------------------------------------------------------------------===//
1852 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1853 const Twine &Name) {
1854 assert(NumOperands == 2 && "NumOperands not initialized?");
1856 // There's no fundamental reason why we require at least one index
1857 // (other than weirdness with &*IdxBegin being invalid; see
1858 // getelementptr's init routine for example). But there's no
1859 // present need to support it.
1860 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1862 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1863 Val->getType() && "Inserted value must match indexed type!");
1867 Indices.append(Idxs.begin(), Idxs.end());
1871 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1872 : Instruction(IVI.getType(), InsertValue,
1873 OperandTraits<InsertValueInst>::op_begin(this), 2),
1874 Indices(IVI.Indices) {
1875 Op<0>() = IVI.getOperand(0);
1876 Op<1>() = IVI.getOperand(1);
1877 SubclassOptionalData = IVI.SubclassOptionalData;
1880 //===----------------------------------------------------------------------===//
1881 // ExtractValueInst Class
1882 //===----------------------------------------------------------------------===//
1884 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1885 assert(NumOperands == 1 && "NumOperands not initialized?");
1887 // There's no fundamental reason why we require at least one index.
1888 // But there's no present need to support it.
1889 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1891 Indices.append(Idxs.begin(), Idxs.end());
1895 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1896 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1897 Indices(EVI.Indices) {
1898 SubclassOptionalData = EVI.SubclassOptionalData;
1901 // getIndexedType - Returns the type of the element that would be extracted
1902 // with an extractvalue instruction with the specified parameters.
1904 // A null type is returned if the indices are invalid for the specified
1907 Type *ExtractValueInst::getIndexedType(Type *Agg,
1908 ArrayRef<unsigned> Idxs) {
1909 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1910 unsigned Index = Idxs[CurIdx];
1911 // We can't use CompositeType::indexValid(Index) here.
1912 // indexValid() always returns true for arrays because getelementptr allows
1913 // out-of-bounds indices. Since we don't allow those for extractvalue and
1914 // insertvalue we need to check array indexing manually.
1915 // Since the only other types we can index into are struct types it's just
1916 // as easy to check those manually as well.
1917 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1918 if (Index >= AT->getNumElements())
1920 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1921 if (Index >= ST->getNumElements())
1924 // Not a valid type to index into.
1928 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1930 return const_cast<Type*>(Agg);
1933 //===----------------------------------------------------------------------===//
1934 // BinaryOperator Class
1935 //===----------------------------------------------------------------------===//
1937 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1938 Type *Ty, const Twine &Name,
1939 Instruction *InsertBefore)
1940 : Instruction(Ty, iType,
1941 OperandTraits<BinaryOperator>::op_begin(this),
1942 OperandTraits<BinaryOperator>::operands(this),
1950 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1951 Type *Ty, const Twine &Name,
1952 BasicBlock *InsertAtEnd)
1953 : Instruction(Ty, iType,
1954 OperandTraits<BinaryOperator>::op_begin(this),
1955 OperandTraits<BinaryOperator>::operands(this),
1964 void BinaryOperator::init(BinaryOps iType) {
1965 Value *LHS = getOperand(0), *RHS = getOperand(1);
1966 (void)LHS; (void)RHS; // Silence warnings.
1967 assert(LHS->getType() == RHS->getType() &&
1968 "Binary operator operand types must match!");
1973 assert(getType() == LHS->getType() &&
1974 "Arithmetic operation should return same type as operands!");
1975 assert(getType()->isIntOrIntVectorTy() &&
1976 "Tried to create an integer operation on a non-integer type!");
1978 case FAdd: case FSub:
1980 assert(getType() == LHS->getType() &&
1981 "Arithmetic operation should return same type as operands!");
1982 assert(getType()->isFPOrFPVectorTy() &&
1983 "Tried to create a floating-point operation on a "
1984 "non-floating-point type!");
1988 assert(getType() == LHS->getType() &&
1989 "Arithmetic operation should return same type as operands!");
1990 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1991 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1992 "Incorrect operand type (not integer) for S/UDIV");
1995 assert(getType() == LHS->getType() &&
1996 "Arithmetic operation should return same type as operands!");
1997 assert(getType()->isFPOrFPVectorTy() &&
1998 "Incorrect operand type (not floating point) for FDIV");
2002 assert(getType() == LHS->getType() &&
2003 "Arithmetic operation should return same type as operands!");
2004 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2005 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2006 "Incorrect operand type (not integer) for S/UREM");
2009 assert(getType() == LHS->getType() &&
2010 "Arithmetic operation should return same type as operands!");
2011 assert(getType()->isFPOrFPVectorTy() &&
2012 "Incorrect operand type (not floating point) for FREM");
2017 assert(getType() == LHS->getType() &&
2018 "Shift operation should return same type as operands!");
2019 assert((getType()->isIntegerTy() ||
2020 (getType()->isVectorTy() &&
2021 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2022 "Tried to create a shift operation on a non-integral type!");
2026 assert(getType() == LHS->getType() &&
2027 "Logical operation should return same type as operands!");
2028 assert((getType()->isIntegerTy() ||
2029 (getType()->isVectorTy() &&
2030 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2031 "Tried to create a logical operation on a non-integral type!");
2039 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2041 Instruction *InsertBefore) {
2042 assert(S1->getType() == S2->getType() &&
2043 "Cannot create binary operator with two operands of differing type!");
2044 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2047 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2049 BasicBlock *InsertAtEnd) {
2050 BinaryOperator *Res = Create(Op, S1, S2, Name);
2051 InsertAtEnd->getInstList().push_back(Res);
2055 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2056 Instruction *InsertBefore) {
2057 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2058 return new BinaryOperator(Instruction::Sub,
2060 Op->getType(), Name, InsertBefore);
2063 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2064 BasicBlock *InsertAtEnd) {
2065 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2066 return new BinaryOperator(Instruction::Sub,
2068 Op->getType(), Name, InsertAtEnd);
2071 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2072 Instruction *InsertBefore) {
2073 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2074 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2077 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2078 BasicBlock *InsertAtEnd) {
2079 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2080 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2083 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2084 Instruction *InsertBefore) {
2085 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2086 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2089 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2090 BasicBlock *InsertAtEnd) {
2091 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2092 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2095 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2096 Instruction *InsertBefore) {
2097 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2098 return new BinaryOperator(Instruction::FSub, zero, Op,
2099 Op->getType(), Name, InsertBefore);
2102 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2103 BasicBlock *InsertAtEnd) {
2104 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2105 return new BinaryOperator(Instruction::FSub, zero, Op,
2106 Op->getType(), Name, InsertAtEnd);
2109 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2110 Instruction *InsertBefore) {
2111 Constant *C = Constant::getAllOnesValue(Op->getType());
2112 return new BinaryOperator(Instruction::Xor, Op, C,
2113 Op->getType(), Name, InsertBefore);
2116 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2117 BasicBlock *InsertAtEnd) {
2118 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2119 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2120 Op->getType(), Name, InsertAtEnd);
2124 // isConstantAllOnes - Helper function for several functions below
2125 static inline bool isConstantAllOnes(const Value *V) {
2126 if (const Constant *C = dyn_cast<Constant>(V))
2127 return C->isAllOnesValue();
2131 bool BinaryOperator::isNeg(const Value *V) {
2132 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2133 if (Bop->getOpcode() == Instruction::Sub)
2134 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2135 return C->isNegativeZeroValue();
2139 bool BinaryOperator::isFNeg(const Value *V) {
2140 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2141 if (Bop->getOpcode() == Instruction::FSub)
2142 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2143 return C->isNegativeZeroValue();
2147 bool BinaryOperator::isNot(const Value *V) {
2148 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2149 return (Bop->getOpcode() == Instruction::Xor &&
2150 (isConstantAllOnes(Bop->getOperand(1)) ||
2151 isConstantAllOnes(Bop->getOperand(0))));
2155 Value *BinaryOperator::getNegArgument(Value *BinOp) {
2156 return cast<BinaryOperator>(BinOp)->getOperand(1);
2159 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
2160 return getNegArgument(const_cast<Value*>(BinOp));
2163 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
2164 return cast<BinaryOperator>(BinOp)->getOperand(1);
2167 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
2168 return getFNegArgument(const_cast<Value*>(BinOp));
2171 Value *BinaryOperator::getNotArgument(Value *BinOp) {
2172 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
2173 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
2174 Value *Op0 = BO->getOperand(0);
2175 Value *Op1 = BO->getOperand(1);
2176 if (isConstantAllOnes(Op0)) return Op1;
2178 assert(isConstantAllOnes(Op1));
2182 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
2183 return getNotArgument(const_cast<Value*>(BinOp));
2187 // swapOperands - Exchange the two operands to this instruction. This
2188 // instruction is safe to use on any binary instruction and does not
2189 // modify the semantics of the instruction. If the instruction is
2190 // order dependent (SetLT f.e.) the opcode is changed.
2192 bool BinaryOperator::swapOperands() {
2193 if (!isCommutative())
2194 return true; // Can't commute operands
2195 Op<0>().swap(Op<1>());
2199 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2200 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2203 void BinaryOperator::setHasNoSignedWrap(bool b) {
2204 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2207 void BinaryOperator::setIsExact(bool b) {
2208 cast<PossiblyExactOperator>(this)->setIsExact(b);
2211 bool BinaryOperator::hasNoUnsignedWrap() const {
2212 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2215 bool BinaryOperator::hasNoSignedWrap() const {
2216 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2219 bool BinaryOperator::isExact() const {
2220 return cast<PossiblyExactOperator>(this)->isExact();
2223 //===----------------------------------------------------------------------===//
2224 // FPMathOperator Class
2225 //===----------------------------------------------------------------------===//
2227 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2228 /// An accuracy of 0.0 means that the operation should be performed with the
2229 /// default precision.
2230 float FPMathOperator::getFPAccuracy() const {
2232 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2235 ConstantFP *Accuracy = cast<ConstantFP>(MD->getOperand(0));
2236 return Accuracy->getValueAPF().convertToFloat();
2240 //===----------------------------------------------------------------------===//
2242 //===----------------------------------------------------------------------===//
2244 void CastInst::anchor() {}
2246 // Just determine if this cast only deals with integral->integral conversion.
2247 bool CastInst::isIntegerCast() const {
2248 switch (getOpcode()) {
2249 default: return false;
2250 case Instruction::ZExt:
2251 case Instruction::SExt:
2252 case Instruction::Trunc:
2254 case Instruction::BitCast:
2255 return getOperand(0)->getType()->isIntegerTy() &&
2256 getType()->isIntegerTy();
2260 bool CastInst::isLosslessCast() const {
2261 // Only BitCast can be lossless, exit fast if we're not BitCast
2262 if (getOpcode() != Instruction::BitCast)
2265 // Identity cast is always lossless
2266 Type* SrcTy = getOperand(0)->getType();
2267 Type* DstTy = getType();
2271 // Pointer to pointer is always lossless.
2272 if (SrcTy->isPointerTy())
2273 return DstTy->isPointerTy();
2274 return false; // Other types have no identity values
2277 /// This function determines if the CastInst does not require any bits to be
2278 /// changed in order to effect the cast. Essentially, it identifies cases where
2279 /// no code gen is necessary for the cast, hence the name no-op cast. For
2280 /// example, the following are all no-op casts:
2281 /// # bitcast i32* %x to i8*
2282 /// # bitcast <2 x i32> %x to <4 x i16>
2283 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2284 /// @brief Determine if the described cast is a no-op.
2285 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2290 default: llvm_unreachable("Invalid CastOp");
2291 case Instruction::Trunc:
2292 case Instruction::ZExt:
2293 case Instruction::SExt:
2294 case Instruction::FPTrunc:
2295 case Instruction::FPExt:
2296 case Instruction::UIToFP:
2297 case Instruction::SIToFP:
2298 case Instruction::FPToUI:
2299 case Instruction::FPToSI:
2300 return false; // These always modify bits
2301 case Instruction::BitCast:
2302 return true; // BitCast never modifies bits.
2303 case Instruction::PtrToInt:
2304 return IntPtrTy->getScalarSizeInBits() ==
2305 DestTy->getScalarSizeInBits();
2306 case Instruction::IntToPtr:
2307 return IntPtrTy->getScalarSizeInBits() ==
2308 SrcTy->getScalarSizeInBits();
2312 /// @brief Determine if a cast is a no-op.
2313 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2314 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2317 /// This function determines if a pair of casts can be eliminated and what
2318 /// opcode should be used in the elimination. This assumes that there are two
2319 /// instructions like this:
2320 /// * %F = firstOpcode SrcTy %x to MidTy
2321 /// * %S = secondOpcode MidTy %F to DstTy
2322 /// The function returns a resultOpcode so these two casts can be replaced with:
2323 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2324 /// If no such cast is permited, the function returns 0.
2325 unsigned CastInst::isEliminableCastPair(
2326 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2327 Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy) {
2328 // Define the 144 possibilities for these two cast instructions. The values
2329 // in this matrix determine what to do in a given situation and select the
2330 // case in the switch below. The rows correspond to firstOp, the columns
2331 // correspond to secondOp. In looking at the table below, keep in mind
2332 // the following cast properties:
2334 // Size Compare Source Destination
2335 // Operator Src ? Size Type Sign Type Sign
2336 // -------- ------------ ------------------- ---------------------
2337 // TRUNC > Integer Any Integral Any
2338 // ZEXT < Integral Unsigned Integer Any
2339 // SEXT < Integral Signed Integer Any
2340 // FPTOUI n/a FloatPt n/a Integral Unsigned
2341 // FPTOSI n/a FloatPt n/a Integral Signed
2342 // UITOFP n/a Integral Unsigned FloatPt n/a
2343 // SITOFP n/a Integral Signed FloatPt n/a
2344 // FPTRUNC > FloatPt n/a FloatPt n/a
2345 // FPEXT < FloatPt n/a FloatPt n/a
2346 // PTRTOINT n/a Pointer n/a Integral Unsigned
2347 // INTTOPTR n/a Integral Unsigned Pointer n/a
2348 // BITCAST = FirstClass n/a FirstClass n/a
2350 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2351 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2352 // into "fptoui double to i64", but this loses information about the range
2353 // of the produced value (we no longer know the top-part is all zeros).
2354 // Further this conversion is often much more expensive for typical hardware,
2355 // and causes issues when building libgcc. We disallow fptosi+sext for the
2357 const unsigned numCastOps =
2358 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2359 static const uint8_t CastResults[numCastOps][numCastOps] = {
2360 // T F F U S F F P I B -+
2361 // R Z S P P I I T P 2 N T |
2362 // U E E 2 2 2 2 R E I T C +- secondOp
2363 // N X X U S F F N X N 2 V |
2364 // C T T I I P P C T T P T -+
2365 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2366 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2367 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2368 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2369 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2370 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2371 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2372 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2373 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2374 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2375 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2376 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2379 // If either of the casts are a bitcast from scalar to vector, disallow the
2380 // merging. However, bitcast of A->B->A are allowed.
2381 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2382 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2383 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2385 // Check if any of the bitcasts convert scalars<->vectors.
2386 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2387 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2388 // Unless we are bitcasing to the original type, disallow optimizations.
2389 if (!chainedBitcast) return 0;
2391 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2392 [secondOp-Instruction::CastOpsBegin];
2395 // categorically disallowed
2398 // allowed, use first cast's opcode
2401 // allowed, use second cast's opcode
2404 // no-op cast in second op implies firstOp as long as the DestTy
2405 // is integer and we are not converting between a vector and a
2407 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2411 // no-op cast in second op implies firstOp as long as the DestTy
2412 // is floating point.
2413 if (DstTy->isFloatingPointTy())
2417 // no-op cast in first op implies secondOp as long as the SrcTy
2419 if (SrcTy->isIntegerTy())
2423 // no-op cast in first op implies secondOp as long as the SrcTy
2424 // is a floating point.
2425 if (SrcTy->isFloatingPointTy())
2429 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2432 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2433 unsigned MidSize = MidTy->getScalarSizeInBits();
2434 if (MidSize >= PtrSize)
2435 return Instruction::BitCast;
2439 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2440 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2441 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2442 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2443 unsigned DstSize = DstTy->getScalarSizeInBits();
2444 if (SrcSize == DstSize)
2445 return Instruction::BitCast;
2446 else if (SrcSize < DstSize)
2450 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2451 return Instruction::ZExt;
2453 // fpext followed by ftrunc is allowed if the bit size returned to is
2454 // the same as the original, in which case its just a bitcast
2456 return Instruction::BitCast;
2457 return 0; // If the types are not the same we can't eliminate it.
2459 // bitcast followed by ptrtoint is allowed as long as the bitcast
2460 // is a pointer to pointer cast.
2461 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2465 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2466 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2470 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2473 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2474 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2475 unsigned DstSize = DstTy->getScalarSizeInBits();
2476 if (SrcSize <= PtrSize && SrcSize == DstSize)
2477 return Instruction::BitCast;
2481 // cast combination can't happen (error in input). This is for all cases
2482 // where the MidTy is not the same for the two cast instructions.
2483 llvm_unreachable("Invalid Cast Combination");
2485 llvm_unreachable("Error in CastResults table!!!");
2489 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2490 const Twine &Name, Instruction *InsertBefore) {
2491 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2492 // Construct and return the appropriate CastInst subclass
2494 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2495 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2496 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2497 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2498 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2499 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2500 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2501 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2502 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2503 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2504 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2505 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2506 default: llvm_unreachable("Invalid opcode provided");
2510 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2511 const Twine &Name, BasicBlock *InsertAtEnd) {
2512 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2513 // Construct and return the appropriate CastInst subclass
2515 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2516 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2517 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2518 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2519 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2520 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2521 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2522 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2523 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2524 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2525 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2526 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2527 default: llvm_unreachable("Invalid opcode provided");
2531 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2533 Instruction *InsertBefore) {
2534 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2535 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2536 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2539 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2541 BasicBlock *InsertAtEnd) {
2542 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2543 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2544 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2547 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2549 Instruction *InsertBefore) {
2550 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2551 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2552 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2555 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2557 BasicBlock *InsertAtEnd) {
2558 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2559 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2560 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2563 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2565 Instruction *InsertBefore) {
2566 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2567 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2568 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2571 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2573 BasicBlock *InsertAtEnd) {
2574 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2575 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2576 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2579 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2581 BasicBlock *InsertAtEnd) {
2582 assert(S->getType()->isPointerTy() && "Invalid cast");
2583 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2586 if (Ty->isIntegerTy())
2587 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2588 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2591 /// @brief Create a BitCast or a PtrToInt cast instruction
2592 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2594 Instruction *InsertBefore) {
2595 assert(S->getType()->isPointerTy() && "Invalid cast");
2596 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2599 if (Ty->isIntegerTy())
2600 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2601 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2604 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2605 bool isSigned, const Twine &Name,
2606 Instruction *InsertBefore) {
2607 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2608 "Invalid integer cast");
2609 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2610 unsigned DstBits = Ty->getScalarSizeInBits();
2611 Instruction::CastOps opcode =
2612 (SrcBits == DstBits ? Instruction::BitCast :
2613 (SrcBits > DstBits ? Instruction::Trunc :
2614 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2615 return Create(opcode, C, Ty, Name, InsertBefore);
2618 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2619 bool isSigned, const Twine &Name,
2620 BasicBlock *InsertAtEnd) {
2621 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2623 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2624 unsigned DstBits = Ty->getScalarSizeInBits();
2625 Instruction::CastOps opcode =
2626 (SrcBits == DstBits ? Instruction::BitCast :
2627 (SrcBits > DstBits ? Instruction::Trunc :
2628 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2629 return Create(opcode, C, Ty, Name, InsertAtEnd);
2632 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2634 Instruction *InsertBefore) {
2635 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2637 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2638 unsigned DstBits = Ty->getScalarSizeInBits();
2639 Instruction::CastOps opcode =
2640 (SrcBits == DstBits ? Instruction::BitCast :
2641 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2642 return Create(opcode, C, Ty, Name, InsertBefore);
2645 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2647 BasicBlock *InsertAtEnd) {
2648 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2650 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2651 unsigned DstBits = Ty->getScalarSizeInBits();
2652 Instruction::CastOps opcode =
2653 (SrcBits == DstBits ? Instruction::BitCast :
2654 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2655 return Create(opcode, C, Ty, Name, InsertAtEnd);
2658 // Check whether it is valid to call getCastOpcode for these types.
2659 // This routine must be kept in sync with getCastOpcode.
2660 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2661 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2664 if (SrcTy == DestTy)
2667 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2668 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2669 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2670 // An element by element cast. Valid if casting the elements is valid.
2671 SrcTy = SrcVecTy->getElementType();
2672 DestTy = DestVecTy->getElementType();
2675 // Get the bit sizes, we'll need these
2676 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2677 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2679 // Run through the possibilities ...
2680 if (DestTy->isIntegerTy()) { // Casting to integral
2681 if (SrcTy->isIntegerTy()) { // Casting from integral
2683 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2685 } else if (SrcTy->isVectorTy()) { // Casting from vector
2686 return DestBits == SrcBits;
2687 } else { // Casting from something else
2688 return SrcTy->isPointerTy();
2690 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2691 if (SrcTy->isIntegerTy()) { // Casting from integral
2693 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2695 } else if (SrcTy->isVectorTy()) { // Casting from vector
2696 return DestBits == SrcBits;
2697 } else { // Casting from something else
2700 } else if (DestTy->isVectorTy()) { // Casting to vector
2701 return DestBits == SrcBits;
2702 } else if (DestTy->isPointerTy()) { // Casting to pointer
2703 if (SrcTy->isPointerTy()) { // Casting from pointer
2705 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2707 } else { // Casting from something else
2710 } else if (DestTy->isX86_MMXTy()) {
2711 if (SrcTy->isVectorTy()) {
2712 return DestBits == SrcBits; // 64-bit vector to MMX
2716 } else { // Casting to something else
2721 // Provide a way to get a "cast" where the cast opcode is inferred from the
2722 // types and size of the operand. This, basically, is a parallel of the
2723 // logic in the castIsValid function below. This axiom should hold:
2724 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2725 // should not assert in castIsValid. In other words, this produces a "correct"
2726 // casting opcode for the arguments passed to it.
2727 // This routine must be kept in sync with isCastable.
2728 Instruction::CastOps
2729 CastInst::getCastOpcode(
2730 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2731 Type *SrcTy = Src->getType();
2733 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2734 "Only first class types are castable!");
2736 if (SrcTy == DestTy)
2739 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2740 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2741 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2742 // An element by element cast. Find the appropriate opcode based on the
2744 SrcTy = SrcVecTy->getElementType();
2745 DestTy = DestVecTy->getElementType();
2748 // Get the bit sizes, we'll need these
2749 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2750 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2752 // Run through the possibilities ...
2753 if (DestTy->isIntegerTy()) { // Casting to integral
2754 if (SrcTy->isIntegerTy()) { // Casting from integral
2755 if (DestBits < SrcBits)
2756 return Trunc; // int -> smaller int
2757 else if (DestBits > SrcBits) { // its an extension
2759 return SExt; // signed -> SEXT
2761 return ZExt; // unsigned -> ZEXT
2763 return BitCast; // Same size, No-op cast
2765 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2767 return FPToSI; // FP -> sint
2769 return FPToUI; // FP -> uint
2770 } else if (SrcTy->isVectorTy()) {
2771 assert(DestBits == SrcBits &&
2772 "Casting vector to integer of different width");
2773 return BitCast; // Same size, no-op cast
2775 assert(SrcTy->isPointerTy() &&
2776 "Casting from a value that is not first-class type");
2777 return PtrToInt; // ptr -> int
2779 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2780 if (SrcTy->isIntegerTy()) { // Casting from integral
2782 return SIToFP; // sint -> FP
2784 return UIToFP; // uint -> FP
2785 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2786 if (DestBits < SrcBits) {
2787 return FPTrunc; // FP -> smaller FP
2788 } else if (DestBits > SrcBits) {
2789 return FPExt; // FP -> larger FP
2791 return BitCast; // same size, no-op cast
2793 } else if (SrcTy->isVectorTy()) {
2794 assert(DestBits == SrcBits &&
2795 "Casting vector to floating point of different width");
2796 return BitCast; // same size, no-op cast
2798 llvm_unreachable("Casting pointer or non-first class to float");
2799 } else if (DestTy->isVectorTy()) {
2800 assert(DestBits == SrcBits &&
2801 "Illegal cast to vector (wrong type or size)");
2803 } else if (DestTy->isPointerTy()) {
2804 if (SrcTy->isPointerTy()) {
2805 return BitCast; // ptr -> ptr
2806 } else if (SrcTy->isIntegerTy()) {
2807 return IntToPtr; // int -> ptr
2809 llvm_unreachable("Casting pointer to other than pointer or int");
2810 } else if (DestTy->isX86_MMXTy()) {
2811 if (SrcTy->isVectorTy()) {
2812 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2813 return BitCast; // 64-bit vector to MMX
2815 llvm_unreachable("Illegal cast to X86_MMX");
2817 llvm_unreachable("Casting to type that is not first-class");
2820 //===----------------------------------------------------------------------===//
2821 // CastInst SubClass Constructors
2822 //===----------------------------------------------------------------------===//
2824 /// Check that the construction parameters for a CastInst are correct. This
2825 /// could be broken out into the separate constructors but it is useful to have
2826 /// it in one place and to eliminate the redundant code for getting the sizes
2827 /// of the types involved.
2829 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2831 // Check for type sanity on the arguments
2832 Type *SrcTy = S->getType();
2833 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2834 SrcTy->isAggregateType() || DstTy->isAggregateType())
2837 // Get the size of the types in bits, we'll need this later
2838 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2839 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2841 // If these are vector types, get the lengths of the vectors (using zero for
2842 // scalar types means that checking that vector lengths match also checks that
2843 // scalars are not being converted to vectors or vectors to scalars).
2844 unsigned SrcLength = SrcTy->isVectorTy() ?
2845 cast<VectorType>(SrcTy)->getNumElements() : 0;
2846 unsigned DstLength = DstTy->isVectorTy() ?
2847 cast<VectorType>(DstTy)->getNumElements() : 0;
2849 // Switch on the opcode provided
2851 default: return false; // This is an input error
2852 case Instruction::Trunc:
2853 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2854 SrcLength == DstLength && SrcBitSize > DstBitSize;
2855 case Instruction::ZExt:
2856 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2857 SrcLength == DstLength && SrcBitSize < DstBitSize;
2858 case Instruction::SExt:
2859 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2860 SrcLength == DstLength && SrcBitSize < DstBitSize;
2861 case Instruction::FPTrunc:
2862 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2863 SrcLength == DstLength && SrcBitSize > DstBitSize;
2864 case Instruction::FPExt:
2865 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2866 SrcLength == DstLength && SrcBitSize < DstBitSize;
2867 case Instruction::UIToFP:
2868 case Instruction::SIToFP:
2869 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2870 SrcLength == DstLength;
2871 case Instruction::FPToUI:
2872 case Instruction::FPToSI:
2873 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2874 SrcLength == DstLength;
2875 case Instruction::PtrToInt:
2876 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2878 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2879 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2881 return SrcTy->getScalarType()->isPointerTy() &&
2882 DstTy->getScalarType()->isIntegerTy();
2883 case Instruction::IntToPtr:
2884 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2886 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2887 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2889 return SrcTy->getScalarType()->isIntegerTy() &&
2890 DstTy->getScalarType()->isPointerTy();
2891 case Instruction::BitCast:
2892 // BitCast implies a no-op cast of type only. No bits change.
2893 // However, you can't cast pointers to anything but pointers.
2894 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2897 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2898 // these cases, the cast is okay if the source and destination bit widths
2900 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2904 TruncInst::TruncInst(
2905 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2906 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2907 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2910 TruncInst::TruncInst(
2911 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2912 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2913 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2917 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2918 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2919 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2923 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2924 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2925 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2928 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2929 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2930 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2934 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2935 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2936 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2939 FPTruncInst::FPTruncInst(
2940 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2941 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2942 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2945 FPTruncInst::FPTruncInst(
2946 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2947 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2948 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2951 FPExtInst::FPExtInst(
2952 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2953 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2954 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2957 FPExtInst::FPExtInst(
2958 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2959 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2960 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2963 UIToFPInst::UIToFPInst(
2964 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2965 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2966 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2969 UIToFPInst::UIToFPInst(
2970 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2971 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2972 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2975 SIToFPInst::SIToFPInst(
2976 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2977 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2978 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2981 SIToFPInst::SIToFPInst(
2982 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2983 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2984 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2987 FPToUIInst::FPToUIInst(
2988 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2989 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2990 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2993 FPToUIInst::FPToUIInst(
2994 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2995 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2996 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2999 FPToSIInst::FPToSIInst(
3000 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3001 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3002 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3005 FPToSIInst::FPToSIInst(
3006 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3007 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3008 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3011 PtrToIntInst::PtrToIntInst(
3012 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3013 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3014 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3017 PtrToIntInst::PtrToIntInst(
3018 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3019 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3020 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3023 IntToPtrInst::IntToPtrInst(
3024 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3025 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3026 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3029 IntToPtrInst::IntToPtrInst(
3030 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3031 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3032 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3035 BitCastInst::BitCastInst(
3036 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3037 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3038 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3041 BitCastInst::BitCastInst(
3042 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3043 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3044 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3047 //===----------------------------------------------------------------------===//
3049 //===----------------------------------------------------------------------===//
3051 void CmpInst::anchor() {}
3053 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3054 Value *LHS, Value *RHS, const Twine &Name,
3055 Instruction *InsertBefore)
3056 : Instruction(ty, op,
3057 OperandTraits<CmpInst>::op_begin(this),
3058 OperandTraits<CmpInst>::operands(this),
3062 setPredicate((Predicate)predicate);
3066 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3067 Value *LHS, Value *RHS, const Twine &Name,
3068 BasicBlock *InsertAtEnd)
3069 : Instruction(ty, op,
3070 OperandTraits<CmpInst>::op_begin(this),
3071 OperandTraits<CmpInst>::operands(this),
3075 setPredicate((Predicate)predicate);
3080 CmpInst::Create(OtherOps Op, unsigned short predicate,
3081 Value *S1, Value *S2,
3082 const Twine &Name, Instruction *InsertBefore) {
3083 if (Op == Instruction::ICmp) {
3085 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3088 return new ICmpInst(CmpInst::Predicate(predicate),
3093 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3096 return new FCmpInst(CmpInst::Predicate(predicate),
3101 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
3102 const Twine &Name, BasicBlock *InsertAtEnd) {
3103 if (Op == Instruction::ICmp) {
3104 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3107 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3111 void CmpInst::swapOperands() {
3112 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3115 cast<FCmpInst>(this)->swapOperands();
3118 bool CmpInst::isCommutative() const {
3119 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3120 return IC->isCommutative();
3121 return cast<FCmpInst>(this)->isCommutative();
3124 bool CmpInst::isEquality() const {
3125 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3126 return IC->isEquality();
3127 return cast<FCmpInst>(this)->isEquality();
3131 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3133 default: llvm_unreachable("Unknown cmp predicate!");
3134 case ICMP_EQ: return ICMP_NE;
3135 case ICMP_NE: return ICMP_EQ;
3136 case ICMP_UGT: return ICMP_ULE;
3137 case ICMP_ULT: return ICMP_UGE;
3138 case ICMP_UGE: return ICMP_ULT;
3139 case ICMP_ULE: return ICMP_UGT;
3140 case ICMP_SGT: return ICMP_SLE;
3141 case ICMP_SLT: return ICMP_SGE;
3142 case ICMP_SGE: return ICMP_SLT;
3143 case ICMP_SLE: return ICMP_SGT;
3145 case FCMP_OEQ: return FCMP_UNE;
3146 case FCMP_ONE: return FCMP_UEQ;
3147 case FCMP_OGT: return FCMP_ULE;
3148 case FCMP_OLT: return FCMP_UGE;
3149 case FCMP_OGE: return FCMP_ULT;
3150 case FCMP_OLE: return FCMP_UGT;
3151 case FCMP_UEQ: return FCMP_ONE;
3152 case FCMP_UNE: return FCMP_OEQ;
3153 case FCMP_UGT: return FCMP_OLE;
3154 case FCMP_ULT: return FCMP_OGE;
3155 case FCMP_UGE: return FCMP_OLT;
3156 case FCMP_ULE: return FCMP_OGT;
3157 case FCMP_ORD: return FCMP_UNO;
3158 case FCMP_UNO: return FCMP_ORD;
3159 case FCMP_TRUE: return FCMP_FALSE;
3160 case FCMP_FALSE: return FCMP_TRUE;
3164 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3166 default: llvm_unreachable("Unknown icmp predicate!");
3167 case ICMP_EQ: case ICMP_NE:
3168 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3170 case ICMP_UGT: return ICMP_SGT;
3171 case ICMP_ULT: return ICMP_SLT;
3172 case ICMP_UGE: return ICMP_SGE;
3173 case ICMP_ULE: return ICMP_SLE;
3177 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3179 default: llvm_unreachable("Unknown icmp predicate!");
3180 case ICMP_EQ: case ICMP_NE:
3181 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3183 case ICMP_SGT: return ICMP_UGT;
3184 case ICMP_SLT: return ICMP_ULT;
3185 case ICMP_SGE: return ICMP_UGE;
3186 case ICMP_SLE: return ICMP_ULE;
3190 /// Initialize a set of values that all satisfy the condition with C.
3193 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3196 uint32_t BitWidth = C.getBitWidth();
3198 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3199 case ICmpInst::ICMP_EQ: Upper++; break;
3200 case ICmpInst::ICMP_NE: Lower++; break;
3201 case ICmpInst::ICMP_ULT:
3202 Lower = APInt::getMinValue(BitWidth);
3203 // Check for an empty-set condition.
3205 return ConstantRange(BitWidth, /*isFullSet=*/false);
3207 case ICmpInst::ICMP_SLT:
3208 Lower = APInt::getSignedMinValue(BitWidth);
3209 // Check for an empty-set condition.
3211 return ConstantRange(BitWidth, /*isFullSet=*/false);
3213 case ICmpInst::ICMP_UGT:
3214 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3215 // Check for an empty-set condition.
3217 return ConstantRange(BitWidth, /*isFullSet=*/false);
3219 case ICmpInst::ICMP_SGT:
3220 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3221 // Check for an empty-set condition.
3223 return ConstantRange(BitWidth, /*isFullSet=*/false);
3225 case ICmpInst::ICMP_ULE:
3226 Lower = APInt::getMinValue(BitWidth); Upper++;
3227 // Check for a full-set condition.
3229 return ConstantRange(BitWidth, /*isFullSet=*/true);
3231 case ICmpInst::ICMP_SLE:
3232 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
3233 // Check for a full-set condition.
3235 return ConstantRange(BitWidth, /*isFullSet=*/true);
3237 case ICmpInst::ICMP_UGE:
3238 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3239 // Check for a full-set condition.
3241 return ConstantRange(BitWidth, /*isFullSet=*/true);
3243 case ICmpInst::ICMP_SGE:
3244 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3245 // Check for a full-set condition.
3247 return ConstantRange(BitWidth, /*isFullSet=*/true);
3250 return ConstantRange(Lower, Upper);
3253 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3255 default: llvm_unreachable("Unknown cmp predicate!");
3256 case ICMP_EQ: case ICMP_NE:
3258 case ICMP_SGT: return ICMP_SLT;
3259 case ICMP_SLT: return ICMP_SGT;
3260 case ICMP_SGE: return ICMP_SLE;
3261 case ICMP_SLE: return ICMP_SGE;
3262 case ICMP_UGT: return ICMP_ULT;
3263 case ICMP_ULT: return ICMP_UGT;
3264 case ICMP_UGE: return ICMP_ULE;
3265 case ICMP_ULE: return ICMP_UGE;
3267 case FCMP_FALSE: case FCMP_TRUE:
3268 case FCMP_OEQ: case FCMP_ONE:
3269 case FCMP_UEQ: case FCMP_UNE:
3270 case FCMP_ORD: case FCMP_UNO:
3272 case FCMP_OGT: return FCMP_OLT;
3273 case FCMP_OLT: return FCMP_OGT;
3274 case FCMP_OGE: return FCMP_OLE;
3275 case FCMP_OLE: return FCMP_OGE;
3276 case FCMP_UGT: return FCMP_ULT;
3277 case FCMP_ULT: return FCMP_UGT;
3278 case FCMP_UGE: return FCMP_ULE;
3279 case FCMP_ULE: return FCMP_UGE;
3283 bool CmpInst::isUnsigned(unsigned short predicate) {
3284 switch (predicate) {
3285 default: return false;
3286 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3287 case ICmpInst::ICMP_UGE: return true;
3291 bool CmpInst::isSigned(unsigned short predicate) {
3292 switch (predicate) {
3293 default: return false;
3294 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3295 case ICmpInst::ICMP_SGE: return true;
3299 bool CmpInst::isOrdered(unsigned short predicate) {
3300 switch (predicate) {
3301 default: return false;
3302 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3303 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3304 case FCmpInst::FCMP_ORD: return true;
3308 bool CmpInst::isUnordered(unsigned short predicate) {
3309 switch (predicate) {
3310 default: return false;
3311 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3312 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3313 case FCmpInst::FCMP_UNO: return true;
3317 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3319 default: return false;
3320 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3321 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3325 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3327 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3328 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3329 default: return false;
3334 //===----------------------------------------------------------------------===//
3335 // SwitchInst Implementation
3336 //===----------------------------------------------------------------------===//
3338 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3339 assert(Value && Default && NumReserved);
3340 ReservedSpace = NumReserved;
3342 OperandList = allocHungoffUses(ReservedSpace);
3344 OperandList[0] = Value;
3345 OperandList[1] = Default;
3348 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3349 /// switch on and a default destination. The number of additional cases can
3350 /// be specified here to make memory allocation more efficient. This
3351 /// constructor can also autoinsert before another instruction.
3352 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3353 Instruction *InsertBefore)
3354 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3355 0, 0, InsertBefore) {
3356 init(Value, Default, 2+NumCases*2);
3359 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3360 /// switch on and a default destination. The number of additional cases can
3361 /// be specified here to make memory allocation more efficient. This
3362 /// constructor also autoinserts at the end of the specified BasicBlock.
3363 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3364 BasicBlock *InsertAtEnd)
3365 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3366 0, 0, InsertAtEnd) {
3367 init(Value, Default, 2+NumCases*2);
3370 SwitchInst::SwitchInst(const SwitchInst &SI)
3371 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3372 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3373 NumOperands = SI.getNumOperands();
3374 Use *OL = OperandList, *InOL = SI.OperandList;
3375 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3377 OL[i+1] = InOL[i+1];
3379 TheSubsets = SI.TheSubsets;
3380 SubclassOptionalData = SI.SubclassOptionalData;
3383 SwitchInst::~SwitchInst() {
3388 /// addCase - Add an entry to the switch instruction...
3390 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3391 IntegersSubsetToBB Mapping;
3393 // FIXME: Currently we work with ConstantInt based cases.
3394 // So inititalize IntItem container directly from ConstantInt.
3395 Mapping.add(IntItem::fromConstantInt(OnVal));
3396 IntegersSubset CaseRanges = Mapping.getCase();
3397 addCase(CaseRanges, Dest);
3400 void SwitchInst::addCase(IntegersSubset& OnVal, BasicBlock *Dest) {
3401 unsigned NewCaseIdx = getNumCases();
3402 unsigned OpNo = NumOperands;
3403 if (OpNo+2 > ReservedSpace)
3404 growOperands(); // Get more space!
3405 // Initialize some new operands.
3406 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3407 NumOperands = OpNo+2;
3409 SubsetsIt TheSubsetsIt = TheSubsets.insert(TheSubsets.end(), OnVal);
3411 CaseIt Case(this, NewCaseIdx, TheSubsetsIt);
3412 Case.updateCaseValueOperand(OnVal);
3413 Case.setSuccessor(Dest);
3416 /// removeCase - This method removes the specified case and its successor
3417 /// from the switch instruction.
3418 void SwitchInst::removeCase(CaseIt& i) {
3419 unsigned idx = i.getCaseIndex();
3421 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3423 unsigned NumOps = getNumOperands();
3424 Use *OL = OperandList;
3426 // Overwrite this case with the end of the list.
3427 if (2 + (idx + 1) * 2 != NumOps) {
3428 OL[2 + idx * 2] = OL[NumOps - 2];
3429 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3432 // Nuke the last value.
3433 OL[NumOps-2].set(0);
3434 OL[NumOps-2+1].set(0);
3436 // Do the same with TheCases collection:
3437 if (i.SubsetIt != --TheSubsets.end()) {
3438 *i.SubsetIt = TheSubsets.back();
3439 TheSubsets.pop_back();
3441 TheSubsets.pop_back();
3442 i.SubsetIt = TheSubsets.end();
3445 NumOperands = NumOps-2;
3448 /// growOperands - grow operands - This grows the operand list in response
3449 /// to a push_back style of operation. This grows the number of ops by 3 times.
3451 void SwitchInst::growOperands() {
3452 unsigned e = getNumOperands();
3453 unsigned NumOps = e*3;
3455 ReservedSpace = NumOps;
3456 Use *NewOps = allocHungoffUses(NumOps);
3457 Use *OldOps = OperandList;
3458 for (unsigned i = 0; i != e; ++i) {
3459 NewOps[i] = OldOps[i];
3461 OperandList = NewOps;
3462 Use::zap(OldOps, OldOps + e, true);
3466 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3467 return getSuccessor(idx);
3469 unsigned SwitchInst::getNumSuccessorsV() const {
3470 return getNumSuccessors();
3472 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3473 setSuccessor(idx, B);
3476 //===----------------------------------------------------------------------===//
3477 // IndirectBrInst Implementation
3478 //===----------------------------------------------------------------------===//
3480 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3481 assert(Address && Address->getType()->isPointerTy() &&
3482 "Address of indirectbr must be a pointer");
3483 ReservedSpace = 1+NumDests;
3485 OperandList = allocHungoffUses(ReservedSpace);
3487 OperandList[0] = Address;
3491 /// growOperands - grow operands - This grows the operand list in response
3492 /// to a push_back style of operation. This grows the number of ops by 2 times.
3494 void IndirectBrInst::growOperands() {
3495 unsigned e = getNumOperands();
3496 unsigned NumOps = e*2;
3498 ReservedSpace = NumOps;
3499 Use *NewOps = allocHungoffUses(NumOps);
3500 Use *OldOps = OperandList;
3501 for (unsigned i = 0; i != e; ++i)
3502 NewOps[i] = OldOps[i];
3503 OperandList = NewOps;
3504 Use::zap(OldOps, OldOps + e, true);
3507 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3508 Instruction *InsertBefore)
3509 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3510 0, 0, InsertBefore) {
3511 init(Address, NumCases);
3514 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3515 BasicBlock *InsertAtEnd)
3516 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3517 0, 0, InsertAtEnd) {
3518 init(Address, NumCases);
3521 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3522 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3523 allocHungoffUses(IBI.getNumOperands()),
3524 IBI.getNumOperands()) {
3525 Use *OL = OperandList, *InOL = IBI.OperandList;
3526 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3528 SubclassOptionalData = IBI.SubclassOptionalData;
3531 IndirectBrInst::~IndirectBrInst() {
3535 /// addDestination - Add a destination.
3537 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3538 unsigned OpNo = NumOperands;
3539 if (OpNo+1 > ReservedSpace)
3540 growOperands(); // Get more space!
3541 // Initialize some new operands.
3542 assert(OpNo < ReservedSpace && "Growing didn't work!");
3543 NumOperands = OpNo+1;
3544 OperandList[OpNo] = DestBB;
3547 /// removeDestination - This method removes the specified successor from the
3548 /// indirectbr instruction.
3549 void IndirectBrInst::removeDestination(unsigned idx) {
3550 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3552 unsigned NumOps = getNumOperands();
3553 Use *OL = OperandList;
3555 // Replace this value with the last one.
3556 OL[idx+1] = OL[NumOps-1];
3558 // Nuke the last value.
3559 OL[NumOps-1].set(0);
3560 NumOperands = NumOps-1;
3563 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3564 return getSuccessor(idx);
3566 unsigned IndirectBrInst::getNumSuccessorsV() const {
3567 return getNumSuccessors();
3569 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3570 setSuccessor(idx, B);
3573 //===----------------------------------------------------------------------===//
3574 // clone_impl() implementations
3575 //===----------------------------------------------------------------------===//
3577 // Define these methods here so vtables don't get emitted into every translation
3578 // unit that uses these classes.
3580 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3581 return new (getNumOperands()) GetElementPtrInst(*this);
3584 BinaryOperator *BinaryOperator::clone_impl() const {
3585 return Create(getOpcode(), Op<0>(), Op<1>());
3588 FCmpInst* FCmpInst::clone_impl() const {
3589 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3592 ICmpInst* ICmpInst::clone_impl() const {
3593 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3596 ExtractValueInst *ExtractValueInst::clone_impl() const {
3597 return new ExtractValueInst(*this);
3600 InsertValueInst *InsertValueInst::clone_impl() const {
3601 return new InsertValueInst(*this);
3604 AllocaInst *AllocaInst::clone_impl() const {
3605 return new AllocaInst(getAllocatedType(),
3606 (Value*)getOperand(0),
3610 LoadInst *LoadInst::clone_impl() const {
3611 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3612 getAlignment(), getOrdering(), getSynchScope());
3615 StoreInst *StoreInst::clone_impl() const {
3616 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3617 getAlignment(), getOrdering(), getSynchScope());
3621 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3622 AtomicCmpXchgInst *Result =
3623 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3624 getOrdering(), getSynchScope());
3625 Result->setVolatile(isVolatile());
3629 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3630 AtomicRMWInst *Result =
3631 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3632 getOrdering(), getSynchScope());
3633 Result->setVolatile(isVolatile());
3637 FenceInst *FenceInst::clone_impl() const {
3638 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3641 TruncInst *TruncInst::clone_impl() const {
3642 return new TruncInst(getOperand(0), getType());
3645 ZExtInst *ZExtInst::clone_impl() const {
3646 return new ZExtInst(getOperand(0), getType());
3649 SExtInst *SExtInst::clone_impl() const {
3650 return new SExtInst(getOperand(0), getType());
3653 FPTruncInst *FPTruncInst::clone_impl() const {
3654 return new FPTruncInst(getOperand(0), getType());
3657 FPExtInst *FPExtInst::clone_impl() const {
3658 return new FPExtInst(getOperand(0), getType());
3661 UIToFPInst *UIToFPInst::clone_impl() const {
3662 return new UIToFPInst(getOperand(0), getType());
3665 SIToFPInst *SIToFPInst::clone_impl() const {
3666 return new SIToFPInst(getOperand(0), getType());
3669 FPToUIInst *FPToUIInst::clone_impl() const {
3670 return new FPToUIInst(getOperand(0), getType());
3673 FPToSIInst *FPToSIInst::clone_impl() const {
3674 return new FPToSIInst(getOperand(0), getType());
3677 PtrToIntInst *PtrToIntInst::clone_impl() const {
3678 return new PtrToIntInst(getOperand(0), getType());
3681 IntToPtrInst *IntToPtrInst::clone_impl() const {
3682 return new IntToPtrInst(getOperand(0), getType());
3685 BitCastInst *BitCastInst::clone_impl() const {
3686 return new BitCastInst(getOperand(0), getType());
3689 CallInst *CallInst::clone_impl() const {
3690 return new(getNumOperands()) CallInst(*this);
3693 SelectInst *SelectInst::clone_impl() const {
3694 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3697 VAArgInst *VAArgInst::clone_impl() const {
3698 return new VAArgInst(getOperand(0), getType());
3701 ExtractElementInst *ExtractElementInst::clone_impl() const {
3702 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3705 InsertElementInst *InsertElementInst::clone_impl() const {
3706 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3709 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3710 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3713 PHINode *PHINode::clone_impl() const {
3714 return new PHINode(*this);
3717 LandingPadInst *LandingPadInst::clone_impl() const {
3718 return new LandingPadInst(*this);
3721 ReturnInst *ReturnInst::clone_impl() const {
3722 return new(getNumOperands()) ReturnInst(*this);
3725 BranchInst *BranchInst::clone_impl() const {
3726 return new(getNumOperands()) BranchInst(*this);
3729 SwitchInst *SwitchInst::clone_impl() const {
3730 return new SwitchInst(*this);
3733 IndirectBrInst *IndirectBrInst::clone_impl() const {
3734 return new IndirectBrInst(*this);
3738 InvokeInst *InvokeInst::clone_impl() const {
3739 return new(getNumOperands()) InvokeInst(*this);
3742 ResumeInst *ResumeInst::clone_impl() const {
3743 return new(1) ResumeInst(*this);
3746 UnreachableInst *UnreachableInst::clone_impl() const {
3747 LLVMContext &Context = getContext();
3748 return new UnreachableInst(Context);