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 #undef CALLSITE_DELEGATE_GETTER
102 #undef CALLSITE_DELEGATE_SETTER
104 //===----------------------------------------------------------------------===//
105 // TerminatorInst Class
106 //===----------------------------------------------------------------------===//
108 // Out of line virtual method, so the vtable, etc has a home.
109 TerminatorInst::~TerminatorInst() {
112 //===----------------------------------------------------------------------===//
113 // UnaryInstruction Class
114 //===----------------------------------------------------------------------===//
116 // Out of line virtual method, so the vtable, etc has a home.
117 UnaryInstruction::~UnaryInstruction() {
120 //===----------------------------------------------------------------------===//
122 //===----------------------------------------------------------------------===//
124 /// areInvalidOperands - Return a string if the specified operands are invalid
125 /// for a select operation, otherwise return null.
126 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
127 if (Op1->getType() != Op2->getType())
128 return "both values to select must have same type";
130 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
132 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
133 return "vector select condition element type must be i1";
134 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
136 return "selected values for vector select must be vectors";
137 if (ET->getNumElements() != VT->getNumElements())
138 return "vector select requires selected vectors to have "
139 "the same vector length as select condition";
140 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
141 return "select condition must be i1 or <n x i1>";
147 //===----------------------------------------------------------------------===//
149 //===----------------------------------------------------------------------===//
151 PHINode::PHINode(const PHINode &PN)
152 : Instruction(PN.getType(), Instruction::PHI,
153 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
154 ReservedSpace(PN.getNumOperands()) {
155 Use *OL = OperandList;
156 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
157 OL[i] = PN.getOperand(i);
158 OL[i+1] = PN.getOperand(i+1);
160 SubclassOptionalData = PN.SubclassOptionalData;
163 PHINode::~PHINode() {
165 dropHungoffUses(OperandList);
168 // removeIncomingValue - Remove an incoming value. This is useful if a
169 // predecessor basic block is deleted.
170 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
171 unsigned NumOps = getNumOperands();
172 Use *OL = OperandList;
173 assert(Idx*2 < NumOps && "BB not in PHI node!");
174 Value *Removed = OL[Idx*2];
176 // Move everything after this operand down.
178 // FIXME: we could just swap with the end of the list, then erase. However,
179 // client might not expect this to happen. The code as it is thrashes the
180 // use/def lists, which is kinda lame.
181 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
186 // Nuke the last value.
188 OL[NumOps-2+1].set(0);
189 NumOperands = NumOps-2;
191 // If the PHI node is dead, because it has zero entries, nuke it now.
192 if (NumOps == 2 && DeletePHIIfEmpty) {
193 // If anyone is using this PHI, make them use a dummy value instead...
194 replaceAllUsesWith(UndefValue::get(getType()));
200 /// resizeOperands - resize operands - This adjusts the length of the operands
201 /// list according to the following behavior:
202 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
203 /// of operation. This grows the number of ops by 1.5 times.
204 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
205 /// 3. If NumOps == NumOperands, trim the reserved space.
207 void PHINode::resizeOperands(unsigned NumOps) {
208 unsigned e = getNumOperands();
211 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
212 } else if (NumOps*2 > NumOperands) {
214 if (ReservedSpace >= NumOps) return;
215 } else if (NumOps == NumOperands) {
216 if (ReservedSpace == NumOps) return;
221 ReservedSpace = NumOps;
222 Use *OldOps = OperandList;
223 Use *NewOps = allocHungoffUses(NumOps);
224 std::copy(OldOps, OldOps + e, NewOps);
225 OperandList = NewOps;
226 if (OldOps) Use::zap(OldOps, OldOps + e, true);
229 /// hasConstantValue - If the specified PHI node always merges together the same
230 /// value, return the value, otherwise return null.
232 /// If the PHI has undef operands, but all the rest of the operands are
233 /// some unique value, return that value if it can be proved that the
234 /// value dominates the PHI. If DT is null, use a conservative check,
235 /// otherwise use DT to test for dominance.
237 Value *PHINode::hasConstantValue(DominatorTree *DT) const {
238 // If the PHI node only has one incoming value, eliminate the PHI node.
239 if (getNumIncomingValues() == 1) {
240 if (getIncomingValue(0) != this) // not X = phi X
241 return getIncomingValue(0);
242 return UndefValue::get(getType()); // Self cycle is dead.
245 // Otherwise if all of the incoming values are the same for the PHI, replace
246 // the PHI node with the incoming value.
249 bool HasUndefInput = false;
250 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
251 if (isa<UndefValue>(getIncomingValue(i))) {
252 HasUndefInput = true;
253 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
254 if (InVal && getIncomingValue(i) != InVal)
255 return 0; // Not the same, bail out.
256 InVal = getIncomingValue(i);
259 // The only case that could cause InVal to be null is if we have a PHI node
260 // that only has entries for itself. In this case, there is no entry into the
261 // loop, so kill the PHI.
263 if (InVal == 0) InVal = UndefValue::get(getType());
265 // If we have a PHI node like phi(X, undef, X), where X is defined by some
266 // instruction, we cannot always return X as the result of the PHI node. Only
267 // do this if X is not an instruction (thus it must dominate the PHI block),
268 // or if the client is prepared to deal with this possibility.
269 if (!HasUndefInput || !isa<Instruction>(InVal))
272 Instruction *IV = cast<Instruction>(InVal);
274 // We have a DominatorTree. Do a precise test.
275 if (!DT->dominates(IV, this))
278 // If it is in the entry block, it obviously dominates everything.
279 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
281 return 0; // Cannot guarantee that InVal dominates this PHINode.
284 // All of the incoming values are the same, return the value now.
289 //===----------------------------------------------------------------------===//
290 // CallInst Implementation
291 //===----------------------------------------------------------------------===//
293 CallInst::~CallInst() {
296 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
297 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
298 Use *OL = OperandList;
301 const FunctionType *FTy =
302 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
303 FTy = FTy; // silence warning.
305 assert((NumParams == FTy->getNumParams() ||
306 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
307 "Calling a function with bad signature!");
308 for (unsigned i = 0; i != NumParams; ++i) {
309 assert((i >= FTy->getNumParams() ||
310 FTy->getParamType(i) == Params[i]->getType()) &&
311 "Calling a function with a bad signature!");
316 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
317 assert(NumOperands == 3 && "NumOperands not set up?");
318 Use *OL = OperandList;
323 const FunctionType *FTy =
324 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
325 FTy = FTy; // silence warning.
327 assert((FTy->getNumParams() == 2 ||
328 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
329 "Calling a function with bad signature");
330 assert((0 >= FTy->getNumParams() ||
331 FTy->getParamType(0) == Actual1->getType()) &&
332 "Calling a function with a bad signature!");
333 assert((1 >= FTy->getNumParams() ||
334 FTy->getParamType(1) == Actual2->getType()) &&
335 "Calling a function with a bad signature!");
338 void CallInst::init(Value *Func, Value *Actual) {
339 assert(NumOperands == 2 && "NumOperands not set up?");
340 Use *OL = OperandList;
344 const FunctionType *FTy =
345 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
346 FTy = FTy; // silence warning.
348 assert((FTy->getNumParams() == 1 ||
349 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
350 "Calling a function with bad signature");
351 assert((0 == FTy->getNumParams() ||
352 FTy->getParamType(0) == Actual->getType()) &&
353 "Calling a function with a bad signature!");
356 void CallInst::init(Value *Func) {
357 assert(NumOperands == 1 && "NumOperands not set up?");
358 Use *OL = OperandList;
361 const FunctionType *FTy =
362 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
363 FTy = FTy; // silence warning.
365 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
368 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
369 Instruction *InsertBefore)
370 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
371 ->getElementType())->getReturnType(),
373 OperandTraits<CallInst>::op_end(this) - 2,
379 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
380 BasicBlock *InsertAtEnd)
381 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
382 ->getElementType())->getReturnType(),
384 OperandTraits<CallInst>::op_end(this) - 2,
389 CallInst::CallInst(Value *Func, const Twine &Name,
390 Instruction *InsertBefore)
391 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
392 ->getElementType())->getReturnType(),
394 OperandTraits<CallInst>::op_end(this) - 1,
400 CallInst::CallInst(Value *Func, const Twine &Name,
401 BasicBlock *InsertAtEnd)
402 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
403 ->getElementType())->getReturnType(),
405 OperandTraits<CallInst>::op_end(this) - 1,
411 CallInst::CallInst(const CallInst &CI)
412 : Instruction(CI.getType(), Instruction::Call,
413 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
414 CI.getNumOperands()) {
415 setAttributes(CI.getAttributes());
416 setTailCall(CI.isTailCall());
417 setCallingConv(CI.getCallingConv());
419 Use *OL = OperandList;
420 Use *InOL = CI.OperandList;
421 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
423 SubclassOptionalData = CI.SubclassOptionalData;
426 void CallInst::addAttribute(unsigned i, Attributes attr) {
427 AttrListPtr PAL = getAttributes();
428 PAL = PAL.addAttr(i, attr);
432 void CallInst::removeAttribute(unsigned i, Attributes attr) {
433 AttrListPtr PAL = getAttributes();
434 PAL = PAL.removeAttr(i, attr);
438 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
439 if (AttributeList.paramHasAttr(i, attr))
441 if (const Function *F = getCalledFunction())
442 return F->paramHasAttr(i, attr);
446 /// IsConstantOne - Return true only if val is constant int 1
447 static bool IsConstantOne(Value *val) {
448 assert(val && "IsConstantOne does not work with NULL val");
449 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
452 static Instruction *createMalloc(Instruction *InsertBefore,
453 BasicBlock *InsertAtEnd, const Type *IntPtrTy,
454 const Type *AllocTy, Value *AllocSize,
455 Value *ArraySize, Function *MallocF,
457 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
458 "createMalloc needs either InsertBefore or InsertAtEnd");
460 // malloc(type) becomes:
461 // bitcast (i8* malloc(typeSize)) to type*
462 // malloc(type, arraySize) becomes:
463 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
465 ArraySize = ConstantInt::get(IntPtrTy, 1);
466 else if (ArraySize->getType() != IntPtrTy) {
468 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
471 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
475 if (!IsConstantOne(ArraySize)) {
476 if (IsConstantOne(AllocSize)) {
477 AllocSize = ArraySize; // Operand * 1 = Operand
478 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
479 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
481 // Malloc arg is constant product of type size and array size
482 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
484 // Multiply type size by the array size...
486 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
487 "mallocsize", InsertBefore);
489 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
490 "mallocsize", InsertAtEnd);
494 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
495 // Create the call to Malloc.
496 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
497 Module* M = BB->getParent()->getParent();
498 const Type *BPTy = Type::getInt8PtrTy(BB->getContext());
499 Value *MallocFunc = MallocF;
501 // prototype malloc as "void *malloc(size_t)"
502 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
503 const PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
504 CallInst *MCall = NULL;
505 Instruction *Result = NULL;
507 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
509 if (Result->getType() != AllocPtrType)
510 // Create a cast instruction to convert to the right type...
511 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
513 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
515 if (Result->getType() != AllocPtrType) {
516 InsertAtEnd->getInstList().push_back(MCall);
517 // Create a cast instruction to convert to the right type...
518 Result = new BitCastInst(MCall, AllocPtrType, Name);
521 MCall->setTailCall();
522 if (Function *F = dyn_cast<Function>(MallocFunc)) {
523 MCall->setCallingConv(F->getCallingConv());
524 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
526 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
531 /// CreateMalloc - Generate the IR for a call to malloc:
532 /// 1. Compute the malloc call's argument as the specified type's size,
533 /// possibly multiplied by the array size if the array size is not
535 /// 2. Call malloc with that argument.
536 /// 3. Bitcast the result of the malloc call to the specified type.
537 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
538 const Type *IntPtrTy, const Type *AllocTy,
539 Value *AllocSize, Value *ArraySize,
541 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
542 ArraySize, NULL, Name);
545 /// CreateMalloc - Generate the IR for a call to malloc:
546 /// 1. Compute the malloc call's argument as the specified type's size,
547 /// possibly multiplied by the array size if the array size is not
549 /// 2. Call malloc with that argument.
550 /// 3. Bitcast the result of the malloc call to the specified type.
551 /// Note: This function does not add the bitcast to the basic block, that is the
552 /// responsibility of the caller.
553 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
554 const Type *IntPtrTy, const Type *AllocTy,
555 Value *AllocSize, Value *ArraySize,
556 Function *MallocF, const Twine &Name) {
557 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
558 ArraySize, MallocF, Name);
561 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
562 BasicBlock *InsertAtEnd) {
563 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
564 "createFree needs either InsertBefore or InsertAtEnd");
565 assert(Source->getType()->isPointerTy() &&
566 "Can not free something of nonpointer type!");
568 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
569 Module* M = BB->getParent()->getParent();
571 const Type *VoidTy = Type::getVoidTy(M->getContext());
572 const Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
573 // prototype free as "void free(void*)"
574 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
575 CallInst* Result = NULL;
576 Value *PtrCast = Source;
578 if (Source->getType() != IntPtrTy)
579 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
580 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
582 if (Source->getType() != IntPtrTy)
583 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
584 Result = CallInst::Create(FreeFunc, PtrCast, "");
586 Result->setTailCall();
587 if (Function *F = dyn_cast<Function>(FreeFunc))
588 Result->setCallingConv(F->getCallingConv());
593 /// CreateFree - Generate the IR for a call to the builtin free function.
594 void CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
595 createFree(Source, InsertBefore, NULL);
598 /// CreateFree - Generate the IR for a call to the builtin free function.
599 /// Note: This function does not add the call to the basic block, that is the
600 /// responsibility of the caller.
601 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
602 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
603 assert(FreeCall && "CreateFree did not create a CallInst");
607 //===----------------------------------------------------------------------===//
608 // InvokeInst Implementation
609 //===----------------------------------------------------------------------===//
611 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
612 Value* const *Args, unsigned NumArgs) {
613 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
614 Use *OL = OperandList;
618 const FunctionType *FTy =
619 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
620 FTy = FTy; // silence warning.
622 assert(((NumArgs == FTy->getNumParams()) ||
623 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
624 "Calling a function with bad signature");
626 for (unsigned i = 0, e = NumArgs; i != e; i++) {
627 assert((i >= FTy->getNumParams() ||
628 FTy->getParamType(i) == Args[i]->getType()) &&
629 "Invoking a function with a bad signature!");
635 InvokeInst::InvokeInst(const InvokeInst &II)
636 : TerminatorInst(II.getType(), Instruction::Invoke,
637 OperandTraits<InvokeInst>::op_end(this)
638 - II.getNumOperands(),
639 II.getNumOperands()) {
640 setAttributes(II.getAttributes());
641 setCallingConv(II.getCallingConv());
642 Use *OL = OperandList, *InOL = II.OperandList;
643 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
645 SubclassOptionalData = II.SubclassOptionalData;
648 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
649 return getSuccessor(idx);
651 unsigned InvokeInst::getNumSuccessorsV() const {
652 return getNumSuccessors();
654 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
655 return setSuccessor(idx, B);
658 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
659 if (AttributeList.paramHasAttr(i, attr))
661 if (const Function *F = getCalledFunction())
662 return F->paramHasAttr(i, attr);
666 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
667 AttrListPtr PAL = getAttributes();
668 PAL = PAL.addAttr(i, attr);
672 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
673 AttrListPtr PAL = getAttributes();
674 PAL = PAL.removeAttr(i, attr);
679 //===----------------------------------------------------------------------===//
680 // ReturnInst Implementation
681 //===----------------------------------------------------------------------===//
683 ReturnInst::ReturnInst(const ReturnInst &RI)
684 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
685 OperandTraits<ReturnInst>::op_end(this) -
687 RI.getNumOperands()) {
688 if (RI.getNumOperands())
689 Op<0>() = RI.Op<0>();
690 SubclassOptionalData = RI.SubclassOptionalData;
693 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
694 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
695 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
700 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
701 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
702 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
707 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
708 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
709 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
712 unsigned ReturnInst::getNumSuccessorsV() const {
713 return getNumSuccessors();
716 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
717 /// emit the vtable for the class in this translation unit.
718 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
719 llvm_unreachable("ReturnInst has no successors!");
722 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
723 llvm_unreachable("ReturnInst has no successors!");
727 ReturnInst::~ReturnInst() {
730 //===----------------------------------------------------------------------===//
731 // UnwindInst Implementation
732 //===----------------------------------------------------------------------===//
734 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
735 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
736 0, 0, InsertBefore) {
738 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
739 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
744 unsigned UnwindInst::getNumSuccessorsV() const {
745 return getNumSuccessors();
748 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
749 llvm_unreachable("UnwindInst has no successors!");
752 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
753 llvm_unreachable("UnwindInst has no successors!");
757 //===----------------------------------------------------------------------===//
758 // UnreachableInst Implementation
759 //===----------------------------------------------------------------------===//
761 UnreachableInst::UnreachableInst(LLVMContext &Context,
762 Instruction *InsertBefore)
763 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
764 0, 0, InsertBefore) {
766 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
767 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
771 unsigned UnreachableInst::getNumSuccessorsV() const {
772 return getNumSuccessors();
775 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
776 llvm_unreachable("UnwindInst has no successors!");
779 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
780 llvm_unreachable("UnwindInst has no successors!");
784 //===----------------------------------------------------------------------===//
785 // BranchInst Implementation
786 //===----------------------------------------------------------------------===//
788 void BranchInst::AssertOK() {
790 assert(getCondition()->getType()->isIntegerTy(1) &&
791 "May only branch on boolean predicates!");
794 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
795 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
796 OperandTraits<BranchInst>::op_end(this) - 1,
798 assert(IfTrue != 0 && "Branch destination may not be null!");
801 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
802 Instruction *InsertBefore)
803 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
804 OperandTraits<BranchInst>::op_end(this) - 3,
814 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
815 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
816 OperandTraits<BranchInst>::op_end(this) - 1,
818 assert(IfTrue != 0 && "Branch destination may not be null!");
822 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
823 BasicBlock *InsertAtEnd)
824 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
825 OperandTraits<BranchInst>::op_end(this) - 3,
836 BranchInst::BranchInst(const BranchInst &BI) :
837 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
838 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
839 BI.getNumOperands()) {
840 Op<-1>() = BI.Op<-1>();
841 if (BI.getNumOperands() != 1) {
842 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
843 Op<-3>() = BI.Op<-3>();
844 Op<-2>() = BI.Op<-2>();
846 SubclassOptionalData = BI.SubclassOptionalData;
850 Use* Use::getPrefix() {
851 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
852 if (PotentialPrefix.getOpaqueValue())
855 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
858 BranchInst::~BranchInst() {
859 if (NumOperands == 1) {
860 if (Use *Prefix = OperandList->getPrefix()) {
863 // mark OperandList to have a special value for scrutiny
864 // by baseclass destructors and operator delete
865 OperandList = Prefix;
868 OperandList = op_begin();
874 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
875 return getSuccessor(idx);
877 unsigned BranchInst::getNumSuccessorsV() const {
878 return getNumSuccessors();
880 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
881 setSuccessor(idx, B);
885 //===----------------------------------------------------------------------===//
886 // AllocaInst Implementation
887 //===----------------------------------------------------------------------===//
889 static Value *getAISize(LLVMContext &Context, Value *Amt) {
891 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
893 assert(!isa<BasicBlock>(Amt) &&
894 "Passed basic block into allocation size parameter! Use other ctor");
895 assert(Amt->getType()->isIntegerTy(32) &&
896 "Allocation array size is not a 32-bit integer!");
901 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
902 const Twine &Name, Instruction *InsertBefore)
903 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
904 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
906 assert(!Ty->isVoidTy() && "Cannot allocate void!");
910 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
911 const Twine &Name, BasicBlock *InsertAtEnd)
912 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
913 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
915 assert(!Ty->isVoidTy() && "Cannot allocate void!");
919 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
920 Instruction *InsertBefore)
921 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
922 getAISize(Ty->getContext(), 0), InsertBefore) {
924 assert(!Ty->isVoidTy() && "Cannot allocate void!");
928 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
929 BasicBlock *InsertAtEnd)
930 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
931 getAISize(Ty->getContext(), 0), InsertAtEnd) {
933 assert(!Ty->isVoidTy() && "Cannot allocate void!");
937 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
938 const Twine &Name, Instruction *InsertBefore)
939 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
940 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
942 assert(!Ty->isVoidTy() && "Cannot allocate void!");
946 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
947 const Twine &Name, BasicBlock *InsertAtEnd)
948 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
949 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
951 assert(!Ty->isVoidTy() && "Cannot allocate void!");
955 // Out of line virtual method, so the vtable, etc has a home.
956 AllocaInst::~AllocaInst() {
959 void AllocaInst::setAlignment(unsigned Align) {
960 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
961 setInstructionSubclassData(Log2_32(Align) + 1);
962 assert(getAlignment() == Align && "Alignment representation error!");
965 bool AllocaInst::isArrayAllocation() const {
966 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
967 return CI->getZExtValue() != 1;
971 const Type *AllocaInst::getAllocatedType() const {
972 return getType()->getElementType();
975 /// isStaticAlloca - Return true if this alloca is in the entry block of the
976 /// function and is a constant size. If so, the code generator will fold it
977 /// into the prolog/epilog code, so it is basically free.
978 bool AllocaInst::isStaticAlloca() const {
979 // Must be constant size.
980 if (!isa<ConstantInt>(getArraySize())) return false;
982 // Must be in the entry block.
983 const BasicBlock *Parent = getParent();
984 return Parent == &Parent->getParent()->front();
987 //===----------------------------------------------------------------------===//
988 // LoadInst Implementation
989 //===----------------------------------------------------------------------===//
991 void LoadInst::AssertOK() {
992 assert(getOperand(0)->getType()->isPointerTy() &&
993 "Ptr must have pointer type.");
996 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
997 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
998 Load, Ptr, InsertBef) {
1005 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1006 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1007 Load, Ptr, InsertAE) {
1014 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1015 Instruction *InsertBef)
1016 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1017 Load, Ptr, InsertBef) {
1018 setVolatile(isVolatile);
1024 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1025 unsigned Align, Instruction *InsertBef)
1026 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1027 Load, Ptr, InsertBef) {
1028 setVolatile(isVolatile);
1029 setAlignment(Align);
1034 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1035 unsigned Align, BasicBlock *InsertAE)
1036 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1037 Load, Ptr, InsertAE) {
1038 setVolatile(isVolatile);
1039 setAlignment(Align);
1044 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1045 BasicBlock *InsertAE)
1046 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1047 Load, Ptr, InsertAE) {
1048 setVolatile(isVolatile);
1056 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1057 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1058 Load, Ptr, InsertBef) {
1062 if (Name && Name[0]) setName(Name);
1065 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1066 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1067 Load, Ptr, InsertAE) {
1071 if (Name && Name[0]) setName(Name);
1074 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1075 Instruction *InsertBef)
1076 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1077 Load, Ptr, InsertBef) {
1078 setVolatile(isVolatile);
1081 if (Name && Name[0]) setName(Name);
1084 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1085 BasicBlock *InsertAE)
1086 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1087 Load, Ptr, InsertAE) {
1088 setVolatile(isVolatile);
1091 if (Name && Name[0]) setName(Name);
1094 void LoadInst::setAlignment(unsigned Align) {
1095 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1096 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1097 ((Log2_32(Align)+1)<<1));
1100 //===----------------------------------------------------------------------===//
1101 // StoreInst Implementation
1102 //===----------------------------------------------------------------------===//
1104 void StoreInst::AssertOK() {
1105 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1106 assert(getOperand(1)->getType()->isPointerTy() &&
1107 "Ptr must have pointer type!");
1108 assert(getOperand(0)->getType() ==
1109 cast<PointerType>(getOperand(1)->getType())->getElementType()
1110 && "Ptr must be a pointer to Val type!");
1114 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1115 : Instruction(Type::getVoidTy(val->getContext()), Store,
1116 OperandTraits<StoreInst>::op_begin(this),
1117 OperandTraits<StoreInst>::operands(this),
1126 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1127 : Instruction(Type::getVoidTy(val->getContext()), Store,
1128 OperandTraits<StoreInst>::op_begin(this),
1129 OperandTraits<StoreInst>::operands(this),
1138 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1139 Instruction *InsertBefore)
1140 : Instruction(Type::getVoidTy(val->getContext()), Store,
1141 OperandTraits<StoreInst>::op_begin(this),
1142 OperandTraits<StoreInst>::operands(this),
1146 setVolatile(isVolatile);
1151 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1152 unsigned Align, Instruction *InsertBefore)
1153 : Instruction(Type::getVoidTy(val->getContext()), Store,
1154 OperandTraits<StoreInst>::op_begin(this),
1155 OperandTraits<StoreInst>::operands(this),
1159 setVolatile(isVolatile);
1160 setAlignment(Align);
1164 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1165 unsigned Align, BasicBlock *InsertAtEnd)
1166 : Instruction(Type::getVoidTy(val->getContext()), Store,
1167 OperandTraits<StoreInst>::op_begin(this),
1168 OperandTraits<StoreInst>::operands(this),
1172 setVolatile(isVolatile);
1173 setAlignment(Align);
1177 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1178 BasicBlock *InsertAtEnd)
1179 : Instruction(Type::getVoidTy(val->getContext()), Store,
1180 OperandTraits<StoreInst>::op_begin(this),
1181 OperandTraits<StoreInst>::operands(this),
1185 setVolatile(isVolatile);
1190 void StoreInst::setAlignment(unsigned Align) {
1191 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1192 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1193 ((Log2_32(Align)+1) << 1));
1196 //===----------------------------------------------------------------------===//
1197 // GetElementPtrInst Implementation
1198 //===----------------------------------------------------------------------===//
1200 static unsigned retrieveAddrSpace(const Value *Val) {
1201 return cast<PointerType>(Val->getType())->getAddressSpace();
1204 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1205 const Twine &Name) {
1206 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1207 Use *OL = OperandList;
1210 for (unsigned i = 0; i != NumIdx; ++i)
1216 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1217 assert(NumOperands == 2 && "NumOperands not initialized?");
1218 Use *OL = OperandList;
1225 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1226 : Instruction(GEPI.getType(), GetElementPtr,
1227 OperandTraits<GetElementPtrInst>::op_end(this)
1228 - GEPI.getNumOperands(),
1229 GEPI.getNumOperands()) {
1230 Use *OL = OperandList;
1231 Use *GEPIOL = GEPI.OperandList;
1232 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1234 SubclassOptionalData = GEPI.SubclassOptionalData;
1237 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1238 const Twine &Name, Instruction *InBe)
1239 : Instruction(PointerType::get(
1240 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1242 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1244 init(Ptr, Idx, Name);
1247 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1248 const Twine &Name, BasicBlock *IAE)
1249 : Instruction(PointerType::get(
1250 checkType(getIndexedType(Ptr->getType(),Idx)),
1251 retrieveAddrSpace(Ptr)),
1253 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1255 init(Ptr, Idx, Name);
1258 /// getIndexedType - Returns the type of the element that would be accessed with
1259 /// a gep instruction with the specified parameters.
1261 /// The Idxs pointer should point to a continuous piece of memory containing the
1262 /// indices, either as Value* or uint64_t.
1264 /// A null type is returned if the indices are invalid for the specified
1267 template <typename IndexTy>
1268 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1270 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1271 if (!PTy) return 0; // Type isn't a pointer type!
1272 const Type *Agg = PTy->getElementType();
1274 // Handle the special case of the empty set index set, which is always valid.
1278 // If there is at least one index, the top level type must be sized, otherwise
1279 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1280 // that contain opaque types) under the assumption that it will be resolved to
1281 // a sane type later.
1282 if (!Agg->isSized() && !Agg->isAbstract())
1285 unsigned CurIdx = 1;
1286 for (; CurIdx != NumIdx; ++CurIdx) {
1287 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1288 if (!CT || CT->isPointerTy()) return 0;
1289 IndexTy Index = Idxs[CurIdx];
1290 if (!CT->indexValid(Index)) return 0;
1291 Agg = CT->getTypeAtIndex(Index);
1293 // If the new type forwards to another type, then it is in the middle
1294 // of being refined to another type (and hence, may have dropped all
1295 // references to what it was using before). So, use the new forwarded
1297 if (const Type *Ty = Agg->getForwardedType())
1300 return CurIdx == NumIdx ? Agg : 0;
1303 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1306 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1309 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1310 uint64_t const *Idxs,
1312 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1315 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1316 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1317 if (!PTy) return 0; // Type isn't a pointer type!
1319 // Check the pointer index.
1320 if (!PTy->indexValid(Idx)) return 0;
1322 return PTy->getElementType();
1326 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1327 /// zeros. If so, the result pointer and the first operand have the same
1328 /// value, just potentially different types.
1329 bool GetElementPtrInst::hasAllZeroIndices() const {
1330 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1331 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1332 if (!CI->isZero()) return false;
1340 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1341 /// constant integers. If so, the result pointer and the first operand have
1342 /// a constant offset between them.
1343 bool GetElementPtrInst::hasAllConstantIndices() const {
1344 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1345 if (!isa<ConstantInt>(getOperand(i)))
1351 void GetElementPtrInst::setIsInBounds(bool B) {
1352 cast<GEPOperator>(this)->setIsInBounds(B);
1355 bool GetElementPtrInst::isInBounds() const {
1356 return cast<GEPOperator>(this)->isInBounds();
1359 //===----------------------------------------------------------------------===//
1360 // ExtractElementInst Implementation
1361 //===----------------------------------------------------------------------===//
1363 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1365 Instruction *InsertBef)
1366 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1368 OperandTraits<ExtractElementInst>::op_begin(this),
1370 assert(isValidOperands(Val, Index) &&
1371 "Invalid extractelement instruction operands!");
1377 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1379 BasicBlock *InsertAE)
1380 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1382 OperandTraits<ExtractElementInst>::op_begin(this),
1384 assert(isValidOperands(Val, Index) &&
1385 "Invalid extractelement instruction operands!");
1393 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1394 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1400 //===----------------------------------------------------------------------===//
1401 // InsertElementInst Implementation
1402 //===----------------------------------------------------------------------===//
1404 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1406 Instruction *InsertBef)
1407 : Instruction(Vec->getType(), InsertElement,
1408 OperandTraits<InsertElementInst>::op_begin(this),
1410 assert(isValidOperands(Vec, Elt, Index) &&
1411 "Invalid insertelement instruction operands!");
1418 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1420 BasicBlock *InsertAE)
1421 : Instruction(Vec->getType(), InsertElement,
1422 OperandTraits<InsertElementInst>::op_begin(this),
1424 assert(isValidOperands(Vec, Elt, Index) &&
1425 "Invalid insertelement instruction operands!");
1433 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1434 const Value *Index) {
1435 if (!Vec->getType()->isVectorTy())
1436 return false; // First operand of insertelement must be vector type.
1438 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1439 return false;// Second operand of insertelement must be vector element type.
1441 if (!Index->getType()->isIntegerTy(32))
1442 return false; // Third operand of insertelement must be i32.
1447 //===----------------------------------------------------------------------===//
1448 // ShuffleVectorInst Implementation
1449 //===----------------------------------------------------------------------===//
1451 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1453 Instruction *InsertBefore)
1454 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1455 cast<VectorType>(Mask->getType())->getNumElements()),
1457 OperandTraits<ShuffleVectorInst>::op_begin(this),
1458 OperandTraits<ShuffleVectorInst>::operands(this),
1460 assert(isValidOperands(V1, V2, Mask) &&
1461 "Invalid shuffle vector instruction operands!");
1468 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1470 BasicBlock *InsertAtEnd)
1471 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1472 cast<VectorType>(Mask->getType())->getNumElements()),
1474 OperandTraits<ShuffleVectorInst>::op_begin(this),
1475 OperandTraits<ShuffleVectorInst>::operands(this),
1477 assert(isValidOperands(V1, V2, Mask) &&
1478 "Invalid shuffle vector instruction operands!");
1486 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1487 const Value *Mask) {
1488 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1491 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1492 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1493 !MaskTy->getElementType()->isIntegerTy(32))
1498 /// getMaskValue - Return the index from the shuffle mask for the specified
1499 /// output result. This is either -1 if the element is undef or a number less
1500 /// than 2*numelements.
1501 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1502 const Constant *Mask = cast<Constant>(getOperand(2));
1503 if (isa<UndefValue>(Mask)) return -1;
1504 if (isa<ConstantAggregateZero>(Mask)) return 0;
1505 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1506 assert(i < MaskCV->getNumOperands() && "Index out of range");
1508 if (isa<UndefValue>(MaskCV->getOperand(i)))
1510 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1513 //===----------------------------------------------------------------------===//
1514 // InsertValueInst Class
1515 //===----------------------------------------------------------------------===//
1517 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1518 unsigned NumIdx, const Twine &Name) {
1519 assert(NumOperands == 2 && "NumOperands not initialized?");
1523 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1527 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1528 const Twine &Name) {
1529 assert(NumOperands == 2 && "NumOperands not initialized?");
1533 Indices.push_back(Idx);
1537 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1538 : Instruction(IVI.getType(), InsertValue,
1539 OperandTraits<InsertValueInst>::op_begin(this), 2),
1540 Indices(IVI.Indices) {
1541 Op<0>() = IVI.getOperand(0);
1542 Op<1>() = IVI.getOperand(1);
1543 SubclassOptionalData = IVI.SubclassOptionalData;
1546 InsertValueInst::InsertValueInst(Value *Agg,
1550 Instruction *InsertBefore)
1551 : Instruction(Agg->getType(), InsertValue,
1552 OperandTraits<InsertValueInst>::op_begin(this),
1554 init(Agg, Val, Idx, Name);
1557 InsertValueInst::InsertValueInst(Value *Agg,
1561 BasicBlock *InsertAtEnd)
1562 : Instruction(Agg->getType(), InsertValue,
1563 OperandTraits<InsertValueInst>::op_begin(this),
1565 init(Agg, Val, Idx, Name);
1568 //===----------------------------------------------------------------------===//
1569 // ExtractValueInst Class
1570 //===----------------------------------------------------------------------===//
1572 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1573 const Twine &Name) {
1574 assert(NumOperands == 1 && "NumOperands not initialized?");
1576 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1580 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1581 assert(NumOperands == 1 && "NumOperands not initialized?");
1583 Indices.push_back(Idx);
1587 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1588 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1589 Indices(EVI.Indices) {
1590 SubclassOptionalData = EVI.SubclassOptionalData;
1593 // getIndexedType - Returns the type of the element that would be extracted
1594 // with an extractvalue instruction with the specified parameters.
1596 // A null type is returned if the indices are invalid for the specified
1599 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1600 const unsigned *Idxs,
1602 unsigned CurIdx = 0;
1603 for (; CurIdx != NumIdx; ++CurIdx) {
1604 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1605 if (!CT || CT->isPointerTy() || CT->isVectorTy()) return 0;
1606 unsigned Index = Idxs[CurIdx];
1607 if (!CT->indexValid(Index)) return 0;
1608 Agg = CT->getTypeAtIndex(Index);
1610 // If the new type forwards to another type, then it is in the middle
1611 // of being refined to another type (and hence, may have dropped all
1612 // references to what it was using before). So, use the new forwarded
1614 if (const Type *Ty = Agg->getForwardedType())
1617 return CurIdx == NumIdx ? Agg : 0;
1620 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1622 return getIndexedType(Agg, &Idx, 1);
1625 //===----------------------------------------------------------------------===//
1626 // BinaryOperator Class
1627 //===----------------------------------------------------------------------===//
1629 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1630 /// type is floating-point, to help provide compatibility with an older API.
1632 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1634 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1635 if (Ty->isFPOrFPVectorTy()) {
1636 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1637 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1638 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1643 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1644 const Type *Ty, const Twine &Name,
1645 Instruction *InsertBefore)
1646 : Instruction(Ty, AdjustIType(iType, Ty),
1647 OperandTraits<BinaryOperator>::op_begin(this),
1648 OperandTraits<BinaryOperator>::operands(this),
1652 init(AdjustIType(iType, Ty));
1656 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1657 const Type *Ty, const Twine &Name,
1658 BasicBlock *InsertAtEnd)
1659 : Instruction(Ty, AdjustIType(iType, Ty),
1660 OperandTraits<BinaryOperator>::op_begin(this),
1661 OperandTraits<BinaryOperator>::operands(this),
1665 init(AdjustIType(iType, Ty));
1670 void BinaryOperator::init(BinaryOps iType) {
1671 Value *LHS = getOperand(0), *RHS = getOperand(1);
1672 LHS = LHS; RHS = RHS; // Silence warnings.
1673 assert(LHS->getType() == RHS->getType() &&
1674 "Binary operator operand types must match!");
1679 assert(getType() == LHS->getType() &&
1680 "Arithmetic operation should return same type as operands!");
1681 assert(getType()->isIntOrIntVectorTy() &&
1682 "Tried to create an integer operation on a non-integer type!");
1684 case FAdd: case FSub:
1686 assert(getType() == LHS->getType() &&
1687 "Arithmetic operation should return same type as operands!");
1688 assert(getType()->isFPOrFPVectorTy() &&
1689 "Tried to create a floating-point operation on a "
1690 "non-floating-point type!");
1694 assert(getType() == LHS->getType() &&
1695 "Arithmetic operation should return same type as operands!");
1696 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1697 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1698 "Incorrect operand type (not integer) for S/UDIV");
1701 assert(getType() == LHS->getType() &&
1702 "Arithmetic operation should return same type as operands!");
1703 assert(getType()->isFPOrFPVectorTy() &&
1704 "Incorrect operand type (not floating point) for FDIV");
1708 assert(getType() == LHS->getType() &&
1709 "Arithmetic operation should return same type as operands!");
1710 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1711 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1712 "Incorrect operand type (not integer) for S/UREM");
1715 assert(getType() == LHS->getType() &&
1716 "Arithmetic operation should return same type as operands!");
1717 assert(getType()->isFPOrFPVectorTy() &&
1718 "Incorrect operand type (not floating point) for FREM");
1723 assert(getType() == LHS->getType() &&
1724 "Shift operation should return same type as operands!");
1725 assert((getType()->isIntegerTy() ||
1726 (getType()->isVectorTy() &&
1727 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1728 "Tried to create a shift operation on a non-integral type!");
1732 assert(getType() == LHS->getType() &&
1733 "Logical operation should return same type as operands!");
1734 assert((getType()->isIntegerTy() ||
1735 (getType()->isVectorTy() &&
1736 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1737 "Tried to create a logical operation on a non-integral type!");
1745 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1747 Instruction *InsertBefore) {
1748 assert(S1->getType() == S2->getType() &&
1749 "Cannot create binary operator with two operands of differing type!");
1750 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1753 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1755 BasicBlock *InsertAtEnd) {
1756 BinaryOperator *Res = Create(Op, S1, S2, Name);
1757 InsertAtEnd->getInstList().push_back(Res);
1761 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1762 Instruction *InsertBefore) {
1763 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1764 return new BinaryOperator(Instruction::Sub,
1766 Op->getType(), Name, InsertBefore);
1769 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1770 BasicBlock *InsertAtEnd) {
1771 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1772 return new BinaryOperator(Instruction::Sub,
1774 Op->getType(), Name, InsertAtEnd);
1777 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1778 Instruction *InsertBefore) {
1779 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1780 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1783 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1784 BasicBlock *InsertAtEnd) {
1785 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1786 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1789 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1790 Instruction *InsertBefore) {
1791 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1792 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1795 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1796 BasicBlock *InsertAtEnd) {
1797 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1798 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1801 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1802 Instruction *InsertBefore) {
1803 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1804 return new BinaryOperator(Instruction::FSub,
1806 Op->getType(), Name, InsertBefore);
1809 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1810 BasicBlock *InsertAtEnd) {
1811 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1812 return new BinaryOperator(Instruction::FSub,
1814 Op->getType(), Name, InsertAtEnd);
1817 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1818 Instruction *InsertBefore) {
1820 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1821 C = Constant::getAllOnesValue(PTy->getElementType());
1822 C = ConstantVector::get(
1823 std::vector<Constant*>(PTy->getNumElements(), C));
1825 C = Constant::getAllOnesValue(Op->getType());
1828 return new BinaryOperator(Instruction::Xor, Op, C,
1829 Op->getType(), Name, InsertBefore);
1832 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1833 BasicBlock *InsertAtEnd) {
1835 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1836 // Create a vector of all ones values.
1837 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1838 AllOnes = ConstantVector::get(
1839 std::vector<Constant*>(PTy->getNumElements(), Elt));
1841 AllOnes = Constant::getAllOnesValue(Op->getType());
1844 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1845 Op->getType(), Name, InsertAtEnd);
1849 // isConstantAllOnes - Helper function for several functions below
1850 static inline bool isConstantAllOnes(const Value *V) {
1851 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1852 return CI->isAllOnesValue();
1853 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1854 return CV->isAllOnesValue();
1858 bool BinaryOperator::isNeg(const Value *V) {
1859 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1860 if (Bop->getOpcode() == Instruction::Sub)
1861 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1862 return C->isNegativeZeroValue();
1866 bool BinaryOperator::isFNeg(const Value *V) {
1867 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1868 if (Bop->getOpcode() == Instruction::FSub)
1869 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1870 return C->isNegativeZeroValue();
1874 bool BinaryOperator::isNot(const Value *V) {
1875 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1876 return (Bop->getOpcode() == Instruction::Xor &&
1877 (isConstantAllOnes(Bop->getOperand(1)) ||
1878 isConstantAllOnes(Bop->getOperand(0))));
1882 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1883 return cast<BinaryOperator>(BinOp)->getOperand(1);
1886 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1887 return getNegArgument(const_cast<Value*>(BinOp));
1890 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1891 return cast<BinaryOperator>(BinOp)->getOperand(1);
1894 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1895 return getFNegArgument(const_cast<Value*>(BinOp));
1898 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1899 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1900 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1901 Value *Op0 = BO->getOperand(0);
1902 Value *Op1 = BO->getOperand(1);
1903 if (isConstantAllOnes(Op0)) return Op1;
1905 assert(isConstantAllOnes(Op1));
1909 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1910 return getNotArgument(const_cast<Value*>(BinOp));
1914 // swapOperands - Exchange the two operands to this instruction. This
1915 // instruction is safe to use on any binary instruction and does not
1916 // modify the semantics of the instruction. If the instruction is
1917 // order dependent (SetLT f.e.) the opcode is changed.
1919 bool BinaryOperator::swapOperands() {
1920 if (!isCommutative())
1921 return true; // Can't commute operands
1922 Op<0>().swap(Op<1>());
1926 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1927 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1930 void BinaryOperator::setHasNoSignedWrap(bool b) {
1931 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1934 void BinaryOperator::setIsExact(bool b) {
1935 cast<SDivOperator>(this)->setIsExact(b);
1938 bool BinaryOperator::hasNoUnsignedWrap() const {
1939 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1942 bool BinaryOperator::hasNoSignedWrap() const {
1943 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1946 bool BinaryOperator::isExact() const {
1947 return cast<SDivOperator>(this)->isExact();
1950 //===----------------------------------------------------------------------===//
1952 //===----------------------------------------------------------------------===//
1954 // Just determine if this cast only deals with integral->integral conversion.
1955 bool CastInst::isIntegerCast() const {
1956 switch (getOpcode()) {
1957 default: return false;
1958 case Instruction::ZExt:
1959 case Instruction::SExt:
1960 case Instruction::Trunc:
1962 case Instruction::BitCast:
1963 return getOperand(0)->getType()->isIntegerTy() &&
1964 getType()->isIntegerTy();
1968 bool CastInst::isLosslessCast() const {
1969 // Only BitCast can be lossless, exit fast if we're not BitCast
1970 if (getOpcode() != Instruction::BitCast)
1973 // Identity cast is always lossless
1974 const Type* SrcTy = getOperand(0)->getType();
1975 const Type* DstTy = getType();
1979 // Pointer to pointer is always lossless.
1980 if (SrcTy->isPointerTy())
1981 return DstTy->isPointerTy();
1982 return false; // Other types have no identity values
1985 /// This function determines if the CastInst does not require any bits to be
1986 /// changed in order to effect the cast. Essentially, it identifies cases where
1987 /// no code gen is necessary for the cast, hence the name no-op cast. For
1988 /// example, the following are all no-op casts:
1989 /// # bitcast i32* %x to i8*
1990 /// # bitcast <2 x i32> %x to <4 x i16>
1991 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1992 /// @brief Determine if a cast is a no-op.
1993 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1994 switch (getOpcode()) {
1996 assert(!"Invalid CastOp");
1997 case Instruction::Trunc:
1998 case Instruction::ZExt:
1999 case Instruction::SExt:
2000 case Instruction::FPTrunc:
2001 case Instruction::FPExt:
2002 case Instruction::UIToFP:
2003 case Instruction::SIToFP:
2004 case Instruction::FPToUI:
2005 case Instruction::FPToSI:
2006 return false; // These always modify bits
2007 case Instruction::BitCast:
2008 return true; // BitCast never modifies bits.
2009 case Instruction::PtrToInt:
2010 return IntPtrTy->getScalarSizeInBits() ==
2011 getType()->getScalarSizeInBits();
2012 case Instruction::IntToPtr:
2013 return IntPtrTy->getScalarSizeInBits() ==
2014 getOperand(0)->getType()->getScalarSizeInBits();
2018 /// This function determines if a pair of casts can be eliminated and what
2019 /// opcode should be used in the elimination. This assumes that there are two
2020 /// instructions like this:
2021 /// * %F = firstOpcode SrcTy %x to MidTy
2022 /// * %S = secondOpcode MidTy %F to DstTy
2023 /// The function returns a resultOpcode so these two casts can be replaced with:
2024 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2025 /// If no such cast is permited, the function returns 0.
2026 unsigned CastInst::isEliminableCastPair(
2027 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2028 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
2030 // Define the 144 possibilities for these two cast instructions. The values
2031 // in this matrix determine what to do in a given situation and select the
2032 // case in the switch below. The rows correspond to firstOp, the columns
2033 // correspond to secondOp. In looking at the table below, keep in mind
2034 // the following cast properties:
2036 // Size Compare Source Destination
2037 // Operator Src ? Size Type Sign Type Sign
2038 // -------- ------------ ------------------- ---------------------
2039 // TRUNC > Integer Any Integral Any
2040 // ZEXT < Integral Unsigned Integer Any
2041 // SEXT < Integral Signed Integer Any
2042 // FPTOUI n/a FloatPt n/a Integral Unsigned
2043 // FPTOSI n/a FloatPt n/a Integral Signed
2044 // UITOFP n/a Integral Unsigned FloatPt n/a
2045 // SITOFP n/a Integral Signed FloatPt n/a
2046 // FPTRUNC > FloatPt n/a FloatPt n/a
2047 // FPEXT < FloatPt n/a FloatPt n/a
2048 // PTRTOINT n/a Pointer n/a Integral Unsigned
2049 // INTTOPTR n/a Integral Unsigned Pointer n/a
2050 // BITCONVERT = FirstClass n/a FirstClass n/a
2052 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2053 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2054 // into "fptoui double to i64", but this loses information about the range
2055 // of the produced value (we no longer know the top-part is all zeros).
2056 // Further this conversion is often much more expensive for typical hardware,
2057 // and causes issues when building libgcc. We disallow fptosi+sext for the
2059 const unsigned numCastOps =
2060 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2061 static const uint8_t CastResults[numCastOps][numCastOps] = {
2062 // T F F U S F F P I B -+
2063 // R Z S P P I I T P 2 N T |
2064 // U E E 2 2 2 2 R E I T C +- secondOp
2065 // N X X U S F F N X N 2 V |
2066 // C T T I I P P C T T P T -+
2067 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2068 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2069 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2070 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2071 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2072 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2073 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2074 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2075 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2076 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2077 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2078 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2081 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2082 [secondOp-Instruction::CastOpsBegin];
2085 // categorically disallowed
2088 // allowed, use first cast's opcode
2091 // allowed, use second cast's opcode
2094 // no-op cast in second op implies firstOp as long as the DestTy
2095 // is integer and we are not converting between a vector and a
2097 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2101 // no-op cast in second op implies firstOp as long as the DestTy
2102 // is floating point.
2103 if (DstTy->isFloatingPointTy())
2107 // no-op cast in first op implies secondOp as long as the SrcTy
2109 if (SrcTy->isIntegerTy())
2113 // no-op cast in first op implies secondOp as long as the SrcTy
2114 // is a floating point.
2115 if (SrcTy->isFloatingPointTy())
2119 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2122 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2123 unsigned MidSize = MidTy->getScalarSizeInBits();
2124 if (MidSize >= PtrSize)
2125 return Instruction::BitCast;
2129 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2130 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2131 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2132 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2133 unsigned DstSize = DstTy->getScalarSizeInBits();
2134 if (SrcSize == DstSize)
2135 return Instruction::BitCast;
2136 else if (SrcSize < DstSize)
2140 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2141 return Instruction::ZExt;
2143 // fpext followed by ftrunc is allowed if the bit size returned to is
2144 // the same as the original, in which case its just a bitcast
2146 return Instruction::BitCast;
2147 return 0; // If the types are not the same we can't eliminate it.
2149 // bitcast followed by ptrtoint is allowed as long as the bitcast
2150 // is a pointer to pointer cast.
2151 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2155 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2156 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2160 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2163 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2164 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2165 unsigned DstSize = DstTy->getScalarSizeInBits();
2166 if (SrcSize <= PtrSize && SrcSize == DstSize)
2167 return Instruction::BitCast;
2171 // cast combination can't happen (error in input). This is for all cases
2172 // where the MidTy is not the same for the two cast instructions.
2173 assert(!"Invalid Cast Combination");
2176 assert(!"Error in CastResults table!!!");
2182 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2183 const Twine &Name, Instruction *InsertBefore) {
2184 // Construct and return the appropriate CastInst subclass
2186 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2187 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2188 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2189 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2190 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2191 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2192 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2193 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2194 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2195 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2196 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2197 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2199 assert(!"Invalid opcode provided");
2204 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2205 const Twine &Name, BasicBlock *InsertAtEnd) {
2206 // Construct and return the appropriate CastInst subclass
2208 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2209 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2210 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2211 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2212 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2213 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2214 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2215 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2216 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2217 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2218 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2219 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2221 assert(!"Invalid opcode provided");
2226 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2228 Instruction *InsertBefore) {
2229 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2230 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2231 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2234 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2236 BasicBlock *InsertAtEnd) {
2237 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2238 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2239 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2242 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2244 Instruction *InsertBefore) {
2245 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2246 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2247 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2250 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2252 BasicBlock *InsertAtEnd) {
2253 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2254 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2255 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2258 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2260 Instruction *InsertBefore) {
2261 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2262 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2263 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2266 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2268 BasicBlock *InsertAtEnd) {
2269 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2270 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2271 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2274 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2276 BasicBlock *InsertAtEnd) {
2277 assert(S->getType()->isPointerTy() && "Invalid cast");
2278 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2281 if (Ty->isIntegerTy())
2282 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2283 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2286 /// @brief Create a BitCast or a PtrToInt cast instruction
2287 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2289 Instruction *InsertBefore) {
2290 assert(S->getType()->isPointerTy() && "Invalid cast");
2291 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2294 if (Ty->isIntegerTy())
2295 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2296 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2299 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2300 bool isSigned, const Twine &Name,
2301 Instruction *InsertBefore) {
2302 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2303 "Invalid integer cast");
2304 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2305 unsigned DstBits = Ty->getScalarSizeInBits();
2306 Instruction::CastOps opcode =
2307 (SrcBits == DstBits ? Instruction::BitCast :
2308 (SrcBits > DstBits ? Instruction::Trunc :
2309 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2310 return Create(opcode, C, Ty, Name, InsertBefore);
2313 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2314 bool isSigned, const Twine &Name,
2315 BasicBlock *InsertAtEnd) {
2316 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2318 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2319 unsigned DstBits = Ty->getScalarSizeInBits();
2320 Instruction::CastOps opcode =
2321 (SrcBits == DstBits ? Instruction::BitCast :
2322 (SrcBits > DstBits ? Instruction::Trunc :
2323 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2324 return Create(opcode, C, Ty, Name, InsertAtEnd);
2327 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2329 Instruction *InsertBefore) {
2330 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2332 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2333 unsigned DstBits = Ty->getScalarSizeInBits();
2334 Instruction::CastOps opcode =
2335 (SrcBits == DstBits ? Instruction::BitCast :
2336 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2337 return Create(opcode, C, Ty, Name, InsertBefore);
2340 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2342 BasicBlock *InsertAtEnd) {
2343 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2345 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2346 unsigned DstBits = Ty->getScalarSizeInBits();
2347 Instruction::CastOps opcode =
2348 (SrcBits == DstBits ? Instruction::BitCast :
2349 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2350 return Create(opcode, C, Ty, Name, InsertAtEnd);
2353 // Check whether it is valid to call getCastOpcode for these types.
2354 // This routine must be kept in sync with getCastOpcode.
2355 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2356 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2359 if (SrcTy == DestTy)
2362 // Get the bit sizes, we'll need these
2363 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2364 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2366 // Run through the possibilities ...
2367 if (DestTy->isIntegerTy()) { // Casting to integral
2368 if (SrcTy->isIntegerTy()) { // Casting from integral
2370 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2372 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2373 // Casting from vector
2374 return DestBits == PTy->getBitWidth();
2375 } else { // Casting from something else
2376 return SrcTy->isPointerTy();
2378 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2379 if (SrcTy->isIntegerTy()) { // Casting from integral
2381 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2383 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2384 // Casting from vector
2385 return DestBits == PTy->getBitWidth();
2386 } else { // Casting from something else
2389 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2390 // Casting to vector
2391 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2392 // Casting from vector
2393 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2394 } else { // Casting from something else
2395 return DestPTy->getBitWidth() == SrcBits;
2397 } else if (DestTy->isPointerTy()) { // Casting to pointer
2398 if (SrcTy->isPointerTy()) { // Casting from pointer
2400 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2402 } else { // Casting from something else
2405 } else { // Casting to something else
2410 // Provide a way to get a "cast" where the cast opcode is inferred from the
2411 // types and size of the operand. This, basically, is a parallel of the
2412 // logic in the castIsValid function below. This axiom should hold:
2413 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2414 // should not assert in castIsValid. In other words, this produces a "correct"
2415 // casting opcode for the arguments passed to it.
2416 // This routine must be kept in sync with isCastable.
2417 Instruction::CastOps
2418 CastInst::getCastOpcode(
2419 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2420 // Get the bit sizes, we'll need these
2421 const Type *SrcTy = Src->getType();
2422 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2423 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2425 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2426 "Only first class types are castable!");
2428 // Run through the possibilities ...
2429 if (DestTy->isIntegerTy()) { // Casting to integral
2430 if (SrcTy->isIntegerTy()) { // Casting from integral
2431 if (DestBits < SrcBits)
2432 return Trunc; // int -> smaller int
2433 else if (DestBits > SrcBits) { // its an extension
2435 return SExt; // signed -> SEXT
2437 return ZExt; // unsigned -> ZEXT
2439 return BitCast; // Same size, No-op cast
2441 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2443 return FPToSI; // FP -> sint
2445 return FPToUI; // FP -> uint
2446 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2447 assert(DestBits == PTy->getBitWidth() &&
2448 "Casting vector to integer of different width");
2450 return BitCast; // Same size, no-op cast
2452 assert(SrcTy->isPointerTy() &&
2453 "Casting from a value that is not first-class type");
2454 return PtrToInt; // ptr -> int
2456 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2457 if (SrcTy->isIntegerTy()) { // Casting from integral
2459 return SIToFP; // sint -> FP
2461 return UIToFP; // uint -> FP
2462 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2463 if (DestBits < SrcBits) {
2464 return FPTrunc; // FP -> smaller FP
2465 } else if (DestBits > SrcBits) {
2466 return FPExt; // FP -> larger FP
2468 return BitCast; // same size, no-op cast
2470 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2471 assert(DestBits == PTy->getBitWidth() &&
2472 "Casting vector to floating point of different width");
2474 return BitCast; // same size, no-op cast
2476 llvm_unreachable("Casting pointer or non-first class to float");
2478 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2479 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2480 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2481 "Casting vector to vector of different widths");
2483 return BitCast; // vector -> vector
2484 } else if (DestPTy->getBitWidth() == SrcBits) {
2485 return BitCast; // float/int -> vector
2487 assert(!"Illegal cast to vector (wrong type or size)");
2489 } else if (DestTy->isPointerTy()) {
2490 if (SrcTy->isPointerTy()) {
2491 return BitCast; // ptr -> ptr
2492 } else if (SrcTy->isIntegerTy()) {
2493 return IntToPtr; // int -> ptr
2495 assert(!"Casting pointer to other than pointer or int");
2498 assert(!"Casting to type that is not first-class");
2501 // If we fall through to here we probably hit an assertion cast above
2502 // and assertions are not turned on. Anything we return is an error, so
2503 // BitCast is as good a choice as any.
2507 //===----------------------------------------------------------------------===//
2508 // CastInst SubClass Constructors
2509 //===----------------------------------------------------------------------===//
2511 /// Check that the construction parameters for a CastInst are correct. This
2512 /// could be broken out into the separate constructors but it is useful to have
2513 /// it in one place and to eliminate the redundant code for getting the sizes
2514 /// of the types involved.
2516 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2518 // Check for type sanity on the arguments
2519 const Type *SrcTy = S->getType();
2520 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2521 SrcTy->isAggregateType() || DstTy->isAggregateType())
2524 // Get the size of the types in bits, we'll need this later
2525 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2526 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2528 // Switch on the opcode provided
2530 default: return false; // This is an input error
2531 case Instruction::Trunc:
2532 return SrcTy->isIntOrIntVectorTy() &&
2533 DstTy->isIntOrIntVectorTy()&& SrcBitSize > DstBitSize;
2534 case Instruction::ZExt:
2535 return SrcTy->isIntOrIntVectorTy() &&
2536 DstTy->isIntOrIntVectorTy()&& SrcBitSize < DstBitSize;
2537 case Instruction::SExt:
2538 return SrcTy->isIntOrIntVectorTy() &&
2539 DstTy->isIntOrIntVectorTy()&& SrcBitSize < DstBitSize;
2540 case Instruction::FPTrunc:
2541 return SrcTy->isFPOrFPVectorTy() &&
2542 DstTy->isFPOrFPVectorTy() &&
2543 SrcBitSize > DstBitSize;
2544 case Instruction::FPExt:
2545 return SrcTy->isFPOrFPVectorTy() &&
2546 DstTy->isFPOrFPVectorTy() &&
2547 SrcBitSize < DstBitSize;
2548 case Instruction::UIToFP:
2549 case Instruction::SIToFP:
2550 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2551 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2552 return SVTy->getElementType()->isIntOrIntVectorTy() &&
2553 DVTy->getElementType()->isFPOrFPVectorTy() &&
2554 SVTy->getNumElements() == DVTy->getNumElements();
2557 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy();
2558 case Instruction::FPToUI:
2559 case Instruction::FPToSI:
2560 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2561 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2562 return SVTy->getElementType()->isFPOrFPVectorTy() &&
2563 DVTy->getElementType()->isIntOrIntVectorTy() &&
2564 SVTy->getNumElements() == DVTy->getNumElements();
2567 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy();
2568 case Instruction::PtrToInt:
2569 return SrcTy->isPointerTy() && DstTy->isIntegerTy();
2570 case Instruction::IntToPtr:
2571 return SrcTy->isIntegerTy() && DstTy->isPointerTy();
2572 case Instruction::BitCast:
2573 // BitCast implies a no-op cast of type only. No bits change.
2574 // However, you can't cast pointers to anything but pointers.
2575 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2578 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2579 // these cases, the cast is okay if the source and destination bit widths
2581 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2585 TruncInst::TruncInst(
2586 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2587 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2588 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2591 TruncInst::TruncInst(
2592 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2593 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2594 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2598 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2599 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2600 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2604 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2605 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2606 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2609 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2610 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2611 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2615 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2616 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2617 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2620 FPTruncInst::FPTruncInst(
2621 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2622 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2623 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2626 FPTruncInst::FPTruncInst(
2627 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2628 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2629 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2632 FPExtInst::FPExtInst(
2633 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2634 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2635 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2638 FPExtInst::FPExtInst(
2639 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2640 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2641 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2644 UIToFPInst::UIToFPInst(
2645 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2646 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2647 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2650 UIToFPInst::UIToFPInst(
2651 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2652 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2653 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2656 SIToFPInst::SIToFPInst(
2657 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2658 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2659 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2662 SIToFPInst::SIToFPInst(
2663 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2664 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2665 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2668 FPToUIInst::FPToUIInst(
2669 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2670 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2671 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2674 FPToUIInst::FPToUIInst(
2675 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2676 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2677 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2680 FPToSIInst::FPToSIInst(
2681 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2682 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2683 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2686 FPToSIInst::FPToSIInst(
2687 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2688 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2689 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2692 PtrToIntInst::PtrToIntInst(
2693 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2694 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2695 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2698 PtrToIntInst::PtrToIntInst(
2699 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2700 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2701 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2704 IntToPtrInst::IntToPtrInst(
2705 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2706 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2707 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2710 IntToPtrInst::IntToPtrInst(
2711 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2712 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2713 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2716 BitCastInst::BitCastInst(
2717 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2718 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2719 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2722 BitCastInst::BitCastInst(
2723 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2724 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2725 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2728 //===----------------------------------------------------------------------===//
2730 //===----------------------------------------------------------------------===//
2732 void CmpInst::Anchor() const {}
2734 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2735 Value *LHS, Value *RHS, const Twine &Name,
2736 Instruction *InsertBefore)
2737 : Instruction(ty, op,
2738 OperandTraits<CmpInst>::op_begin(this),
2739 OperandTraits<CmpInst>::operands(this),
2743 setPredicate((Predicate)predicate);
2747 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2748 Value *LHS, Value *RHS, const Twine &Name,
2749 BasicBlock *InsertAtEnd)
2750 : Instruction(ty, op,
2751 OperandTraits<CmpInst>::op_begin(this),
2752 OperandTraits<CmpInst>::operands(this),
2756 setPredicate((Predicate)predicate);
2761 CmpInst::Create(OtherOps Op, unsigned short predicate,
2762 Value *S1, Value *S2,
2763 const Twine &Name, Instruction *InsertBefore) {
2764 if (Op == Instruction::ICmp) {
2766 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2769 return new ICmpInst(CmpInst::Predicate(predicate),
2774 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2777 return new FCmpInst(CmpInst::Predicate(predicate),
2782 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2783 const Twine &Name, BasicBlock *InsertAtEnd) {
2784 if (Op == Instruction::ICmp) {
2785 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2788 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2792 void CmpInst::swapOperands() {
2793 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2796 cast<FCmpInst>(this)->swapOperands();
2799 bool CmpInst::isCommutative() {
2800 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2801 return IC->isCommutative();
2802 return cast<FCmpInst>(this)->isCommutative();
2805 bool CmpInst::isEquality() {
2806 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2807 return IC->isEquality();
2808 return cast<FCmpInst>(this)->isEquality();
2812 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2814 default: assert(!"Unknown cmp predicate!");
2815 case ICMP_EQ: return ICMP_NE;
2816 case ICMP_NE: return ICMP_EQ;
2817 case ICMP_UGT: return ICMP_ULE;
2818 case ICMP_ULT: return ICMP_UGE;
2819 case ICMP_UGE: return ICMP_ULT;
2820 case ICMP_ULE: return ICMP_UGT;
2821 case ICMP_SGT: return ICMP_SLE;
2822 case ICMP_SLT: return ICMP_SGE;
2823 case ICMP_SGE: return ICMP_SLT;
2824 case ICMP_SLE: return ICMP_SGT;
2826 case FCMP_OEQ: return FCMP_UNE;
2827 case FCMP_ONE: return FCMP_UEQ;
2828 case FCMP_OGT: return FCMP_ULE;
2829 case FCMP_OLT: return FCMP_UGE;
2830 case FCMP_OGE: return FCMP_ULT;
2831 case FCMP_OLE: return FCMP_UGT;
2832 case FCMP_UEQ: return FCMP_ONE;
2833 case FCMP_UNE: return FCMP_OEQ;
2834 case FCMP_UGT: return FCMP_OLE;
2835 case FCMP_ULT: return FCMP_OGE;
2836 case FCMP_UGE: return FCMP_OLT;
2837 case FCMP_ULE: return FCMP_OGT;
2838 case FCMP_ORD: return FCMP_UNO;
2839 case FCMP_UNO: return FCMP_ORD;
2840 case FCMP_TRUE: return FCMP_FALSE;
2841 case FCMP_FALSE: return FCMP_TRUE;
2845 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2847 default: assert(! "Unknown icmp predicate!");
2848 case ICMP_EQ: case ICMP_NE:
2849 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2851 case ICMP_UGT: return ICMP_SGT;
2852 case ICMP_ULT: return ICMP_SLT;
2853 case ICMP_UGE: return ICMP_SGE;
2854 case ICMP_ULE: return ICMP_SLE;
2858 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2860 default: assert(! "Unknown icmp predicate!");
2861 case ICMP_EQ: case ICMP_NE:
2862 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2864 case ICMP_SGT: return ICMP_UGT;
2865 case ICMP_SLT: return ICMP_ULT;
2866 case ICMP_SGE: return ICMP_UGE;
2867 case ICMP_SLE: return ICMP_ULE;
2871 /// Initialize a set of values that all satisfy the condition with C.
2874 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2877 uint32_t BitWidth = C.getBitWidth();
2879 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2880 case ICmpInst::ICMP_EQ: Upper++; break;
2881 case ICmpInst::ICMP_NE: Lower++; break;
2882 case ICmpInst::ICMP_ULT:
2883 Lower = APInt::getMinValue(BitWidth);
2884 // Check for an empty-set condition.
2886 return ConstantRange(BitWidth, /*isFullSet=*/false);
2888 case ICmpInst::ICMP_SLT:
2889 Lower = APInt::getSignedMinValue(BitWidth);
2890 // Check for an empty-set condition.
2892 return ConstantRange(BitWidth, /*isFullSet=*/false);
2894 case ICmpInst::ICMP_UGT:
2895 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2896 // Check for an empty-set condition.
2898 return ConstantRange(BitWidth, /*isFullSet=*/false);
2900 case ICmpInst::ICMP_SGT:
2901 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2902 // Check for an empty-set condition.
2904 return ConstantRange(BitWidth, /*isFullSet=*/false);
2906 case ICmpInst::ICMP_ULE:
2907 Lower = APInt::getMinValue(BitWidth); Upper++;
2908 // Check for a full-set condition.
2910 return ConstantRange(BitWidth, /*isFullSet=*/true);
2912 case ICmpInst::ICMP_SLE:
2913 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2914 // Check for a full-set condition.
2916 return ConstantRange(BitWidth, /*isFullSet=*/true);
2918 case ICmpInst::ICMP_UGE:
2919 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2920 // Check for a full-set condition.
2922 return ConstantRange(BitWidth, /*isFullSet=*/true);
2924 case ICmpInst::ICMP_SGE:
2925 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2926 // Check for a full-set condition.
2928 return ConstantRange(BitWidth, /*isFullSet=*/true);
2931 return ConstantRange(Lower, Upper);
2934 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2936 default: assert(!"Unknown cmp predicate!");
2937 case ICMP_EQ: case ICMP_NE:
2939 case ICMP_SGT: return ICMP_SLT;
2940 case ICMP_SLT: return ICMP_SGT;
2941 case ICMP_SGE: return ICMP_SLE;
2942 case ICMP_SLE: return ICMP_SGE;
2943 case ICMP_UGT: return ICMP_ULT;
2944 case ICMP_ULT: return ICMP_UGT;
2945 case ICMP_UGE: return ICMP_ULE;
2946 case ICMP_ULE: return ICMP_UGE;
2948 case FCMP_FALSE: case FCMP_TRUE:
2949 case FCMP_OEQ: case FCMP_ONE:
2950 case FCMP_UEQ: case FCMP_UNE:
2951 case FCMP_ORD: case FCMP_UNO:
2953 case FCMP_OGT: return FCMP_OLT;
2954 case FCMP_OLT: return FCMP_OGT;
2955 case FCMP_OGE: return FCMP_OLE;
2956 case FCMP_OLE: return FCMP_OGE;
2957 case FCMP_UGT: return FCMP_ULT;
2958 case FCMP_ULT: return FCMP_UGT;
2959 case FCMP_UGE: return FCMP_ULE;
2960 case FCMP_ULE: return FCMP_UGE;
2964 bool CmpInst::isUnsigned(unsigned short predicate) {
2965 switch (predicate) {
2966 default: return false;
2967 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2968 case ICmpInst::ICMP_UGE: return true;
2972 bool CmpInst::isSigned(unsigned short predicate) {
2973 switch (predicate) {
2974 default: return false;
2975 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2976 case ICmpInst::ICMP_SGE: return true;
2980 bool CmpInst::isOrdered(unsigned short predicate) {
2981 switch (predicate) {
2982 default: return false;
2983 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2984 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2985 case FCmpInst::FCMP_ORD: return true;
2989 bool CmpInst::isUnordered(unsigned short predicate) {
2990 switch (predicate) {
2991 default: return false;
2992 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2993 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2994 case FCmpInst::FCMP_UNO: return true;
2998 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3000 default: return false;
3001 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3002 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3006 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3008 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3009 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3010 default: return false;
3015 //===----------------------------------------------------------------------===//
3016 // SwitchInst Implementation
3017 //===----------------------------------------------------------------------===//
3019 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
3020 assert(Value && Default);
3021 ReservedSpace = 2+NumCases*2;
3023 OperandList = allocHungoffUses(ReservedSpace);
3025 OperandList[0] = Value;
3026 OperandList[1] = Default;
3029 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3030 /// switch on and a default destination. The number of additional cases can
3031 /// be specified here to make memory allocation more efficient. This
3032 /// constructor can also autoinsert before another instruction.
3033 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3034 Instruction *InsertBefore)
3035 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3036 0, 0, InsertBefore) {
3037 init(Value, Default, NumCases);
3040 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3041 /// switch on and a default destination. The number of additional cases can
3042 /// be specified here to make memory allocation more efficient. This
3043 /// constructor also autoinserts at the end of the specified BasicBlock.
3044 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3045 BasicBlock *InsertAtEnd)
3046 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3047 0, 0, InsertAtEnd) {
3048 init(Value, Default, NumCases);
3051 SwitchInst::SwitchInst(const SwitchInst &SI)
3052 : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch,
3053 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
3054 Use *OL = OperandList, *InOL = SI.OperandList;
3055 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
3057 OL[i+1] = InOL[i+1];
3059 SubclassOptionalData = SI.SubclassOptionalData;
3062 SwitchInst::~SwitchInst() {
3063 dropHungoffUses(OperandList);
3067 /// addCase - Add an entry to the switch instruction...
3069 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3070 unsigned OpNo = NumOperands;
3071 if (OpNo+2 > ReservedSpace)
3072 resizeOperands(0); // Get more space!
3073 // Initialize some new operands.
3074 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3075 NumOperands = OpNo+2;
3076 OperandList[OpNo] = OnVal;
3077 OperandList[OpNo+1] = Dest;
3080 /// removeCase - This method removes the specified successor from the switch
3081 /// instruction. Note that this cannot be used to remove the default
3082 /// destination (successor #0).
3084 void SwitchInst::removeCase(unsigned idx) {
3085 assert(idx != 0 && "Cannot remove the default case!");
3086 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3088 unsigned NumOps = getNumOperands();
3089 Use *OL = OperandList;
3091 // Move everything after this operand down.
3093 // FIXME: we could just swap with the end of the list, then erase. However,
3094 // client might not expect this to happen. The code as it is thrashes the
3095 // use/def lists, which is kinda lame.
3096 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
3098 OL[i-2+1] = OL[i+1];
3101 // Nuke the last value.
3102 OL[NumOps-2].set(0);
3103 OL[NumOps-2+1].set(0);
3104 NumOperands = NumOps-2;
3107 /// resizeOperands - resize operands - This adjusts the length of the operands
3108 /// list according to the following behavior:
3109 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
3110 /// of operation. This grows the number of ops by 3 times.
3111 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
3112 /// 3. If NumOps == NumOperands, trim the reserved space.
3114 void SwitchInst::resizeOperands(unsigned NumOps) {
3115 unsigned e = getNumOperands();
3118 } else if (NumOps*2 > NumOperands) {
3119 // No resize needed.
3120 if (ReservedSpace >= NumOps) return;
3121 } else if (NumOps == NumOperands) {
3122 if (ReservedSpace == NumOps) return;
3127 ReservedSpace = NumOps;
3128 Use *NewOps = allocHungoffUses(NumOps);
3129 Use *OldOps = OperandList;
3130 for (unsigned i = 0; i != e; ++i) {
3131 NewOps[i] = OldOps[i];
3133 OperandList = NewOps;
3134 if (OldOps) Use::zap(OldOps, OldOps + e, true);
3138 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3139 return getSuccessor(idx);
3141 unsigned SwitchInst::getNumSuccessorsV() const {
3142 return getNumSuccessors();
3144 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3145 setSuccessor(idx, B);
3148 //===----------------------------------------------------------------------===//
3149 // SwitchInst Implementation
3150 //===----------------------------------------------------------------------===//
3152 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3153 assert(Address && Address->getType()->isPointerTy() &&
3154 "Address of indirectbr must be a pointer");
3155 ReservedSpace = 1+NumDests;
3157 OperandList = allocHungoffUses(ReservedSpace);
3159 OperandList[0] = Address;
3163 /// resizeOperands - resize operands - This adjusts the length of the operands
3164 /// list according to the following behavior:
3165 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
3166 /// of operation. This grows the number of ops by 2 times.
3167 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
3168 /// 3. If NumOps == NumOperands, trim the reserved space.
3170 void IndirectBrInst::resizeOperands(unsigned NumOps) {
3171 unsigned e = getNumOperands();
3174 } else if (NumOps*2 > NumOperands) {
3175 // No resize needed.
3176 if (ReservedSpace >= NumOps) return;
3177 } else if (NumOps == NumOperands) {
3178 if (ReservedSpace == NumOps) return;
3183 ReservedSpace = NumOps;
3184 Use *NewOps = allocHungoffUses(NumOps);
3185 Use *OldOps = OperandList;
3186 for (unsigned i = 0; i != e; ++i)
3187 NewOps[i] = OldOps[i];
3188 OperandList = NewOps;
3189 if (OldOps) Use::zap(OldOps, OldOps + e, true);
3192 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3193 Instruction *InsertBefore)
3194 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3195 0, 0, InsertBefore) {
3196 init(Address, NumCases);
3199 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3200 BasicBlock *InsertAtEnd)
3201 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3202 0, 0, InsertAtEnd) {
3203 init(Address, NumCases);
3206 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3207 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3208 allocHungoffUses(IBI.getNumOperands()),
3209 IBI.getNumOperands()) {
3210 Use *OL = OperandList, *InOL = IBI.OperandList;
3211 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3213 SubclassOptionalData = IBI.SubclassOptionalData;
3216 IndirectBrInst::~IndirectBrInst() {
3217 dropHungoffUses(OperandList);
3220 /// addDestination - Add a destination.
3222 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3223 unsigned OpNo = NumOperands;
3224 if (OpNo+1 > ReservedSpace)
3225 resizeOperands(0); // Get more space!
3226 // Initialize some new operands.
3227 assert(OpNo < ReservedSpace && "Growing didn't work!");
3228 NumOperands = OpNo+1;
3229 OperandList[OpNo] = DestBB;
3232 /// removeDestination - This method removes the specified successor from the
3233 /// indirectbr instruction.
3234 void IndirectBrInst::removeDestination(unsigned idx) {
3235 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3237 unsigned NumOps = getNumOperands();
3238 Use *OL = OperandList;
3240 // Replace this value with the last one.
3241 OL[idx+1] = OL[NumOps-1];
3243 // Nuke the last value.
3244 OL[NumOps-1].set(0);
3245 NumOperands = NumOps-1;
3248 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3249 return getSuccessor(idx);
3251 unsigned IndirectBrInst::getNumSuccessorsV() const {
3252 return getNumSuccessors();
3254 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3255 setSuccessor(idx, B);
3258 //===----------------------------------------------------------------------===//
3259 // clone_impl() implementations
3260 //===----------------------------------------------------------------------===//
3262 // Define these methods here so vtables don't get emitted into every translation
3263 // unit that uses these classes.
3265 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3266 return new (getNumOperands()) GetElementPtrInst(*this);
3269 BinaryOperator *BinaryOperator::clone_impl() const {
3270 return Create(getOpcode(), Op<0>(), Op<1>());
3273 FCmpInst* FCmpInst::clone_impl() const {
3274 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3277 ICmpInst* ICmpInst::clone_impl() const {
3278 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3281 ExtractValueInst *ExtractValueInst::clone_impl() const {
3282 return new ExtractValueInst(*this);
3285 InsertValueInst *InsertValueInst::clone_impl() const {
3286 return new InsertValueInst(*this);
3289 AllocaInst *AllocaInst::clone_impl() const {
3290 return new AllocaInst(getAllocatedType(),
3291 (Value*)getOperand(0),
3295 LoadInst *LoadInst::clone_impl() const {
3296 return new LoadInst(getOperand(0),
3297 Twine(), isVolatile(),
3301 StoreInst *StoreInst::clone_impl() const {
3302 return new StoreInst(getOperand(0), getOperand(1),
3303 isVolatile(), getAlignment());
3306 TruncInst *TruncInst::clone_impl() const {
3307 return new TruncInst(getOperand(0), getType());
3310 ZExtInst *ZExtInst::clone_impl() const {
3311 return new ZExtInst(getOperand(0), getType());
3314 SExtInst *SExtInst::clone_impl() const {
3315 return new SExtInst(getOperand(0), getType());
3318 FPTruncInst *FPTruncInst::clone_impl() const {
3319 return new FPTruncInst(getOperand(0), getType());
3322 FPExtInst *FPExtInst::clone_impl() const {
3323 return new FPExtInst(getOperand(0), getType());
3326 UIToFPInst *UIToFPInst::clone_impl() const {
3327 return new UIToFPInst(getOperand(0), getType());
3330 SIToFPInst *SIToFPInst::clone_impl() const {
3331 return new SIToFPInst(getOperand(0), getType());
3334 FPToUIInst *FPToUIInst::clone_impl() const {
3335 return new FPToUIInst(getOperand(0), getType());
3338 FPToSIInst *FPToSIInst::clone_impl() const {
3339 return new FPToSIInst(getOperand(0), getType());
3342 PtrToIntInst *PtrToIntInst::clone_impl() const {
3343 return new PtrToIntInst(getOperand(0), getType());
3346 IntToPtrInst *IntToPtrInst::clone_impl() const {
3347 return new IntToPtrInst(getOperand(0), getType());
3350 BitCastInst *BitCastInst::clone_impl() const {
3351 return new BitCastInst(getOperand(0), getType());
3354 CallInst *CallInst::clone_impl() const {
3355 return new(getNumOperands()) CallInst(*this);
3358 SelectInst *SelectInst::clone_impl() const {
3359 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3362 VAArgInst *VAArgInst::clone_impl() const {
3363 return new VAArgInst(getOperand(0), getType());
3366 ExtractElementInst *ExtractElementInst::clone_impl() const {
3367 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3370 InsertElementInst *InsertElementInst::clone_impl() const {
3371 return InsertElementInst::Create(getOperand(0),
3376 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3377 return new ShuffleVectorInst(getOperand(0),
3382 PHINode *PHINode::clone_impl() const {
3383 return new PHINode(*this);
3386 ReturnInst *ReturnInst::clone_impl() const {
3387 return new(getNumOperands()) ReturnInst(*this);
3390 BranchInst *BranchInst::clone_impl() const {
3391 unsigned Ops(getNumOperands());
3392 return new(Ops, Ops == 1) BranchInst(*this);
3395 SwitchInst *SwitchInst::clone_impl() const {
3396 return new SwitchInst(*this);
3399 IndirectBrInst *IndirectBrInst::clone_impl() const {
3400 return new IndirectBrInst(*this);
3404 InvokeInst *InvokeInst::clone_impl() const {
3405 return new(getNumOperands()) InvokeInst(*this);
3408 UnwindInst *UnwindInst::clone_impl() const {
3409 LLVMContext &Context = getContext();
3410 return new UnwindInst(Context);
3413 UnreachableInst *UnreachableInst::clone_impl() const {
3414 LLVMContext &Context = getContext();
3415 return new UnreachableInst(Context);