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/Analysis/Dominators.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/CallSite.h"
25 #include "llvm/Support/ConstantRange.h"
26 #include "llvm/Support/MathExtras.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 #define CALLSITE_DELEGATE_GETTER(METHOD) \
34 Instruction *II(getInstruction()); \
36 ? cast<CallInst>(II)->METHOD \
37 : cast<InvokeInst>(II)->METHOD
39 #define CALLSITE_DELEGATE_SETTER(METHOD) \
40 Instruction *II(getInstruction()); \
42 cast<CallInst>(II)->METHOD; \
44 cast<InvokeInst>(II)->METHOD
46 CallSite::CallSite(Instruction *C) {
47 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
49 I.setInt(isa<CallInst>(C));
51 CallingConv::ID CallSite::getCallingConv() const {
52 CALLSITE_DELEGATE_GETTER(getCallingConv());
54 void CallSite::setCallingConv(CallingConv::ID CC) {
55 CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
57 const AttrListPtr &CallSite::getAttributes() const {
58 CALLSITE_DELEGATE_GETTER(getAttributes());
60 void CallSite::setAttributes(const AttrListPtr &PAL) {
61 CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
63 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
64 CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
66 uint16_t CallSite::getParamAlignment(uint16_t i) const {
67 CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
69 bool CallSite::doesNotAccessMemory() const {
70 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
72 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
73 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
75 bool CallSite::onlyReadsMemory() const {
76 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
78 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
79 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
81 bool CallSite::doesNotReturn() const {
82 CALLSITE_DELEGATE_GETTER(doesNotReturn());
84 void CallSite::setDoesNotReturn(bool doesNotReturn) {
85 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
87 bool CallSite::doesNotThrow() const {
88 CALLSITE_DELEGATE_GETTER(doesNotThrow());
90 void CallSite::setDoesNotThrow(bool doesNotThrow) {
91 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
94 bool CallSite::hasArgument(const Value *Arg) const {
95 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
101 User::op_iterator CallSite::getCallee() const {
102 Instruction *II(getInstruction());
104 ? cast<CallInst>(II)->op_begin()
105 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Function
108 #undef CALLSITE_DELEGATE_GETTER
109 #undef CALLSITE_DELEGATE_SETTER
111 //===----------------------------------------------------------------------===//
112 // TerminatorInst Class
113 //===----------------------------------------------------------------------===//
115 // Out of line virtual method, so the vtable, etc has a home.
116 TerminatorInst::~TerminatorInst() {
119 //===----------------------------------------------------------------------===//
120 // UnaryInstruction Class
121 //===----------------------------------------------------------------------===//
123 // Out of line virtual method, so the vtable, etc has a home.
124 UnaryInstruction::~UnaryInstruction() {
127 //===----------------------------------------------------------------------===//
129 //===----------------------------------------------------------------------===//
131 /// areInvalidOperands - Return a string if the specified operands are invalid
132 /// for a select operation, otherwise return null.
133 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
134 if (Op1->getType() != Op2->getType())
135 return "both values to select must have same type";
137 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
139 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
140 return "vector select condition element type must be i1";
141 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
143 return "selected values for vector select must be vectors";
144 if (ET->getNumElements() != VT->getNumElements())
145 return "vector select requires selected vectors to have "
146 "the same vector length as select condition";
147 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
148 return "select condition must be i1 or <n x i1>";
154 //===----------------------------------------------------------------------===//
156 //===----------------------------------------------------------------------===//
158 PHINode::PHINode(const PHINode &PN)
159 : Instruction(PN.getType(), Instruction::PHI,
160 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
161 ReservedSpace(PN.getNumOperands()) {
162 Use *OL = OperandList;
163 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
164 OL[i] = PN.getOperand(i);
165 OL[i+1] = PN.getOperand(i+1);
167 SubclassOptionalData = PN.SubclassOptionalData;
170 PHINode::~PHINode() {
172 dropHungoffUses(OperandList);
175 // removeIncomingValue - Remove an incoming value. This is useful if a
176 // predecessor basic block is deleted.
177 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
178 unsigned NumOps = getNumOperands();
179 Use *OL = OperandList;
180 assert(Idx*2 < NumOps && "BB not in PHI node!");
181 Value *Removed = OL[Idx*2];
183 // Move everything after this operand down.
185 // FIXME: we could just swap with the end of the list, then erase. However,
186 // client might not expect this to happen. The code as it is thrashes the
187 // use/def lists, which is kinda lame.
188 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
193 // Nuke the last value.
195 OL[NumOps-2+1].set(0);
196 NumOperands = NumOps-2;
198 // If the PHI node is dead, because it has zero entries, nuke it now.
199 if (NumOps == 2 && DeletePHIIfEmpty) {
200 // If anyone is using this PHI, make them use a dummy value instead...
201 replaceAllUsesWith(UndefValue::get(getType()));
207 /// resizeOperands - resize operands - This adjusts the length of the operands
208 /// list according to the following behavior:
209 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
210 /// of operation. This grows the number of ops by 1.5 times.
211 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
212 /// 3. If NumOps == NumOperands, trim the reserved space.
214 void PHINode::resizeOperands(unsigned NumOps) {
215 unsigned e = getNumOperands();
218 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
219 } else if (NumOps*2 > NumOperands) {
221 if (ReservedSpace >= NumOps) return;
222 } else if (NumOps == NumOperands) {
223 if (ReservedSpace == NumOps) return;
228 ReservedSpace = NumOps;
229 Use *OldOps = OperandList;
230 Use *NewOps = allocHungoffUses(NumOps);
231 std::copy(OldOps, OldOps + e, NewOps);
232 OperandList = NewOps;
233 if (OldOps) Use::zap(OldOps, OldOps + e, true);
236 /// hasConstantValue - If the specified PHI node always merges together the same
237 /// value, return the value, otherwise return null.
239 /// If the PHI has undef operands, but all the rest of the operands are
240 /// some unique value, return that value if it can be proved that the
241 /// value dominates the PHI. If DT is null, use a conservative check,
242 /// otherwise use DT to test for dominance.
244 Value *PHINode::hasConstantValue(DominatorTree *DT) const {
245 // If the PHI node only has one incoming value, eliminate the PHI node.
246 if (getNumIncomingValues() == 1) {
247 if (getIncomingValue(0) != this) // not X = phi X
248 return getIncomingValue(0);
249 return UndefValue::get(getType()); // Self cycle is dead.
252 // Otherwise if all of the incoming values are the same for the PHI, replace
253 // the PHI node with the incoming value.
256 bool HasUndefInput = false;
257 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
258 if (isa<UndefValue>(getIncomingValue(i))) {
259 HasUndefInput = true;
260 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
261 if (InVal && getIncomingValue(i) != InVal)
262 return 0; // Not the same, bail out.
263 InVal = getIncomingValue(i);
266 // The only case that could cause InVal to be null is if we have a PHI node
267 // that only has entries for itself. In this case, there is no entry into the
268 // loop, so kill the PHI.
270 if (InVal == 0) InVal = UndefValue::get(getType());
272 // If we have a PHI node like phi(X, undef, X), where X is defined by some
273 // instruction, we cannot always return X as the result of the PHI node. Only
274 // do this if X is not an instruction (thus it must dominate the PHI block),
275 // or if the client is prepared to deal with this possibility.
276 if (!HasUndefInput || !isa<Instruction>(InVal))
279 Instruction *IV = cast<Instruction>(InVal);
281 // We have a DominatorTree. Do a precise test.
282 if (!DT->dominates(IV, this))
285 // If it is in the entry block, it obviously dominates everything.
286 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
288 return 0; // Cannot guarantee that InVal dominates this PHINode.
291 // All of the incoming values are the same, return the value now.
296 //===----------------------------------------------------------------------===//
297 // CallInst Implementation
298 //===----------------------------------------------------------------------===//
300 CallInst::~CallInst() {
303 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
304 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
305 Use *OL = OperandList;
308 const FunctionType *FTy =
309 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
310 FTy = FTy; // silence warning.
312 assert((NumParams == FTy->getNumParams() ||
313 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
314 "Calling a function with bad signature!");
315 for (unsigned i = 0; i != NumParams; ++i) {
316 assert((i >= FTy->getNumParams() ||
317 FTy->getParamType(i) == Params[i]->getType()) &&
318 "Calling a function with a bad signature!");
323 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
324 assert(NumOperands == 3 && "NumOperands not set up?");
325 Use *OL = OperandList;
330 const FunctionType *FTy =
331 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
332 FTy = FTy; // silence warning.
334 assert((FTy->getNumParams() == 2 ||
335 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
336 "Calling a function with bad signature");
337 assert((0 >= FTy->getNumParams() ||
338 FTy->getParamType(0) == Actual1->getType()) &&
339 "Calling a function with a bad signature!");
340 assert((1 >= FTy->getNumParams() ||
341 FTy->getParamType(1) == Actual2->getType()) &&
342 "Calling a function with a bad signature!");
345 void CallInst::init(Value *Func, Value *Actual) {
346 assert(NumOperands == 2 && "NumOperands not set up?");
347 Use *OL = OperandList;
351 const FunctionType *FTy =
352 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
353 FTy = FTy; // silence warning.
355 assert((FTy->getNumParams() == 1 ||
356 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
357 "Calling a function with bad signature");
358 assert((0 == FTy->getNumParams() ||
359 FTy->getParamType(0) == Actual->getType()) &&
360 "Calling a function with a bad signature!");
363 void CallInst::init(Value *Func) {
364 assert(NumOperands == 1 && "NumOperands not set up?");
365 Use *OL = OperandList;
368 const FunctionType *FTy =
369 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
370 FTy = FTy; // silence warning.
372 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
375 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
376 Instruction *InsertBefore)
377 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
378 ->getElementType())->getReturnType(),
380 OperandTraits<CallInst>::op_end(this) - 2,
386 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
387 BasicBlock *InsertAtEnd)
388 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
389 ->getElementType())->getReturnType(),
391 OperandTraits<CallInst>::op_end(this) - 2,
396 CallInst::CallInst(Value *Func, const Twine &Name,
397 Instruction *InsertBefore)
398 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
399 ->getElementType())->getReturnType(),
401 OperandTraits<CallInst>::op_end(this) - 1,
407 CallInst::CallInst(Value *Func, const Twine &Name,
408 BasicBlock *InsertAtEnd)
409 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
410 ->getElementType())->getReturnType(),
412 OperandTraits<CallInst>::op_end(this) - 1,
418 CallInst::CallInst(const CallInst &CI)
419 : Instruction(CI.getType(), Instruction::Call,
420 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
421 CI.getNumOperands()) {
422 setAttributes(CI.getAttributes());
423 setTailCall(CI.isTailCall());
424 setCallingConv(CI.getCallingConv());
426 Use *OL = OperandList;
427 Use *InOL = CI.OperandList;
428 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
430 SubclassOptionalData = CI.SubclassOptionalData;
433 void CallInst::addAttribute(unsigned i, Attributes attr) {
434 AttrListPtr PAL = getAttributes();
435 PAL = PAL.addAttr(i, attr);
439 void CallInst::removeAttribute(unsigned i, Attributes attr) {
440 AttrListPtr PAL = getAttributes();
441 PAL = PAL.removeAttr(i, attr);
445 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
446 if (AttributeList.paramHasAttr(i, attr))
448 if (const Function *F = getCalledFunction())
449 return F->paramHasAttr(i, attr);
453 /// IsConstantOne - Return true only if val is constant int 1
454 static bool IsConstantOne(Value *val) {
455 assert(val && "IsConstantOne does not work with NULL val");
456 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
459 static Instruction *createMalloc(Instruction *InsertBefore,
460 BasicBlock *InsertAtEnd, const Type *IntPtrTy,
461 const Type *AllocTy, Value *AllocSize,
462 Value *ArraySize, Function *MallocF,
464 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
465 "createMalloc needs either InsertBefore or InsertAtEnd");
467 // malloc(type) becomes:
468 // bitcast (i8* malloc(typeSize)) to type*
469 // malloc(type, arraySize) becomes:
470 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
472 ArraySize = ConstantInt::get(IntPtrTy, 1);
473 else if (ArraySize->getType() != IntPtrTy) {
475 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
478 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
482 if (!IsConstantOne(ArraySize)) {
483 if (IsConstantOne(AllocSize)) {
484 AllocSize = ArraySize; // Operand * 1 = Operand
485 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
486 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
488 // Malloc arg is constant product of type size and array size
489 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
491 // Multiply type size by the array size...
493 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
494 "mallocsize", InsertBefore);
496 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
497 "mallocsize", InsertAtEnd);
501 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
502 // Create the call to Malloc.
503 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
504 Module* M = BB->getParent()->getParent();
505 const Type *BPTy = Type::getInt8PtrTy(BB->getContext());
506 Value *MallocFunc = MallocF;
508 // prototype malloc as "void *malloc(size_t)"
509 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
510 const PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
511 CallInst *MCall = NULL;
512 Instruction *Result = NULL;
514 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
516 if (Result->getType() != AllocPtrType)
517 // Create a cast instruction to convert to the right type...
518 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
520 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
522 if (Result->getType() != AllocPtrType) {
523 InsertAtEnd->getInstList().push_back(MCall);
524 // Create a cast instruction to convert to the right type...
525 Result = new BitCastInst(MCall, AllocPtrType, Name);
528 MCall->setTailCall();
529 if (Function *F = dyn_cast<Function>(MallocFunc)) {
530 MCall->setCallingConv(F->getCallingConv());
531 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
533 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
538 /// CreateMalloc - Generate the IR for a call to malloc:
539 /// 1. Compute the malloc call's argument as the specified type's size,
540 /// possibly multiplied by the array size if the array size is not
542 /// 2. Call malloc with that argument.
543 /// 3. Bitcast the result of the malloc call to the specified type.
544 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
545 const Type *IntPtrTy, const Type *AllocTy,
546 Value *AllocSize, Value *ArraySize,
548 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
549 ArraySize, NULL, Name);
552 /// CreateMalloc - Generate the IR for a call to malloc:
553 /// 1. Compute the malloc call's argument as the specified type's size,
554 /// possibly multiplied by the array size if the array size is not
556 /// 2. Call malloc with that argument.
557 /// 3. Bitcast the result of the malloc call to the specified type.
558 /// Note: This function does not add the bitcast to the basic block, that is the
559 /// responsibility of the caller.
560 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
561 const Type *IntPtrTy, const Type *AllocTy,
562 Value *AllocSize, Value *ArraySize,
563 Function *MallocF, const Twine &Name) {
564 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
565 ArraySize, MallocF, Name);
568 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
569 BasicBlock *InsertAtEnd) {
570 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
571 "createFree needs either InsertBefore or InsertAtEnd");
572 assert(Source->getType()->isPointerTy() &&
573 "Can not free something of nonpointer type!");
575 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
576 Module* M = BB->getParent()->getParent();
578 const Type *VoidTy = Type::getVoidTy(M->getContext());
579 const Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
580 // prototype free as "void free(void*)"
581 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
582 CallInst* Result = NULL;
583 Value *PtrCast = Source;
585 if (Source->getType() != IntPtrTy)
586 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
587 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
589 if (Source->getType() != IntPtrTy)
590 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
591 Result = CallInst::Create(FreeFunc, PtrCast, "");
593 Result->setTailCall();
594 if (Function *F = dyn_cast<Function>(FreeFunc))
595 Result->setCallingConv(F->getCallingConv());
600 /// CreateFree - Generate the IR for a call to the builtin free function.
601 void CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
602 createFree(Source, InsertBefore, NULL);
605 /// CreateFree - Generate the IR for a call to the builtin free function.
606 /// Note: This function does not add the call to the basic block, that is the
607 /// responsibility of the caller.
608 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
609 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
610 assert(FreeCall && "CreateFree did not create a CallInst");
614 //===----------------------------------------------------------------------===//
615 // InvokeInst Implementation
616 //===----------------------------------------------------------------------===//
618 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
619 Value* const *Args, unsigned NumArgs) {
620 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
623 Op<-1>() = IfException;
624 const FunctionType *FTy =
625 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
626 FTy = FTy; // silence warning.
628 assert(((NumArgs == FTy->getNumParams()) ||
629 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
630 "Calling a function with bad signature");
632 Use *OL = OperandList;
633 for (unsigned i = 0, e = NumArgs; i != e; i++) {
634 assert((i >= FTy->getNumParams() ||
635 FTy->getParamType(i) == Args[i]->getType()) &&
636 "Invoking a function with a bad signature!");
642 InvokeInst::InvokeInst(const InvokeInst &II)
643 : TerminatorInst(II.getType(), Instruction::Invoke,
644 OperandTraits<InvokeInst>::op_end(this)
645 - II.getNumOperands(),
646 II.getNumOperands()) {
647 setAttributes(II.getAttributes());
648 setCallingConv(II.getCallingConv());
649 Use *OL = OperandList, *InOL = II.OperandList;
650 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
652 SubclassOptionalData = II.SubclassOptionalData;
655 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
656 return getSuccessor(idx);
658 unsigned InvokeInst::getNumSuccessorsV() const {
659 return getNumSuccessors();
661 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
662 return setSuccessor(idx, B);
665 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
666 if (AttributeList.paramHasAttr(i, attr))
668 if (const Function *F = getCalledFunction())
669 return F->paramHasAttr(i, attr);
673 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
674 AttrListPtr PAL = getAttributes();
675 PAL = PAL.addAttr(i, attr);
679 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
680 AttrListPtr PAL = getAttributes();
681 PAL = PAL.removeAttr(i, attr);
686 //===----------------------------------------------------------------------===//
687 // ReturnInst Implementation
688 //===----------------------------------------------------------------------===//
690 ReturnInst::ReturnInst(const ReturnInst &RI)
691 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
692 OperandTraits<ReturnInst>::op_end(this) -
694 RI.getNumOperands()) {
695 if (RI.getNumOperands())
696 Op<0>() = RI.Op<0>();
697 SubclassOptionalData = RI.SubclassOptionalData;
700 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
701 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
702 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
707 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
708 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
709 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
714 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
715 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
716 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
719 unsigned ReturnInst::getNumSuccessorsV() const {
720 return getNumSuccessors();
723 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
724 /// emit the vtable for the class in this translation unit.
725 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
726 llvm_unreachable("ReturnInst has no successors!");
729 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
730 llvm_unreachable("ReturnInst has no successors!");
734 ReturnInst::~ReturnInst() {
737 //===----------------------------------------------------------------------===//
738 // UnwindInst Implementation
739 //===----------------------------------------------------------------------===//
741 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
742 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
743 0, 0, InsertBefore) {
745 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
746 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
751 unsigned UnwindInst::getNumSuccessorsV() const {
752 return getNumSuccessors();
755 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
756 llvm_unreachable("UnwindInst has no successors!");
759 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
760 llvm_unreachable("UnwindInst has no successors!");
764 //===----------------------------------------------------------------------===//
765 // UnreachableInst Implementation
766 //===----------------------------------------------------------------------===//
768 UnreachableInst::UnreachableInst(LLVMContext &Context,
769 Instruction *InsertBefore)
770 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
771 0, 0, InsertBefore) {
773 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
774 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
778 unsigned UnreachableInst::getNumSuccessorsV() const {
779 return getNumSuccessors();
782 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
783 llvm_unreachable("UnwindInst has no successors!");
786 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
787 llvm_unreachable("UnwindInst has no successors!");
791 //===----------------------------------------------------------------------===//
792 // BranchInst Implementation
793 //===----------------------------------------------------------------------===//
795 void BranchInst::AssertOK() {
797 assert(getCondition()->getType()->isIntegerTy(1) &&
798 "May only branch on boolean predicates!");
801 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
802 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
803 OperandTraits<BranchInst>::op_end(this) - 1,
805 assert(IfTrue != 0 && "Branch destination may not be null!");
808 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
809 Instruction *InsertBefore)
810 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
811 OperandTraits<BranchInst>::op_end(this) - 3,
821 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
822 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
823 OperandTraits<BranchInst>::op_end(this) - 1,
825 assert(IfTrue != 0 && "Branch destination may not be null!");
829 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
830 BasicBlock *InsertAtEnd)
831 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
832 OperandTraits<BranchInst>::op_end(this) - 3,
843 BranchInst::BranchInst(const BranchInst &BI) :
844 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
845 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
846 BI.getNumOperands()) {
847 Op<-1>() = BI.Op<-1>();
848 if (BI.getNumOperands() != 1) {
849 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
850 Op<-3>() = BI.Op<-3>();
851 Op<-2>() = BI.Op<-2>();
853 SubclassOptionalData = BI.SubclassOptionalData;
857 Use* Use::getPrefix() {
858 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
859 if (PotentialPrefix.getOpaqueValue())
862 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
865 BranchInst::~BranchInst() {
866 if (NumOperands == 1) {
867 if (Use *Prefix = OperandList->getPrefix()) {
870 // mark OperandList to have a special value for scrutiny
871 // by baseclass destructors and operator delete
872 OperandList = Prefix;
875 OperandList = op_begin();
881 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
882 return getSuccessor(idx);
884 unsigned BranchInst::getNumSuccessorsV() const {
885 return getNumSuccessors();
887 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
888 setSuccessor(idx, B);
892 //===----------------------------------------------------------------------===//
893 // AllocaInst Implementation
894 //===----------------------------------------------------------------------===//
896 static Value *getAISize(LLVMContext &Context, Value *Amt) {
898 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
900 assert(!isa<BasicBlock>(Amt) &&
901 "Passed basic block into allocation size parameter! Use other ctor");
902 assert(Amt->getType()->isIntegerTy(32) &&
903 "Allocation array size is not a 32-bit integer!");
908 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
909 const Twine &Name, Instruction *InsertBefore)
910 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
911 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
913 assert(!Ty->isVoidTy() && "Cannot allocate void!");
917 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
918 const Twine &Name, BasicBlock *InsertAtEnd)
919 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
920 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
922 assert(!Ty->isVoidTy() && "Cannot allocate void!");
926 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
927 Instruction *InsertBefore)
928 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
929 getAISize(Ty->getContext(), 0), InsertBefore) {
931 assert(!Ty->isVoidTy() && "Cannot allocate void!");
935 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
936 BasicBlock *InsertAtEnd)
937 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
938 getAISize(Ty->getContext(), 0), InsertAtEnd) {
940 assert(!Ty->isVoidTy() && "Cannot allocate void!");
944 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
945 const Twine &Name, Instruction *InsertBefore)
946 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
947 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
949 assert(!Ty->isVoidTy() && "Cannot allocate void!");
953 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
954 const Twine &Name, BasicBlock *InsertAtEnd)
955 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
956 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
958 assert(!Ty->isVoidTy() && "Cannot allocate void!");
962 // Out of line virtual method, so the vtable, etc has a home.
963 AllocaInst::~AllocaInst() {
966 void AllocaInst::setAlignment(unsigned Align) {
967 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
968 setInstructionSubclassData(Log2_32(Align) + 1);
969 assert(getAlignment() == Align && "Alignment representation error!");
972 bool AllocaInst::isArrayAllocation() const {
973 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
974 return CI->getZExtValue() != 1;
978 const Type *AllocaInst::getAllocatedType() const {
979 return getType()->getElementType();
982 /// isStaticAlloca - Return true if this alloca is in the entry block of the
983 /// function and is a constant size. If so, the code generator will fold it
984 /// into the prolog/epilog code, so it is basically free.
985 bool AllocaInst::isStaticAlloca() const {
986 // Must be constant size.
987 if (!isa<ConstantInt>(getArraySize())) return false;
989 // Must be in the entry block.
990 const BasicBlock *Parent = getParent();
991 return Parent == &Parent->getParent()->front();
994 //===----------------------------------------------------------------------===//
995 // LoadInst Implementation
996 //===----------------------------------------------------------------------===//
998 void LoadInst::AssertOK() {
999 assert(getOperand(0)->getType()->isPointerTy() &&
1000 "Ptr must have pointer type.");
1003 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1004 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1005 Load, Ptr, InsertBef) {
1012 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1013 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1014 Load, Ptr, InsertAE) {
1021 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1022 Instruction *InsertBef)
1023 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1024 Load, Ptr, InsertBef) {
1025 setVolatile(isVolatile);
1031 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1032 unsigned Align, Instruction *InsertBef)
1033 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1034 Load, Ptr, InsertBef) {
1035 setVolatile(isVolatile);
1036 setAlignment(Align);
1041 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1042 unsigned Align, BasicBlock *InsertAE)
1043 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1044 Load, Ptr, InsertAE) {
1045 setVolatile(isVolatile);
1046 setAlignment(Align);
1051 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1052 BasicBlock *InsertAE)
1053 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1054 Load, Ptr, InsertAE) {
1055 setVolatile(isVolatile);
1063 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1064 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1065 Load, Ptr, InsertBef) {
1069 if (Name && Name[0]) setName(Name);
1072 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1073 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1074 Load, Ptr, InsertAE) {
1078 if (Name && Name[0]) setName(Name);
1081 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1082 Instruction *InsertBef)
1083 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1084 Load, Ptr, InsertBef) {
1085 setVolatile(isVolatile);
1088 if (Name && Name[0]) setName(Name);
1091 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1092 BasicBlock *InsertAE)
1093 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1094 Load, Ptr, InsertAE) {
1095 setVolatile(isVolatile);
1098 if (Name && Name[0]) setName(Name);
1101 void LoadInst::setAlignment(unsigned Align) {
1102 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1103 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1104 ((Log2_32(Align)+1)<<1));
1107 //===----------------------------------------------------------------------===//
1108 // StoreInst Implementation
1109 //===----------------------------------------------------------------------===//
1111 void StoreInst::AssertOK() {
1112 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1113 assert(getOperand(1)->getType()->isPointerTy() &&
1114 "Ptr must have pointer type!");
1115 assert(getOperand(0)->getType() ==
1116 cast<PointerType>(getOperand(1)->getType())->getElementType()
1117 && "Ptr must be a pointer to Val type!");
1121 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1122 : Instruction(Type::getVoidTy(val->getContext()), Store,
1123 OperandTraits<StoreInst>::op_begin(this),
1124 OperandTraits<StoreInst>::operands(this),
1133 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1134 : Instruction(Type::getVoidTy(val->getContext()), Store,
1135 OperandTraits<StoreInst>::op_begin(this),
1136 OperandTraits<StoreInst>::operands(this),
1145 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1146 Instruction *InsertBefore)
1147 : Instruction(Type::getVoidTy(val->getContext()), Store,
1148 OperandTraits<StoreInst>::op_begin(this),
1149 OperandTraits<StoreInst>::operands(this),
1153 setVolatile(isVolatile);
1158 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1159 unsigned Align, Instruction *InsertBefore)
1160 : Instruction(Type::getVoidTy(val->getContext()), Store,
1161 OperandTraits<StoreInst>::op_begin(this),
1162 OperandTraits<StoreInst>::operands(this),
1166 setVolatile(isVolatile);
1167 setAlignment(Align);
1171 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1172 unsigned Align, BasicBlock *InsertAtEnd)
1173 : Instruction(Type::getVoidTy(val->getContext()), Store,
1174 OperandTraits<StoreInst>::op_begin(this),
1175 OperandTraits<StoreInst>::operands(this),
1179 setVolatile(isVolatile);
1180 setAlignment(Align);
1184 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1185 BasicBlock *InsertAtEnd)
1186 : Instruction(Type::getVoidTy(val->getContext()), Store,
1187 OperandTraits<StoreInst>::op_begin(this),
1188 OperandTraits<StoreInst>::operands(this),
1192 setVolatile(isVolatile);
1197 void StoreInst::setAlignment(unsigned Align) {
1198 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1199 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1200 ((Log2_32(Align)+1) << 1));
1203 //===----------------------------------------------------------------------===//
1204 // GetElementPtrInst Implementation
1205 //===----------------------------------------------------------------------===//
1207 static unsigned retrieveAddrSpace(const Value *Val) {
1208 return cast<PointerType>(Val->getType())->getAddressSpace();
1211 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1212 const Twine &Name) {
1213 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1214 Use *OL = OperandList;
1217 for (unsigned i = 0; i != NumIdx; ++i)
1223 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1224 assert(NumOperands == 2 && "NumOperands not initialized?");
1225 Use *OL = OperandList;
1232 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1233 : Instruction(GEPI.getType(), GetElementPtr,
1234 OperandTraits<GetElementPtrInst>::op_end(this)
1235 - GEPI.getNumOperands(),
1236 GEPI.getNumOperands()) {
1237 Use *OL = OperandList;
1238 Use *GEPIOL = GEPI.OperandList;
1239 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1241 SubclassOptionalData = GEPI.SubclassOptionalData;
1244 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1245 const Twine &Name, Instruction *InBe)
1246 : Instruction(PointerType::get(
1247 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1249 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1251 init(Ptr, Idx, Name);
1254 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1255 const Twine &Name, BasicBlock *IAE)
1256 : Instruction(PointerType::get(
1257 checkType(getIndexedType(Ptr->getType(),Idx)),
1258 retrieveAddrSpace(Ptr)),
1260 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1262 init(Ptr, Idx, Name);
1265 /// getIndexedType - Returns the type of the element that would be accessed with
1266 /// a gep instruction with the specified parameters.
1268 /// The Idxs pointer should point to a continuous piece of memory containing the
1269 /// indices, either as Value* or uint64_t.
1271 /// A null type is returned if the indices are invalid for the specified
1274 template <typename IndexTy>
1275 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1277 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1278 if (!PTy) return 0; // Type isn't a pointer type!
1279 const Type *Agg = PTy->getElementType();
1281 // Handle the special case of the empty set index set, which is always valid.
1285 // If there is at least one index, the top level type must be sized, otherwise
1286 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1287 // that contain opaque types) under the assumption that it will be resolved to
1288 // a sane type later.
1289 if (!Agg->isSized() && !Agg->isAbstract())
1292 unsigned CurIdx = 1;
1293 for (; CurIdx != NumIdx; ++CurIdx) {
1294 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1295 if (!CT || CT->isPointerTy()) return 0;
1296 IndexTy Index = Idxs[CurIdx];
1297 if (!CT->indexValid(Index)) return 0;
1298 Agg = CT->getTypeAtIndex(Index);
1300 // If the new type forwards to another type, then it is in the middle
1301 // of being refined to another type (and hence, may have dropped all
1302 // references to what it was using before). So, use the new forwarded
1304 if (const Type *Ty = Agg->getForwardedType())
1307 return CurIdx == NumIdx ? Agg : 0;
1310 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1313 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1316 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1317 uint64_t const *Idxs,
1319 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1322 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1323 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1324 if (!PTy) return 0; // Type isn't a pointer type!
1326 // Check the pointer index.
1327 if (!PTy->indexValid(Idx)) return 0;
1329 return PTy->getElementType();
1333 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1334 /// zeros. If so, the result pointer and the first operand have the same
1335 /// value, just potentially different types.
1336 bool GetElementPtrInst::hasAllZeroIndices() const {
1337 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1338 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1339 if (!CI->isZero()) return false;
1347 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1348 /// constant integers. If so, the result pointer and the first operand have
1349 /// a constant offset between them.
1350 bool GetElementPtrInst::hasAllConstantIndices() const {
1351 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1352 if (!isa<ConstantInt>(getOperand(i)))
1358 void GetElementPtrInst::setIsInBounds(bool B) {
1359 cast<GEPOperator>(this)->setIsInBounds(B);
1362 bool GetElementPtrInst::isInBounds() const {
1363 return cast<GEPOperator>(this)->isInBounds();
1366 //===----------------------------------------------------------------------===//
1367 // ExtractElementInst Implementation
1368 //===----------------------------------------------------------------------===//
1370 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1372 Instruction *InsertBef)
1373 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1375 OperandTraits<ExtractElementInst>::op_begin(this),
1377 assert(isValidOperands(Val, Index) &&
1378 "Invalid extractelement instruction operands!");
1384 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1386 BasicBlock *InsertAE)
1387 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1389 OperandTraits<ExtractElementInst>::op_begin(this),
1391 assert(isValidOperands(Val, Index) &&
1392 "Invalid extractelement instruction operands!");
1400 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1401 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1407 //===----------------------------------------------------------------------===//
1408 // InsertElementInst Implementation
1409 //===----------------------------------------------------------------------===//
1411 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1413 Instruction *InsertBef)
1414 : Instruction(Vec->getType(), InsertElement,
1415 OperandTraits<InsertElementInst>::op_begin(this),
1417 assert(isValidOperands(Vec, Elt, Index) &&
1418 "Invalid insertelement instruction operands!");
1425 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1427 BasicBlock *InsertAE)
1428 : Instruction(Vec->getType(), InsertElement,
1429 OperandTraits<InsertElementInst>::op_begin(this),
1431 assert(isValidOperands(Vec, Elt, Index) &&
1432 "Invalid insertelement instruction operands!");
1440 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1441 const Value *Index) {
1442 if (!Vec->getType()->isVectorTy())
1443 return false; // First operand of insertelement must be vector type.
1445 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1446 return false;// Second operand of insertelement must be vector element type.
1448 if (!Index->getType()->isIntegerTy(32))
1449 return false; // Third operand of insertelement must be i32.
1454 //===----------------------------------------------------------------------===//
1455 // ShuffleVectorInst Implementation
1456 //===----------------------------------------------------------------------===//
1458 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1460 Instruction *InsertBefore)
1461 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1462 cast<VectorType>(Mask->getType())->getNumElements()),
1464 OperandTraits<ShuffleVectorInst>::op_begin(this),
1465 OperandTraits<ShuffleVectorInst>::operands(this),
1467 assert(isValidOperands(V1, V2, Mask) &&
1468 "Invalid shuffle vector instruction operands!");
1475 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1477 BasicBlock *InsertAtEnd)
1478 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1479 cast<VectorType>(Mask->getType())->getNumElements()),
1481 OperandTraits<ShuffleVectorInst>::op_begin(this),
1482 OperandTraits<ShuffleVectorInst>::operands(this),
1484 assert(isValidOperands(V1, V2, Mask) &&
1485 "Invalid shuffle vector instruction operands!");
1493 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1494 const Value *Mask) {
1495 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1498 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1499 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1500 !MaskTy->getElementType()->isIntegerTy(32))
1505 /// getMaskValue - Return the index from the shuffle mask for the specified
1506 /// output result. This is either -1 if the element is undef or a number less
1507 /// than 2*numelements.
1508 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1509 const Constant *Mask = cast<Constant>(getOperand(2));
1510 if (isa<UndefValue>(Mask)) return -1;
1511 if (isa<ConstantAggregateZero>(Mask)) return 0;
1512 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1513 assert(i < MaskCV->getNumOperands() && "Index out of range");
1515 if (isa<UndefValue>(MaskCV->getOperand(i)))
1517 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1520 //===----------------------------------------------------------------------===//
1521 // InsertValueInst Class
1522 //===----------------------------------------------------------------------===//
1524 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1525 unsigned NumIdx, const Twine &Name) {
1526 assert(NumOperands == 2 && "NumOperands not initialized?");
1530 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1534 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1535 const Twine &Name) {
1536 assert(NumOperands == 2 && "NumOperands not initialized?");
1540 Indices.push_back(Idx);
1544 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1545 : Instruction(IVI.getType(), InsertValue,
1546 OperandTraits<InsertValueInst>::op_begin(this), 2),
1547 Indices(IVI.Indices) {
1548 Op<0>() = IVI.getOperand(0);
1549 Op<1>() = IVI.getOperand(1);
1550 SubclassOptionalData = IVI.SubclassOptionalData;
1553 InsertValueInst::InsertValueInst(Value *Agg,
1557 Instruction *InsertBefore)
1558 : Instruction(Agg->getType(), InsertValue,
1559 OperandTraits<InsertValueInst>::op_begin(this),
1561 init(Agg, Val, Idx, Name);
1564 InsertValueInst::InsertValueInst(Value *Agg,
1568 BasicBlock *InsertAtEnd)
1569 : Instruction(Agg->getType(), InsertValue,
1570 OperandTraits<InsertValueInst>::op_begin(this),
1572 init(Agg, Val, Idx, Name);
1575 //===----------------------------------------------------------------------===//
1576 // ExtractValueInst Class
1577 //===----------------------------------------------------------------------===//
1579 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1580 const Twine &Name) {
1581 assert(NumOperands == 1 && "NumOperands not initialized?");
1583 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1587 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1588 assert(NumOperands == 1 && "NumOperands not initialized?");
1590 Indices.push_back(Idx);
1594 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1595 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1596 Indices(EVI.Indices) {
1597 SubclassOptionalData = EVI.SubclassOptionalData;
1600 // getIndexedType - Returns the type of the element that would be extracted
1601 // with an extractvalue instruction with the specified parameters.
1603 // A null type is returned if the indices are invalid for the specified
1606 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1607 const unsigned *Idxs,
1609 unsigned CurIdx = 0;
1610 for (; CurIdx != NumIdx; ++CurIdx) {
1611 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1612 if (!CT || CT->isPointerTy() || CT->isVectorTy()) return 0;
1613 unsigned Index = Idxs[CurIdx];
1614 if (!CT->indexValid(Index)) return 0;
1615 Agg = CT->getTypeAtIndex(Index);
1617 // If the new type forwards to another type, then it is in the middle
1618 // of being refined to another type (and hence, may have dropped all
1619 // references to what it was using before). So, use the new forwarded
1621 if (const Type *Ty = Agg->getForwardedType())
1624 return CurIdx == NumIdx ? Agg : 0;
1627 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1629 return getIndexedType(Agg, &Idx, 1);
1632 //===----------------------------------------------------------------------===//
1633 // BinaryOperator Class
1634 //===----------------------------------------------------------------------===//
1636 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1637 /// type is floating-point, to help provide compatibility with an older API.
1639 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1641 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1642 if (Ty->isFPOrFPVectorTy()) {
1643 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1644 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1645 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1650 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1651 const Type *Ty, const Twine &Name,
1652 Instruction *InsertBefore)
1653 : Instruction(Ty, AdjustIType(iType, Ty),
1654 OperandTraits<BinaryOperator>::op_begin(this),
1655 OperandTraits<BinaryOperator>::operands(this),
1659 init(AdjustIType(iType, Ty));
1663 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1664 const Type *Ty, const Twine &Name,
1665 BasicBlock *InsertAtEnd)
1666 : Instruction(Ty, AdjustIType(iType, Ty),
1667 OperandTraits<BinaryOperator>::op_begin(this),
1668 OperandTraits<BinaryOperator>::operands(this),
1672 init(AdjustIType(iType, Ty));
1677 void BinaryOperator::init(BinaryOps iType) {
1678 Value *LHS = getOperand(0), *RHS = getOperand(1);
1679 LHS = LHS; RHS = RHS; // Silence warnings.
1680 assert(LHS->getType() == RHS->getType() &&
1681 "Binary operator operand types must match!");
1686 assert(getType() == LHS->getType() &&
1687 "Arithmetic operation should return same type as operands!");
1688 assert(getType()->isIntOrIntVectorTy() &&
1689 "Tried to create an integer operation on a non-integer type!");
1691 case FAdd: case FSub:
1693 assert(getType() == LHS->getType() &&
1694 "Arithmetic operation should return same type as operands!");
1695 assert(getType()->isFPOrFPVectorTy() &&
1696 "Tried to create a floating-point operation on a "
1697 "non-floating-point type!");
1701 assert(getType() == LHS->getType() &&
1702 "Arithmetic operation should return same type as operands!");
1703 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1704 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1705 "Incorrect operand type (not integer) for S/UDIV");
1708 assert(getType() == LHS->getType() &&
1709 "Arithmetic operation should return same type as operands!");
1710 assert(getType()->isFPOrFPVectorTy() &&
1711 "Incorrect operand type (not floating point) for FDIV");
1715 assert(getType() == LHS->getType() &&
1716 "Arithmetic operation should return same type as operands!");
1717 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1718 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1719 "Incorrect operand type (not integer) for S/UREM");
1722 assert(getType() == LHS->getType() &&
1723 "Arithmetic operation should return same type as operands!");
1724 assert(getType()->isFPOrFPVectorTy() &&
1725 "Incorrect operand type (not floating point) for FREM");
1730 assert(getType() == LHS->getType() &&
1731 "Shift operation should return same type as operands!");
1732 assert((getType()->isIntegerTy() ||
1733 (getType()->isVectorTy() &&
1734 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1735 "Tried to create a shift operation on a non-integral type!");
1739 assert(getType() == LHS->getType() &&
1740 "Logical operation should return same type as operands!");
1741 assert((getType()->isIntegerTy() ||
1742 (getType()->isVectorTy() &&
1743 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1744 "Tried to create a logical operation on a non-integral type!");
1752 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1754 Instruction *InsertBefore) {
1755 assert(S1->getType() == S2->getType() &&
1756 "Cannot create binary operator with two operands of differing type!");
1757 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1760 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1762 BasicBlock *InsertAtEnd) {
1763 BinaryOperator *Res = Create(Op, S1, S2, Name);
1764 InsertAtEnd->getInstList().push_back(Res);
1768 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1769 Instruction *InsertBefore) {
1770 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1771 return new BinaryOperator(Instruction::Sub,
1773 Op->getType(), Name, InsertBefore);
1776 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1777 BasicBlock *InsertAtEnd) {
1778 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1779 return new BinaryOperator(Instruction::Sub,
1781 Op->getType(), Name, InsertAtEnd);
1784 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1785 Instruction *InsertBefore) {
1786 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1787 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1790 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1791 BasicBlock *InsertAtEnd) {
1792 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1793 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1796 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1797 Instruction *InsertBefore) {
1798 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1799 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1802 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1803 BasicBlock *InsertAtEnd) {
1804 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1805 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1808 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1809 Instruction *InsertBefore) {
1810 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1811 return new BinaryOperator(Instruction::FSub,
1813 Op->getType(), Name, InsertBefore);
1816 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1817 BasicBlock *InsertAtEnd) {
1818 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1819 return new BinaryOperator(Instruction::FSub,
1821 Op->getType(), Name, InsertAtEnd);
1824 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1825 Instruction *InsertBefore) {
1827 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1828 C = Constant::getAllOnesValue(PTy->getElementType());
1829 C = ConstantVector::get(
1830 std::vector<Constant*>(PTy->getNumElements(), C));
1832 C = Constant::getAllOnesValue(Op->getType());
1835 return new BinaryOperator(Instruction::Xor, Op, C,
1836 Op->getType(), Name, InsertBefore);
1839 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1840 BasicBlock *InsertAtEnd) {
1842 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1843 // Create a vector of all ones values.
1844 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1845 AllOnes = ConstantVector::get(
1846 std::vector<Constant*>(PTy->getNumElements(), Elt));
1848 AllOnes = Constant::getAllOnesValue(Op->getType());
1851 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1852 Op->getType(), Name, InsertAtEnd);
1856 // isConstantAllOnes - Helper function for several functions below
1857 static inline bool isConstantAllOnes(const Value *V) {
1858 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1859 return CI->isAllOnesValue();
1860 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1861 return CV->isAllOnesValue();
1865 bool BinaryOperator::isNeg(const Value *V) {
1866 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1867 if (Bop->getOpcode() == Instruction::Sub)
1868 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1869 return C->isNegativeZeroValue();
1873 bool BinaryOperator::isFNeg(const Value *V) {
1874 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1875 if (Bop->getOpcode() == Instruction::FSub)
1876 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1877 return C->isNegativeZeroValue();
1881 bool BinaryOperator::isNot(const Value *V) {
1882 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1883 return (Bop->getOpcode() == Instruction::Xor &&
1884 (isConstantAllOnes(Bop->getOperand(1)) ||
1885 isConstantAllOnes(Bop->getOperand(0))));
1889 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1890 return cast<BinaryOperator>(BinOp)->getOperand(1);
1893 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1894 return getNegArgument(const_cast<Value*>(BinOp));
1897 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1898 return cast<BinaryOperator>(BinOp)->getOperand(1);
1901 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1902 return getFNegArgument(const_cast<Value*>(BinOp));
1905 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1906 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1907 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1908 Value *Op0 = BO->getOperand(0);
1909 Value *Op1 = BO->getOperand(1);
1910 if (isConstantAllOnes(Op0)) return Op1;
1912 assert(isConstantAllOnes(Op1));
1916 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1917 return getNotArgument(const_cast<Value*>(BinOp));
1921 // swapOperands - Exchange the two operands to this instruction. This
1922 // instruction is safe to use on any binary instruction and does not
1923 // modify the semantics of the instruction. If the instruction is
1924 // order dependent (SetLT f.e.) the opcode is changed.
1926 bool BinaryOperator::swapOperands() {
1927 if (!isCommutative())
1928 return true; // Can't commute operands
1929 Op<0>().swap(Op<1>());
1933 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1934 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1937 void BinaryOperator::setHasNoSignedWrap(bool b) {
1938 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1941 void BinaryOperator::setIsExact(bool b) {
1942 cast<SDivOperator>(this)->setIsExact(b);
1945 bool BinaryOperator::hasNoUnsignedWrap() const {
1946 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1949 bool BinaryOperator::hasNoSignedWrap() const {
1950 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1953 bool BinaryOperator::isExact() const {
1954 return cast<SDivOperator>(this)->isExact();
1957 //===----------------------------------------------------------------------===//
1959 //===----------------------------------------------------------------------===//
1961 // Just determine if this cast only deals with integral->integral conversion.
1962 bool CastInst::isIntegerCast() const {
1963 switch (getOpcode()) {
1964 default: return false;
1965 case Instruction::ZExt:
1966 case Instruction::SExt:
1967 case Instruction::Trunc:
1969 case Instruction::BitCast:
1970 return getOperand(0)->getType()->isIntegerTy() &&
1971 getType()->isIntegerTy();
1975 bool CastInst::isLosslessCast() const {
1976 // Only BitCast can be lossless, exit fast if we're not BitCast
1977 if (getOpcode() != Instruction::BitCast)
1980 // Identity cast is always lossless
1981 const Type* SrcTy = getOperand(0)->getType();
1982 const Type* DstTy = getType();
1986 // Pointer to pointer is always lossless.
1987 if (SrcTy->isPointerTy())
1988 return DstTy->isPointerTy();
1989 return false; // Other types have no identity values
1992 /// This function determines if the CastInst does not require any bits to be
1993 /// changed in order to effect the cast. Essentially, it identifies cases where
1994 /// no code gen is necessary for the cast, hence the name no-op cast. For
1995 /// example, the following are all no-op casts:
1996 /// # bitcast i32* %x to i8*
1997 /// # bitcast <2 x i32> %x to <4 x i16>
1998 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1999 /// @brief Determine if a cast is a no-op.
2000 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
2001 switch (getOpcode()) {
2003 assert(!"Invalid CastOp");
2004 case Instruction::Trunc:
2005 case Instruction::ZExt:
2006 case Instruction::SExt:
2007 case Instruction::FPTrunc:
2008 case Instruction::FPExt:
2009 case Instruction::UIToFP:
2010 case Instruction::SIToFP:
2011 case Instruction::FPToUI:
2012 case Instruction::FPToSI:
2013 return false; // These always modify bits
2014 case Instruction::BitCast:
2015 return true; // BitCast never modifies bits.
2016 case Instruction::PtrToInt:
2017 return IntPtrTy->getScalarSizeInBits() ==
2018 getType()->getScalarSizeInBits();
2019 case Instruction::IntToPtr:
2020 return IntPtrTy->getScalarSizeInBits() ==
2021 getOperand(0)->getType()->getScalarSizeInBits();
2025 /// This function determines if a pair of casts can be eliminated and what
2026 /// opcode should be used in the elimination. This assumes that there are two
2027 /// instructions like this:
2028 /// * %F = firstOpcode SrcTy %x to MidTy
2029 /// * %S = secondOpcode MidTy %F to DstTy
2030 /// The function returns a resultOpcode so these two casts can be replaced with:
2031 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2032 /// If no such cast is permited, the function returns 0.
2033 unsigned CastInst::isEliminableCastPair(
2034 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2035 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
2037 // Define the 144 possibilities for these two cast instructions. The values
2038 // in this matrix determine what to do in a given situation and select the
2039 // case in the switch below. The rows correspond to firstOp, the columns
2040 // correspond to secondOp. In looking at the table below, keep in mind
2041 // the following cast properties:
2043 // Size Compare Source Destination
2044 // Operator Src ? Size Type Sign Type Sign
2045 // -------- ------------ ------------------- ---------------------
2046 // TRUNC > Integer Any Integral Any
2047 // ZEXT < Integral Unsigned Integer Any
2048 // SEXT < Integral Signed Integer Any
2049 // FPTOUI n/a FloatPt n/a Integral Unsigned
2050 // FPTOSI n/a FloatPt n/a Integral Signed
2051 // UITOFP n/a Integral Unsigned FloatPt n/a
2052 // SITOFP n/a Integral Signed FloatPt n/a
2053 // FPTRUNC > FloatPt n/a FloatPt n/a
2054 // FPEXT < FloatPt n/a FloatPt n/a
2055 // PTRTOINT n/a Pointer n/a Integral Unsigned
2056 // INTTOPTR n/a Integral Unsigned Pointer n/a
2057 // BITCONVERT = FirstClass n/a FirstClass n/a
2059 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2060 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2061 // into "fptoui double to i64", but this loses information about the range
2062 // of the produced value (we no longer know the top-part is all zeros).
2063 // Further this conversion is often much more expensive for typical hardware,
2064 // and causes issues when building libgcc. We disallow fptosi+sext for the
2066 const unsigned numCastOps =
2067 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2068 static const uint8_t CastResults[numCastOps][numCastOps] = {
2069 // T F F U S F F P I B -+
2070 // R Z S P P I I T P 2 N T |
2071 // U E E 2 2 2 2 R E I T C +- secondOp
2072 // N X X U S F F N X N 2 V |
2073 // C T T I I P P C T T P T -+
2074 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2075 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2076 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2077 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2078 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2079 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2080 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2081 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2082 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2083 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2084 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2085 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2088 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2089 [secondOp-Instruction::CastOpsBegin];
2092 // categorically disallowed
2095 // allowed, use first cast's opcode
2098 // allowed, use second cast's opcode
2101 // no-op cast in second op implies firstOp as long as the DestTy
2102 // is integer and we are not converting between a vector and a
2104 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2108 // no-op cast in second op implies firstOp as long as the DestTy
2109 // is floating point.
2110 if (DstTy->isFloatingPointTy())
2114 // no-op cast in first op implies secondOp as long as the SrcTy
2116 if (SrcTy->isIntegerTy())
2120 // no-op cast in first op implies secondOp as long as the SrcTy
2121 // is a floating point.
2122 if (SrcTy->isFloatingPointTy())
2126 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2129 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2130 unsigned MidSize = MidTy->getScalarSizeInBits();
2131 if (MidSize >= PtrSize)
2132 return Instruction::BitCast;
2136 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2137 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2138 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2139 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2140 unsigned DstSize = DstTy->getScalarSizeInBits();
2141 if (SrcSize == DstSize)
2142 return Instruction::BitCast;
2143 else if (SrcSize < DstSize)
2147 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2148 return Instruction::ZExt;
2150 // fpext followed by ftrunc is allowed if the bit size returned to is
2151 // the same as the original, in which case its just a bitcast
2153 return Instruction::BitCast;
2154 return 0; // If the types are not the same we can't eliminate it.
2156 // bitcast followed by ptrtoint is allowed as long as the bitcast
2157 // is a pointer to pointer cast.
2158 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2162 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2163 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2167 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2170 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2171 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2172 unsigned DstSize = DstTy->getScalarSizeInBits();
2173 if (SrcSize <= PtrSize && SrcSize == DstSize)
2174 return Instruction::BitCast;
2178 // cast combination can't happen (error in input). This is for all cases
2179 // where the MidTy is not the same for the two cast instructions.
2180 assert(!"Invalid Cast Combination");
2183 assert(!"Error in CastResults table!!!");
2189 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2190 const Twine &Name, Instruction *InsertBefore) {
2191 // Construct and return the appropriate CastInst subclass
2193 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2194 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2195 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2196 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2197 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2198 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2199 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2200 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2201 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2202 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2203 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2204 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2206 assert(!"Invalid opcode provided");
2211 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2212 const Twine &Name, BasicBlock *InsertAtEnd) {
2213 // Construct and return the appropriate CastInst subclass
2215 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2216 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2217 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2218 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2219 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2220 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2221 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2222 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2223 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2224 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2225 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2226 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2228 assert(!"Invalid opcode provided");
2233 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2235 Instruction *InsertBefore) {
2236 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2237 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2238 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2241 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2243 BasicBlock *InsertAtEnd) {
2244 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2245 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2246 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2249 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2251 Instruction *InsertBefore) {
2252 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2253 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2254 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2257 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2259 BasicBlock *InsertAtEnd) {
2260 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2261 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2262 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2265 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2267 Instruction *InsertBefore) {
2268 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2269 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2270 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2273 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2275 BasicBlock *InsertAtEnd) {
2276 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2277 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2278 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2281 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2283 BasicBlock *InsertAtEnd) {
2284 assert(S->getType()->isPointerTy() && "Invalid cast");
2285 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2288 if (Ty->isIntegerTy())
2289 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2290 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2293 /// @brief Create a BitCast or a PtrToInt cast instruction
2294 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2296 Instruction *InsertBefore) {
2297 assert(S->getType()->isPointerTy() && "Invalid cast");
2298 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2301 if (Ty->isIntegerTy())
2302 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2303 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2306 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2307 bool isSigned, const Twine &Name,
2308 Instruction *InsertBefore) {
2309 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2310 "Invalid integer cast");
2311 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2312 unsigned DstBits = Ty->getScalarSizeInBits();
2313 Instruction::CastOps opcode =
2314 (SrcBits == DstBits ? Instruction::BitCast :
2315 (SrcBits > DstBits ? Instruction::Trunc :
2316 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2317 return Create(opcode, C, Ty, Name, InsertBefore);
2320 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2321 bool isSigned, const Twine &Name,
2322 BasicBlock *InsertAtEnd) {
2323 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2325 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2326 unsigned DstBits = Ty->getScalarSizeInBits();
2327 Instruction::CastOps opcode =
2328 (SrcBits == DstBits ? Instruction::BitCast :
2329 (SrcBits > DstBits ? Instruction::Trunc :
2330 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2331 return Create(opcode, C, Ty, Name, InsertAtEnd);
2334 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2336 Instruction *InsertBefore) {
2337 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2339 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2340 unsigned DstBits = Ty->getScalarSizeInBits();
2341 Instruction::CastOps opcode =
2342 (SrcBits == DstBits ? Instruction::BitCast :
2343 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2344 return Create(opcode, C, Ty, Name, InsertBefore);
2347 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2349 BasicBlock *InsertAtEnd) {
2350 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2352 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2353 unsigned DstBits = Ty->getScalarSizeInBits();
2354 Instruction::CastOps opcode =
2355 (SrcBits == DstBits ? Instruction::BitCast :
2356 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2357 return Create(opcode, C, Ty, Name, InsertAtEnd);
2360 // Check whether it is valid to call getCastOpcode for these types.
2361 // This routine must be kept in sync with getCastOpcode.
2362 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2363 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2366 if (SrcTy == DestTy)
2369 // Get the bit sizes, we'll need these
2370 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2371 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2373 // Run through the possibilities ...
2374 if (DestTy->isIntegerTy()) { // Casting to integral
2375 if (SrcTy->isIntegerTy()) { // Casting from integral
2377 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2379 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2380 // Casting from vector
2381 return DestBits == PTy->getBitWidth();
2382 } else { // Casting from something else
2383 return SrcTy->isPointerTy();
2385 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2386 if (SrcTy->isIntegerTy()) { // Casting from integral
2388 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2390 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2391 // Casting from vector
2392 return DestBits == PTy->getBitWidth();
2393 } else { // Casting from something else
2396 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2397 // Casting to vector
2398 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2399 // Casting from vector
2400 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2401 } else { // Casting from something else
2402 return DestPTy->getBitWidth() == SrcBits;
2404 } else if (DestTy->isPointerTy()) { // Casting to pointer
2405 if (SrcTy->isPointerTy()) { // Casting from pointer
2407 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2409 } else { // Casting from something else
2412 } else { // Casting to something else
2417 // Provide a way to get a "cast" where the cast opcode is inferred from the
2418 // types and size of the operand. This, basically, is a parallel of the
2419 // logic in the castIsValid function below. This axiom should hold:
2420 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2421 // should not assert in castIsValid. In other words, this produces a "correct"
2422 // casting opcode for the arguments passed to it.
2423 // This routine must be kept in sync with isCastable.
2424 Instruction::CastOps
2425 CastInst::getCastOpcode(
2426 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2427 // Get the bit sizes, we'll need these
2428 const Type *SrcTy = Src->getType();
2429 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2430 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2432 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2433 "Only first class types are castable!");
2435 // Run through the possibilities ...
2436 if (DestTy->isIntegerTy()) { // Casting to integral
2437 if (SrcTy->isIntegerTy()) { // Casting from integral
2438 if (DestBits < SrcBits)
2439 return Trunc; // int -> smaller int
2440 else if (DestBits > SrcBits) { // its an extension
2442 return SExt; // signed -> SEXT
2444 return ZExt; // unsigned -> ZEXT
2446 return BitCast; // Same size, No-op cast
2448 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2450 return FPToSI; // FP -> sint
2452 return FPToUI; // FP -> uint
2453 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2454 assert(DestBits == PTy->getBitWidth() &&
2455 "Casting vector to integer of different width");
2457 return BitCast; // Same size, no-op cast
2459 assert(SrcTy->isPointerTy() &&
2460 "Casting from a value that is not first-class type");
2461 return PtrToInt; // ptr -> int
2463 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2464 if (SrcTy->isIntegerTy()) { // Casting from integral
2466 return SIToFP; // sint -> FP
2468 return UIToFP; // uint -> FP
2469 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2470 if (DestBits < SrcBits) {
2471 return FPTrunc; // FP -> smaller FP
2472 } else if (DestBits > SrcBits) {
2473 return FPExt; // FP -> larger FP
2475 return BitCast; // same size, no-op cast
2477 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2478 assert(DestBits == PTy->getBitWidth() &&
2479 "Casting vector to floating point of different width");
2481 return BitCast; // same size, no-op cast
2483 llvm_unreachable("Casting pointer or non-first class to float");
2485 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2486 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2487 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2488 "Casting vector to vector of different widths");
2490 return BitCast; // vector -> vector
2491 } else if (DestPTy->getBitWidth() == SrcBits) {
2492 return BitCast; // float/int -> vector
2494 assert(!"Illegal cast to vector (wrong type or size)");
2496 } else if (DestTy->isPointerTy()) {
2497 if (SrcTy->isPointerTy()) {
2498 return BitCast; // ptr -> ptr
2499 } else if (SrcTy->isIntegerTy()) {
2500 return IntToPtr; // int -> ptr
2502 assert(!"Casting pointer to other than pointer or int");
2505 assert(!"Casting to type that is not first-class");
2508 // If we fall through to here we probably hit an assertion cast above
2509 // and assertions are not turned on. Anything we return is an error, so
2510 // BitCast is as good a choice as any.
2514 //===----------------------------------------------------------------------===//
2515 // CastInst SubClass Constructors
2516 //===----------------------------------------------------------------------===//
2518 /// Check that the construction parameters for a CastInst are correct. This
2519 /// could be broken out into the separate constructors but it is useful to have
2520 /// it in one place and to eliminate the redundant code for getting the sizes
2521 /// of the types involved.
2523 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2525 // Check for type sanity on the arguments
2526 const Type *SrcTy = S->getType();
2527 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2528 SrcTy->isAggregateType() || DstTy->isAggregateType())
2531 // Get the size of the types in bits, we'll need this later
2532 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2533 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2535 // Switch on the opcode provided
2537 default: return false; // This is an input error
2538 case Instruction::Trunc:
2539 return SrcTy->isIntOrIntVectorTy() &&
2540 DstTy->isIntOrIntVectorTy()&& SrcBitSize > DstBitSize;
2541 case Instruction::ZExt:
2542 return SrcTy->isIntOrIntVectorTy() &&
2543 DstTy->isIntOrIntVectorTy()&& SrcBitSize < DstBitSize;
2544 case Instruction::SExt:
2545 return SrcTy->isIntOrIntVectorTy() &&
2546 DstTy->isIntOrIntVectorTy()&& SrcBitSize < DstBitSize;
2547 case Instruction::FPTrunc:
2548 return SrcTy->isFPOrFPVectorTy() &&
2549 DstTy->isFPOrFPVectorTy() &&
2550 SrcBitSize > DstBitSize;
2551 case Instruction::FPExt:
2552 return SrcTy->isFPOrFPVectorTy() &&
2553 DstTy->isFPOrFPVectorTy() &&
2554 SrcBitSize < DstBitSize;
2555 case Instruction::UIToFP:
2556 case Instruction::SIToFP:
2557 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2558 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2559 return SVTy->getElementType()->isIntOrIntVectorTy() &&
2560 DVTy->getElementType()->isFPOrFPVectorTy() &&
2561 SVTy->getNumElements() == DVTy->getNumElements();
2564 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy();
2565 case Instruction::FPToUI:
2566 case Instruction::FPToSI:
2567 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2568 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2569 return SVTy->getElementType()->isFPOrFPVectorTy() &&
2570 DVTy->getElementType()->isIntOrIntVectorTy() &&
2571 SVTy->getNumElements() == DVTy->getNumElements();
2574 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy();
2575 case Instruction::PtrToInt:
2576 return SrcTy->isPointerTy() && DstTy->isIntegerTy();
2577 case Instruction::IntToPtr:
2578 return SrcTy->isIntegerTy() && DstTy->isPointerTy();
2579 case Instruction::BitCast:
2580 // BitCast implies a no-op cast of type only. No bits change.
2581 // However, you can't cast pointers to anything but pointers.
2582 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2585 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2586 // these cases, the cast is okay if the source and destination bit widths
2588 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2592 TruncInst::TruncInst(
2593 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2594 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2595 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2598 TruncInst::TruncInst(
2599 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2600 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2601 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2605 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2606 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2607 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2611 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2612 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2613 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2616 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2617 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2618 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2622 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2623 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2624 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2627 FPTruncInst::FPTruncInst(
2628 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2629 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2630 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2633 FPTruncInst::FPTruncInst(
2634 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2635 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2636 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2639 FPExtInst::FPExtInst(
2640 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2641 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2642 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2645 FPExtInst::FPExtInst(
2646 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2647 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2648 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2651 UIToFPInst::UIToFPInst(
2652 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2653 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2654 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2657 UIToFPInst::UIToFPInst(
2658 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2659 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2660 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2663 SIToFPInst::SIToFPInst(
2664 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2665 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2666 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2669 SIToFPInst::SIToFPInst(
2670 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2671 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2672 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2675 FPToUIInst::FPToUIInst(
2676 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2677 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2678 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2681 FPToUIInst::FPToUIInst(
2682 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2683 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2684 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2687 FPToSIInst::FPToSIInst(
2688 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2689 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2690 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2693 FPToSIInst::FPToSIInst(
2694 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2695 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2696 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2699 PtrToIntInst::PtrToIntInst(
2700 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2701 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2702 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2705 PtrToIntInst::PtrToIntInst(
2706 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2707 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2708 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2711 IntToPtrInst::IntToPtrInst(
2712 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2713 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2714 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2717 IntToPtrInst::IntToPtrInst(
2718 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2719 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2720 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2723 BitCastInst::BitCastInst(
2724 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2725 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2726 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2729 BitCastInst::BitCastInst(
2730 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2731 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2732 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2735 //===----------------------------------------------------------------------===//
2737 //===----------------------------------------------------------------------===//
2739 void CmpInst::Anchor() const {}
2741 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2742 Value *LHS, Value *RHS, const Twine &Name,
2743 Instruction *InsertBefore)
2744 : Instruction(ty, op,
2745 OperandTraits<CmpInst>::op_begin(this),
2746 OperandTraits<CmpInst>::operands(this),
2750 setPredicate((Predicate)predicate);
2754 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2755 Value *LHS, Value *RHS, const Twine &Name,
2756 BasicBlock *InsertAtEnd)
2757 : Instruction(ty, op,
2758 OperandTraits<CmpInst>::op_begin(this),
2759 OperandTraits<CmpInst>::operands(this),
2763 setPredicate((Predicate)predicate);
2768 CmpInst::Create(OtherOps Op, unsigned short predicate,
2769 Value *S1, Value *S2,
2770 const Twine &Name, Instruction *InsertBefore) {
2771 if (Op == Instruction::ICmp) {
2773 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2776 return new ICmpInst(CmpInst::Predicate(predicate),
2781 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2784 return new FCmpInst(CmpInst::Predicate(predicate),
2789 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2790 const Twine &Name, BasicBlock *InsertAtEnd) {
2791 if (Op == Instruction::ICmp) {
2792 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2795 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2799 void CmpInst::swapOperands() {
2800 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2803 cast<FCmpInst>(this)->swapOperands();
2806 bool CmpInst::isCommutative() {
2807 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2808 return IC->isCommutative();
2809 return cast<FCmpInst>(this)->isCommutative();
2812 bool CmpInst::isEquality() {
2813 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2814 return IC->isEquality();
2815 return cast<FCmpInst>(this)->isEquality();
2819 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2821 default: assert(!"Unknown cmp predicate!");
2822 case ICMP_EQ: return ICMP_NE;
2823 case ICMP_NE: return ICMP_EQ;
2824 case ICMP_UGT: return ICMP_ULE;
2825 case ICMP_ULT: return ICMP_UGE;
2826 case ICMP_UGE: return ICMP_ULT;
2827 case ICMP_ULE: return ICMP_UGT;
2828 case ICMP_SGT: return ICMP_SLE;
2829 case ICMP_SLT: return ICMP_SGE;
2830 case ICMP_SGE: return ICMP_SLT;
2831 case ICMP_SLE: return ICMP_SGT;
2833 case FCMP_OEQ: return FCMP_UNE;
2834 case FCMP_ONE: return FCMP_UEQ;
2835 case FCMP_OGT: return FCMP_ULE;
2836 case FCMP_OLT: return FCMP_UGE;
2837 case FCMP_OGE: return FCMP_ULT;
2838 case FCMP_OLE: return FCMP_UGT;
2839 case FCMP_UEQ: return FCMP_ONE;
2840 case FCMP_UNE: return FCMP_OEQ;
2841 case FCMP_UGT: return FCMP_OLE;
2842 case FCMP_ULT: return FCMP_OGE;
2843 case FCMP_UGE: return FCMP_OLT;
2844 case FCMP_ULE: return FCMP_OGT;
2845 case FCMP_ORD: return FCMP_UNO;
2846 case FCMP_UNO: return FCMP_ORD;
2847 case FCMP_TRUE: return FCMP_FALSE;
2848 case FCMP_FALSE: return FCMP_TRUE;
2852 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2854 default: assert(! "Unknown icmp predicate!");
2855 case ICMP_EQ: case ICMP_NE:
2856 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2858 case ICMP_UGT: return ICMP_SGT;
2859 case ICMP_ULT: return ICMP_SLT;
2860 case ICMP_UGE: return ICMP_SGE;
2861 case ICMP_ULE: return ICMP_SLE;
2865 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2867 default: assert(! "Unknown icmp predicate!");
2868 case ICMP_EQ: case ICMP_NE:
2869 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2871 case ICMP_SGT: return ICMP_UGT;
2872 case ICMP_SLT: return ICMP_ULT;
2873 case ICMP_SGE: return ICMP_UGE;
2874 case ICMP_SLE: return ICMP_ULE;
2878 /// Initialize a set of values that all satisfy the condition with C.
2881 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2884 uint32_t BitWidth = C.getBitWidth();
2886 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2887 case ICmpInst::ICMP_EQ: Upper++; break;
2888 case ICmpInst::ICMP_NE: Lower++; break;
2889 case ICmpInst::ICMP_ULT:
2890 Lower = APInt::getMinValue(BitWidth);
2891 // Check for an empty-set condition.
2893 return ConstantRange(BitWidth, /*isFullSet=*/false);
2895 case ICmpInst::ICMP_SLT:
2896 Lower = APInt::getSignedMinValue(BitWidth);
2897 // Check for an empty-set condition.
2899 return ConstantRange(BitWidth, /*isFullSet=*/false);
2901 case ICmpInst::ICMP_UGT:
2902 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2903 // Check for an empty-set condition.
2905 return ConstantRange(BitWidth, /*isFullSet=*/false);
2907 case ICmpInst::ICMP_SGT:
2908 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2909 // Check for an empty-set condition.
2911 return ConstantRange(BitWidth, /*isFullSet=*/false);
2913 case ICmpInst::ICMP_ULE:
2914 Lower = APInt::getMinValue(BitWidth); Upper++;
2915 // Check for a full-set condition.
2917 return ConstantRange(BitWidth, /*isFullSet=*/true);
2919 case ICmpInst::ICMP_SLE:
2920 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2921 // Check for a full-set condition.
2923 return ConstantRange(BitWidth, /*isFullSet=*/true);
2925 case ICmpInst::ICMP_UGE:
2926 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2927 // Check for a full-set condition.
2929 return ConstantRange(BitWidth, /*isFullSet=*/true);
2931 case ICmpInst::ICMP_SGE:
2932 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2933 // Check for a full-set condition.
2935 return ConstantRange(BitWidth, /*isFullSet=*/true);
2938 return ConstantRange(Lower, Upper);
2941 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2943 default: assert(!"Unknown cmp predicate!");
2944 case ICMP_EQ: case ICMP_NE:
2946 case ICMP_SGT: return ICMP_SLT;
2947 case ICMP_SLT: return ICMP_SGT;
2948 case ICMP_SGE: return ICMP_SLE;
2949 case ICMP_SLE: return ICMP_SGE;
2950 case ICMP_UGT: return ICMP_ULT;
2951 case ICMP_ULT: return ICMP_UGT;
2952 case ICMP_UGE: return ICMP_ULE;
2953 case ICMP_ULE: return ICMP_UGE;
2955 case FCMP_FALSE: case FCMP_TRUE:
2956 case FCMP_OEQ: case FCMP_ONE:
2957 case FCMP_UEQ: case FCMP_UNE:
2958 case FCMP_ORD: case FCMP_UNO:
2960 case FCMP_OGT: return FCMP_OLT;
2961 case FCMP_OLT: return FCMP_OGT;
2962 case FCMP_OGE: return FCMP_OLE;
2963 case FCMP_OLE: return FCMP_OGE;
2964 case FCMP_UGT: return FCMP_ULT;
2965 case FCMP_ULT: return FCMP_UGT;
2966 case FCMP_UGE: return FCMP_ULE;
2967 case FCMP_ULE: return FCMP_UGE;
2971 bool CmpInst::isUnsigned(unsigned short predicate) {
2972 switch (predicate) {
2973 default: return false;
2974 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2975 case ICmpInst::ICMP_UGE: return true;
2979 bool CmpInst::isSigned(unsigned short predicate) {
2980 switch (predicate) {
2981 default: return false;
2982 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2983 case ICmpInst::ICMP_SGE: return true;
2987 bool CmpInst::isOrdered(unsigned short predicate) {
2988 switch (predicate) {
2989 default: return false;
2990 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2991 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2992 case FCmpInst::FCMP_ORD: return true;
2996 bool CmpInst::isUnordered(unsigned short predicate) {
2997 switch (predicate) {
2998 default: return false;
2999 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3000 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3001 case FCmpInst::FCMP_UNO: return true;
3005 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3007 default: return false;
3008 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3009 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3013 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3015 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3016 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3017 default: return false;
3022 //===----------------------------------------------------------------------===//
3023 // SwitchInst Implementation
3024 //===----------------------------------------------------------------------===//
3026 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
3027 assert(Value && Default);
3028 ReservedSpace = 2+NumCases*2;
3030 OperandList = allocHungoffUses(ReservedSpace);
3032 OperandList[0] = Value;
3033 OperandList[1] = Default;
3036 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3037 /// switch on and a default destination. The number of additional cases can
3038 /// be specified here to make memory allocation more efficient. This
3039 /// constructor can also autoinsert before another instruction.
3040 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3041 Instruction *InsertBefore)
3042 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3043 0, 0, InsertBefore) {
3044 init(Value, Default, NumCases);
3047 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3048 /// switch on and a default destination. The number of additional cases can
3049 /// be specified here to make memory allocation more efficient. This
3050 /// constructor also autoinserts at the end of the specified BasicBlock.
3051 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3052 BasicBlock *InsertAtEnd)
3053 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3054 0, 0, InsertAtEnd) {
3055 init(Value, Default, NumCases);
3058 SwitchInst::SwitchInst(const SwitchInst &SI)
3059 : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch,
3060 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
3061 Use *OL = OperandList, *InOL = SI.OperandList;
3062 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
3064 OL[i+1] = InOL[i+1];
3066 SubclassOptionalData = SI.SubclassOptionalData;
3069 SwitchInst::~SwitchInst() {
3070 dropHungoffUses(OperandList);
3074 /// addCase - Add an entry to the switch instruction...
3076 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3077 unsigned OpNo = NumOperands;
3078 if (OpNo+2 > ReservedSpace)
3079 resizeOperands(0); // Get more space!
3080 // Initialize some new operands.
3081 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3082 NumOperands = OpNo+2;
3083 OperandList[OpNo] = OnVal;
3084 OperandList[OpNo+1] = Dest;
3087 /// removeCase - This method removes the specified successor from the switch
3088 /// instruction. Note that this cannot be used to remove the default
3089 /// destination (successor #0).
3091 void SwitchInst::removeCase(unsigned idx) {
3092 assert(idx != 0 && "Cannot remove the default case!");
3093 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3095 unsigned NumOps = getNumOperands();
3096 Use *OL = OperandList;
3098 // Move everything after this operand down.
3100 // FIXME: we could just swap with the end of the list, then erase. However,
3101 // client might not expect this to happen. The code as it is thrashes the
3102 // use/def lists, which is kinda lame.
3103 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
3105 OL[i-2+1] = OL[i+1];
3108 // Nuke the last value.
3109 OL[NumOps-2].set(0);
3110 OL[NumOps-2+1].set(0);
3111 NumOperands = NumOps-2;
3114 /// resizeOperands - resize operands - This adjusts the length of the operands
3115 /// list according to the following behavior:
3116 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
3117 /// of operation. This grows the number of ops by 3 times.
3118 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
3119 /// 3. If NumOps == NumOperands, trim the reserved space.
3121 void SwitchInst::resizeOperands(unsigned NumOps) {
3122 unsigned e = getNumOperands();
3125 } else if (NumOps*2 > NumOperands) {
3126 // No resize needed.
3127 if (ReservedSpace >= NumOps) return;
3128 } else if (NumOps == NumOperands) {
3129 if (ReservedSpace == NumOps) return;
3134 ReservedSpace = NumOps;
3135 Use *NewOps = allocHungoffUses(NumOps);
3136 Use *OldOps = OperandList;
3137 for (unsigned i = 0; i != e; ++i) {
3138 NewOps[i] = OldOps[i];
3140 OperandList = NewOps;
3141 if (OldOps) Use::zap(OldOps, OldOps + e, true);
3145 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3146 return getSuccessor(idx);
3148 unsigned SwitchInst::getNumSuccessorsV() const {
3149 return getNumSuccessors();
3151 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3152 setSuccessor(idx, B);
3155 //===----------------------------------------------------------------------===//
3156 // SwitchInst Implementation
3157 //===----------------------------------------------------------------------===//
3159 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3160 assert(Address && Address->getType()->isPointerTy() &&
3161 "Address of indirectbr must be a pointer");
3162 ReservedSpace = 1+NumDests;
3164 OperandList = allocHungoffUses(ReservedSpace);
3166 OperandList[0] = Address;
3170 /// resizeOperands - resize operands - This adjusts the length of the operands
3171 /// list according to the following behavior:
3172 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
3173 /// of operation. This grows the number of ops by 2 times.
3174 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
3175 /// 3. If NumOps == NumOperands, trim the reserved space.
3177 void IndirectBrInst::resizeOperands(unsigned NumOps) {
3178 unsigned e = getNumOperands();
3181 } else if (NumOps*2 > NumOperands) {
3182 // No resize needed.
3183 if (ReservedSpace >= NumOps) return;
3184 } else if (NumOps == NumOperands) {
3185 if (ReservedSpace == NumOps) return;
3190 ReservedSpace = NumOps;
3191 Use *NewOps = allocHungoffUses(NumOps);
3192 Use *OldOps = OperandList;
3193 for (unsigned i = 0; i != e; ++i)
3194 NewOps[i] = OldOps[i];
3195 OperandList = NewOps;
3196 if (OldOps) Use::zap(OldOps, OldOps + e, true);
3199 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3200 Instruction *InsertBefore)
3201 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3202 0, 0, InsertBefore) {
3203 init(Address, NumCases);
3206 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3207 BasicBlock *InsertAtEnd)
3208 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3209 0, 0, InsertAtEnd) {
3210 init(Address, NumCases);
3213 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3214 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3215 allocHungoffUses(IBI.getNumOperands()),
3216 IBI.getNumOperands()) {
3217 Use *OL = OperandList, *InOL = IBI.OperandList;
3218 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3220 SubclassOptionalData = IBI.SubclassOptionalData;
3223 IndirectBrInst::~IndirectBrInst() {
3224 dropHungoffUses(OperandList);
3227 /// addDestination - Add a destination.
3229 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3230 unsigned OpNo = NumOperands;
3231 if (OpNo+1 > ReservedSpace)
3232 resizeOperands(0); // Get more space!
3233 // Initialize some new operands.
3234 assert(OpNo < ReservedSpace && "Growing didn't work!");
3235 NumOperands = OpNo+1;
3236 OperandList[OpNo] = DestBB;
3239 /// removeDestination - This method removes the specified successor from the
3240 /// indirectbr instruction.
3241 void IndirectBrInst::removeDestination(unsigned idx) {
3242 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3244 unsigned NumOps = getNumOperands();
3245 Use *OL = OperandList;
3247 // Replace this value with the last one.
3248 OL[idx+1] = OL[NumOps-1];
3250 // Nuke the last value.
3251 OL[NumOps-1].set(0);
3252 NumOperands = NumOps-1;
3255 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3256 return getSuccessor(idx);
3258 unsigned IndirectBrInst::getNumSuccessorsV() const {
3259 return getNumSuccessors();
3261 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3262 setSuccessor(idx, B);
3265 //===----------------------------------------------------------------------===//
3266 // clone_impl() implementations
3267 //===----------------------------------------------------------------------===//
3269 // Define these methods here so vtables don't get emitted into every translation
3270 // unit that uses these classes.
3272 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3273 return new (getNumOperands()) GetElementPtrInst(*this);
3276 BinaryOperator *BinaryOperator::clone_impl() const {
3277 return Create(getOpcode(), Op<0>(), Op<1>());
3280 FCmpInst* FCmpInst::clone_impl() const {
3281 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3284 ICmpInst* ICmpInst::clone_impl() const {
3285 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3288 ExtractValueInst *ExtractValueInst::clone_impl() const {
3289 return new ExtractValueInst(*this);
3292 InsertValueInst *InsertValueInst::clone_impl() const {
3293 return new InsertValueInst(*this);
3296 AllocaInst *AllocaInst::clone_impl() const {
3297 return new AllocaInst(getAllocatedType(),
3298 (Value*)getOperand(0),
3302 LoadInst *LoadInst::clone_impl() const {
3303 return new LoadInst(getOperand(0),
3304 Twine(), isVolatile(),
3308 StoreInst *StoreInst::clone_impl() const {
3309 return new StoreInst(getOperand(0), getOperand(1),
3310 isVolatile(), getAlignment());
3313 TruncInst *TruncInst::clone_impl() const {
3314 return new TruncInst(getOperand(0), getType());
3317 ZExtInst *ZExtInst::clone_impl() const {
3318 return new ZExtInst(getOperand(0), getType());
3321 SExtInst *SExtInst::clone_impl() const {
3322 return new SExtInst(getOperand(0), getType());
3325 FPTruncInst *FPTruncInst::clone_impl() const {
3326 return new FPTruncInst(getOperand(0), getType());
3329 FPExtInst *FPExtInst::clone_impl() const {
3330 return new FPExtInst(getOperand(0), getType());
3333 UIToFPInst *UIToFPInst::clone_impl() const {
3334 return new UIToFPInst(getOperand(0), getType());
3337 SIToFPInst *SIToFPInst::clone_impl() const {
3338 return new SIToFPInst(getOperand(0), getType());
3341 FPToUIInst *FPToUIInst::clone_impl() const {
3342 return new FPToUIInst(getOperand(0), getType());
3345 FPToSIInst *FPToSIInst::clone_impl() const {
3346 return new FPToSIInst(getOperand(0), getType());
3349 PtrToIntInst *PtrToIntInst::clone_impl() const {
3350 return new PtrToIntInst(getOperand(0), getType());
3353 IntToPtrInst *IntToPtrInst::clone_impl() const {
3354 return new IntToPtrInst(getOperand(0), getType());
3357 BitCastInst *BitCastInst::clone_impl() const {
3358 return new BitCastInst(getOperand(0), getType());
3361 CallInst *CallInst::clone_impl() const {
3362 return new(getNumOperands()) CallInst(*this);
3365 SelectInst *SelectInst::clone_impl() const {
3366 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3369 VAArgInst *VAArgInst::clone_impl() const {
3370 return new VAArgInst(getOperand(0), getType());
3373 ExtractElementInst *ExtractElementInst::clone_impl() const {
3374 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3377 InsertElementInst *InsertElementInst::clone_impl() const {
3378 return InsertElementInst::Create(getOperand(0),
3383 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3384 return new ShuffleVectorInst(getOperand(0),
3389 PHINode *PHINode::clone_impl() const {
3390 return new PHINode(*this);
3393 ReturnInst *ReturnInst::clone_impl() const {
3394 return new(getNumOperands()) ReturnInst(*this);
3397 BranchInst *BranchInst::clone_impl() const {
3398 unsigned Ops(getNumOperands());
3399 return new(Ops, Ops == 1) BranchInst(*this);
3402 SwitchInst *SwitchInst::clone_impl() const {
3403 return new SwitchInst(*this);
3406 IndirectBrInst *IndirectBrInst::clone_impl() const {
3407 return new IndirectBrInst(*this);
3411 InvokeInst *InvokeInst::clone_impl() const {
3412 return new(getNumOperands()) InvokeInst(*this);
3415 UnwindInst *UnwindInst::clone_impl() const {
3416 LLVMContext &Context = getContext();
3417 return new UnwindInst(Context);
3420 UnreachableInst *UnreachableInst::clone_impl() const {
3421 LLVMContext &Context = getContext();
3422 return new UnreachableInst(Context);