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));
70 /// @brief Return true if the call should not be inlined.
71 bool CallSite::isNoInline() const {
72 CALLSITE_DELEGATE_GETTER(isNoInline());
75 void CallSite::setIsNoInline(bool Value) {
76 CALLSITE_DELEGATE_GETTER(setIsNoInline(Value));
80 bool CallSite::doesNotAccessMemory() const {
81 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
83 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
84 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
86 bool CallSite::onlyReadsMemory() const {
87 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
89 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
90 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
92 bool CallSite::doesNotReturn() const {
93 CALLSITE_DELEGATE_GETTER(doesNotReturn());
95 void CallSite::setDoesNotReturn(bool doesNotReturn) {
96 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
98 bool CallSite::doesNotThrow() const {
99 CALLSITE_DELEGATE_GETTER(doesNotThrow());
101 void CallSite::setDoesNotThrow(bool doesNotThrow) {
102 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
105 bool CallSite::hasArgument(const Value *Arg) const {
106 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
107 if (AI->get() == Arg)
112 User::op_iterator CallSite::getCallee() const {
113 Instruction *II(getInstruction());
115 ? cast<CallInst>(II)->op_begin()
116 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Function
119 #undef CALLSITE_DELEGATE_GETTER
120 #undef CALLSITE_DELEGATE_SETTER
122 //===----------------------------------------------------------------------===//
123 // TerminatorInst Class
124 //===----------------------------------------------------------------------===//
126 // Out of line virtual method, so the vtable, etc has a home.
127 TerminatorInst::~TerminatorInst() {
130 //===----------------------------------------------------------------------===//
131 // UnaryInstruction Class
132 //===----------------------------------------------------------------------===//
134 // Out of line virtual method, so the vtable, etc has a home.
135 UnaryInstruction::~UnaryInstruction() {
138 //===----------------------------------------------------------------------===//
140 //===----------------------------------------------------------------------===//
142 /// areInvalidOperands - Return a string if the specified operands are invalid
143 /// for a select operation, otherwise return null.
144 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
145 if (Op1->getType() != Op2->getType())
146 return "both values to select must have same type";
148 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
150 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
151 return "vector select condition element type must be i1";
152 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
154 return "selected values for vector select must be vectors";
155 if (ET->getNumElements() != VT->getNumElements())
156 return "vector select requires selected vectors to have "
157 "the same vector length as select condition";
158 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
159 return "select condition must be i1 or <n x i1>";
165 //===----------------------------------------------------------------------===//
167 //===----------------------------------------------------------------------===//
169 PHINode::PHINode(const PHINode &PN)
170 : Instruction(PN.getType(), Instruction::PHI,
171 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
172 ReservedSpace(PN.getNumOperands()) {
173 Use *OL = OperandList;
174 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
175 OL[i] = PN.getOperand(i);
176 OL[i+1] = PN.getOperand(i+1);
178 SubclassOptionalData = PN.SubclassOptionalData;
181 PHINode::~PHINode() {
183 dropHungoffUses(OperandList);
186 // removeIncomingValue - Remove an incoming value. This is useful if a
187 // predecessor basic block is deleted.
188 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
189 unsigned NumOps = getNumOperands();
190 Use *OL = OperandList;
191 assert(Idx*2 < NumOps && "BB not in PHI node!");
192 Value *Removed = OL[Idx*2];
194 // Move everything after this operand down.
196 // FIXME: we could just swap with the end of the list, then erase. However,
197 // client might not expect this to happen. The code as it is thrashes the
198 // use/def lists, which is kinda lame.
199 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
204 // Nuke the last value.
206 OL[NumOps-2+1].set(0);
207 NumOperands = NumOps-2;
209 // If the PHI node is dead, because it has zero entries, nuke it now.
210 if (NumOps == 2 && DeletePHIIfEmpty) {
211 // If anyone is using this PHI, make them use a dummy value instead...
212 replaceAllUsesWith(UndefValue::get(getType()));
218 /// resizeOperands - resize operands - This adjusts the length of the operands
219 /// list according to the following behavior:
220 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
221 /// of operation. This grows the number of ops by 1.5 times.
222 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
223 /// 3. If NumOps == NumOperands, trim the reserved space.
225 void PHINode::resizeOperands(unsigned NumOps) {
226 unsigned e = getNumOperands();
229 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
230 } else if (NumOps*2 > NumOperands) {
232 if (ReservedSpace >= NumOps) return;
233 } else if (NumOps == NumOperands) {
234 if (ReservedSpace == NumOps) return;
239 ReservedSpace = NumOps;
240 Use *OldOps = OperandList;
241 Use *NewOps = allocHungoffUses(NumOps);
242 std::copy(OldOps, OldOps + e, NewOps);
243 OperandList = NewOps;
244 if (OldOps) Use::zap(OldOps, OldOps + e, true);
247 /// hasConstantValue - If the specified PHI node always merges together the same
248 /// value, return the value, otherwise return null.
250 /// If the PHI has undef operands, but all the rest of the operands are
251 /// some unique value, return that value if it can be proved that the
252 /// value dominates the PHI. If DT is null, use a conservative check,
253 /// otherwise use DT to test for dominance.
255 Value *PHINode::hasConstantValue(DominatorTree *DT) const {
256 // If the PHI node only has one incoming value, eliminate the PHI node.
257 if (getNumIncomingValues() == 1) {
258 if (getIncomingValue(0) != this) // not X = phi X
259 return getIncomingValue(0);
260 return UndefValue::get(getType()); // Self cycle is dead.
263 // Otherwise if all of the incoming values are the same for the PHI, replace
264 // the PHI node with the incoming value.
267 bool HasUndefInput = false;
268 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
269 if (isa<UndefValue>(getIncomingValue(i))) {
270 HasUndefInput = true;
271 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
272 if (InVal && getIncomingValue(i) != InVal)
273 return 0; // Not the same, bail out.
274 InVal = getIncomingValue(i);
277 // The only case that could cause InVal to be null is if we have a PHI node
278 // that only has entries for itself. In this case, there is no entry into the
279 // loop, so kill the PHI.
281 if (InVal == 0) InVal = UndefValue::get(getType());
283 // If we have a PHI node like phi(X, undef, X), where X is defined by some
284 // instruction, we cannot always return X as the result of the PHI node. Only
285 // do this if X is not an instruction (thus it must dominate the PHI block),
286 // or if the client is prepared to deal with this possibility.
287 if (!HasUndefInput || !isa<Instruction>(InVal))
290 Instruction *IV = cast<Instruction>(InVal);
292 // We have a DominatorTree. Do a precise test.
293 if (!DT->dominates(IV, this))
296 // If it is in the entry block, it obviously dominates everything.
297 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
299 return 0; // Cannot guarantee that InVal dominates this PHINode.
302 // All of the incoming values are the same, return the value now.
307 //===----------------------------------------------------------------------===//
308 // CallInst Implementation
309 //===----------------------------------------------------------------------===//
311 CallInst::~CallInst() {
314 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
315 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
316 Use *OL = OperandList;
319 const FunctionType *FTy =
320 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
321 FTy = FTy; // silence warning.
323 assert((NumParams == FTy->getNumParams() ||
324 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
325 "Calling a function with bad signature!");
326 for (unsigned i = 0; i != NumParams; ++i) {
327 assert((i >= FTy->getNumParams() ||
328 FTy->getParamType(i) == Params[i]->getType()) &&
329 "Calling a function with a bad signature!");
334 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
335 assert(NumOperands == 3 && "NumOperands not set up?");
336 Use *OL = OperandList;
341 const FunctionType *FTy =
342 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
343 FTy = FTy; // silence warning.
345 assert((FTy->getNumParams() == 2 ||
346 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
347 "Calling a function with bad signature");
348 assert((0 >= FTy->getNumParams() ||
349 FTy->getParamType(0) == Actual1->getType()) &&
350 "Calling a function with a bad signature!");
351 assert((1 >= FTy->getNumParams() ||
352 FTy->getParamType(1) == Actual2->getType()) &&
353 "Calling a function with a bad signature!");
356 void CallInst::init(Value *Func, Value *Actual) {
357 assert(NumOperands == 2 && "NumOperands not set up?");
358 Use *OL = OperandList;
362 const FunctionType *FTy =
363 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
364 FTy = FTy; // silence warning.
366 assert((FTy->getNumParams() == 1 ||
367 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
368 "Calling a function with bad signature");
369 assert((0 == FTy->getNumParams() ||
370 FTy->getParamType(0) == Actual->getType()) &&
371 "Calling a function with a bad signature!");
374 void CallInst::init(Value *Func) {
375 assert(NumOperands == 1 && "NumOperands not set up?");
376 Use *OL = OperandList;
379 const FunctionType *FTy =
380 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
381 FTy = FTy; // silence warning.
383 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
386 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
387 Instruction *InsertBefore)
388 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
389 ->getElementType())->getReturnType(),
391 OperandTraits<CallInst>::op_end(this) - 2,
397 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
398 BasicBlock *InsertAtEnd)
399 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
400 ->getElementType())->getReturnType(),
402 OperandTraits<CallInst>::op_end(this) - 2,
407 CallInst::CallInst(Value *Func, const Twine &Name,
408 Instruction *InsertBefore)
409 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
410 ->getElementType())->getReturnType(),
412 OperandTraits<CallInst>::op_end(this) - 1,
418 CallInst::CallInst(Value *Func, const Twine &Name,
419 BasicBlock *InsertAtEnd)
420 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
421 ->getElementType())->getReturnType(),
423 OperandTraits<CallInst>::op_end(this) - 1,
429 CallInst::CallInst(const CallInst &CI)
430 : Instruction(CI.getType(), Instruction::Call,
431 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
432 CI.getNumOperands()) {
433 setAttributes(CI.getAttributes());
434 setTailCall(CI.isTailCall());
435 setCallingConv(CI.getCallingConv());
437 Use *OL = OperandList;
438 Use *InOL = CI.OperandList;
439 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
441 SubclassOptionalData = CI.SubclassOptionalData;
444 void CallInst::addAttribute(unsigned i, Attributes attr) {
445 AttrListPtr PAL = getAttributes();
446 PAL = PAL.addAttr(i, attr);
450 void CallInst::removeAttribute(unsigned i, Attributes attr) {
451 AttrListPtr PAL = getAttributes();
452 PAL = PAL.removeAttr(i, attr);
456 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
457 if (AttributeList.paramHasAttr(i, attr))
459 if (const Function *F = getCalledFunction())
460 return F->paramHasAttr(i, attr);
464 /// IsConstantOne - Return true only if val is constant int 1
465 static bool IsConstantOne(Value *val) {
466 assert(val && "IsConstantOne does not work with NULL val");
467 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
470 static Instruction *createMalloc(Instruction *InsertBefore,
471 BasicBlock *InsertAtEnd, const Type *IntPtrTy,
472 const Type *AllocTy, Value *AllocSize,
473 Value *ArraySize, Function *MallocF,
475 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
476 "createMalloc needs either InsertBefore or InsertAtEnd");
478 // malloc(type) becomes:
479 // bitcast (i8* malloc(typeSize)) to type*
480 // malloc(type, arraySize) becomes:
481 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
483 ArraySize = ConstantInt::get(IntPtrTy, 1);
484 else if (ArraySize->getType() != IntPtrTy) {
486 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
489 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
493 if (!IsConstantOne(ArraySize)) {
494 if (IsConstantOne(AllocSize)) {
495 AllocSize = ArraySize; // Operand * 1 = Operand
496 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
497 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
499 // Malloc arg is constant product of type size and array size
500 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
502 // Multiply type size by the array size...
504 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
505 "mallocsize", InsertBefore);
507 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
508 "mallocsize", InsertAtEnd);
512 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
513 // Create the call to Malloc.
514 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
515 Module* M = BB->getParent()->getParent();
516 const Type *BPTy = Type::getInt8PtrTy(BB->getContext());
517 Value *MallocFunc = MallocF;
519 // prototype malloc as "void *malloc(size_t)"
520 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
521 const PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
522 CallInst *MCall = NULL;
523 Instruction *Result = NULL;
525 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
527 if (Result->getType() != AllocPtrType)
528 // Create a cast instruction to convert to the right type...
529 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
531 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
533 if (Result->getType() != AllocPtrType) {
534 InsertAtEnd->getInstList().push_back(MCall);
535 // Create a cast instruction to convert to the right type...
536 Result = new BitCastInst(MCall, AllocPtrType, Name);
539 MCall->setTailCall();
540 if (Function *F = dyn_cast<Function>(MallocFunc)) {
541 MCall->setCallingConv(F->getCallingConv());
542 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
544 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
549 /// CreateMalloc - Generate the IR for a call to malloc:
550 /// 1. Compute the malloc call's argument as the specified type's size,
551 /// possibly multiplied by the array size if the array size is not
553 /// 2. Call malloc with that argument.
554 /// 3. Bitcast the result of the malloc call to the specified type.
555 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
556 const Type *IntPtrTy, const Type *AllocTy,
557 Value *AllocSize, Value *ArraySize,
559 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
560 ArraySize, NULL, Name);
563 /// CreateMalloc - Generate the IR for a call to malloc:
564 /// 1. Compute the malloc call's argument as the specified type's size,
565 /// possibly multiplied by the array size if the array size is not
567 /// 2. Call malloc with that argument.
568 /// 3. Bitcast the result of the malloc call to the specified type.
569 /// Note: This function does not add the bitcast to the basic block, that is the
570 /// responsibility of the caller.
571 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
572 const Type *IntPtrTy, const Type *AllocTy,
573 Value *AllocSize, Value *ArraySize,
574 Function *MallocF, const Twine &Name) {
575 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
576 ArraySize, MallocF, Name);
579 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
580 BasicBlock *InsertAtEnd) {
581 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
582 "createFree needs either InsertBefore or InsertAtEnd");
583 assert(Source->getType()->isPointerTy() &&
584 "Can not free something of nonpointer type!");
586 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
587 Module* M = BB->getParent()->getParent();
589 const Type *VoidTy = Type::getVoidTy(M->getContext());
590 const Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
591 // prototype free as "void free(void*)"
592 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
593 CallInst* Result = NULL;
594 Value *PtrCast = Source;
596 if (Source->getType() != IntPtrTy)
597 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
598 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
600 if (Source->getType() != IntPtrTy)
601 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
602 Result = CallInst::Create(FreeFunc, PtrCast, "");
604 Result->setTailCall();
605 if (Function *F = dyn_cast<Function>(FreeFunc))
606 Result->setCallingConv(F->getCallingConv());
611 /// CreateFree - Generate the IR for a call to the builtin free function.
612 void CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
613 createFree(Source, InsertBefore, NULL);
616 /// CreateFree - Generate the IR for a call to the builtin free function.
617 /// Note: This function does not add the call to the basic block, that is the
618 /// responsibility of the caller.
619 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
620 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
621 assert(FreeCall && "CreateFree did not create a CallInst");
625 //===----------------------------------------------------------------------===//
626 // InvokeInst Implementation
627 //===----------------------------------------------------------------------===//
629 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
630 Value* const *Args, unsigned NumArgs) {
631 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
634 Op<-1>() = IfException;
635 const FunctionType *FTy =
636 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
637 FTy = FTy; // silence warning.
639 assert(((NumArgs == FTy->getNumParams()) ||
640 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
641 "Invoking a function with bad signature");
643 Use *OL = OperandList;
644 for (unsigned i = 0, e = NumArgs; i != e; i++) {
645 assert((i >= FTy->getNumParams() ||
646 FTy->getParamType(i) == Args[i]->getType()) &&
647 "Invoking a function with a bad signature!");
653 InvokeInst::InvokeInst(const InvokeInst &II)
654 : TerminatorInst(II.getType(), Instruction::Invoke,
655 OperandTraits<InvokeInst>::op_end(this)
656 - II.getNumOperands(),
657 II.getNumOperands()) {
658 setAttributes(II.getAttributes());
659 setCallingConv(II.getCallingConv());
660 Use *OL = OperandList, *InOL = II.OperandList;
661 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
663 SubclassOptionalData = II.SubclassOptionalData;
666 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
667 return getSuccessor(idx);
669 unsigned InvokeInst::getNumSuccessorsV() const {
670 return getNumSuccessors();
672 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
673 return setSuccessor(idx, B);
676 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
677 if (AttributeList.paramHasAttr(i, attr))
679 if (const Function *F = getCalledFunction())
680 return F->paramHasAttr(i, attr);
684 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
685 AttrListPtr PAL = getAttributes();
686 PAL = PAL.addAttr(i, attr);
690 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
691 AttrListPtr PAL = getAttributes();
692 PAL = PAL.removeAttr(i, attr);
697 //===----------------------------------------------------------------------===//
698 // ReturnInst Implementation
699 //===----------------------------------------------------------------------===//
701 ReturnInst::ReturnInst(const ReturnInst &RI)
702 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
703 OperandTraits<ReturnInst>::op_end(this) -
705 RI.getNumOperands()) {
706 if (RI.getNumOperands())
707 Op<0>() = RI.Op<0>();
708 SubclassOptionalData = RI.SubclassOptionalData;
711 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
712 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
713 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
718 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
719 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
720 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
725 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
726 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
727 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
730 unsigned ReturnInst::getNumSuccessorsV() const {
731 return getNumSuccessors();
734 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
735 /// emit the vtable for the class in this translation unit.
736 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
737 llvm_unreachable("ReturnInst has no successors!");
740 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
741 llvm_unreachable("ReturnInst has no successors!");
745 ReturnInst::~ReturnInst() {
748 //===----------------------------------------------------------------------===//
749 // UnwindInst Implementation
750 //===----------------------------------------------------------------------===//
752 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
753 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
754 0, 0, InsertBefore) {
756 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
757 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
762 unsigned UnwindInst::getNumSuccessorsV() const {
763 return getNumSuccessors();
766 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
767 llvm_unreachable("UnwindInst has no successors!");
770 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
771 llvm_unreachable("UnwindInst has no successors!");
775 //===----------------------------------------------------------------------===//
776 // UnreachableInst Implementation
777 //===----------------------------------------------------------------------===//
779 UnreachableInst::UnreachableInst(LLVMContext &Context,
780 Instruction *InsertBefore)
781 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
782 0, 0, InsertBefore) {
784 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
785 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
789 unsigned UnreachableInst::getNumSuccessorsV() const {
790 return getNumSuccessors();
793 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
794 llvm_unreachable("UnwindInst has no successors!");
797 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
798 llvm_unreachable("UnwindInst has no successors!");
802 //===----------------------------------------------------------------------===//
803 // BranchInst Implementation
804 //===----------------------------------------------------------------------===//
806 void BranchInst::AssertOK() {
808 assert(getCondition()->getType()->isIntegerTy(1) &&
809 "May only branch on boolean predicates!");
812 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
813 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
814 OperandTraits<BranchInst>::op_end(this) - 1,
816 assert(IfTrue != 0 && "Branch destination may not be null!");
819 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
820 Instruction *InsertBefore)
821 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
822 OperandTraits<BranchInst>::op_end(this) - 3,
832 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
833 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
834 OperandTraits<BranchInst>::op_end(this) - 1,
836 assert(IfTrue != 0 && "Branch destination may not be null!");
840 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
841 BasicBlock *InsertAtEnd)
842 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
843 OperandTraits<BranchInst>::op_end(this) - 3,
854 BranchInst::BranchInst(const BranchInst &BI) :
855 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
856 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
857 BI.getNumOperands()) {
858 Op<-1>() = BI.Op<-1>();
859 if (BI.getNumOperands() != 1) {
860 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
861 Op<-3>() = BI.Op<-3>();
862 Op<-2>() = BI.Op<-2>();
864 SubclassOptionalData = BI.SubclassOptionalData;
868 Use* Use::getPrefix() {
869 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
870 if (PotentialPrefix.getOpaqueValue())
873 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
876 BranchInst::~BranchInst() {
877 if (NumOperands == 1) {
878 if (Use *Prefix = OperandList->getPrefix()) {
881 // mark OperandList to have a special value for scrutiny
882 // by baseclass destructors and operator delete
883 OperandList = Prefix;
886 OperandList = op_begin();
892 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
893 return getSuccessor(idx);
895 unsigned BranchInst::getNumSuccessorsV() const {
896 return getNumSuccessors();
898 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
899 setSuccessor(idx, B);
903 //===----------------------------------------------------------------------===//
904 // AllocaInst Implementation
905 //===----------------------------------------------------------------------===//
907 static Value *getAISize(LLVMContext &Context, Value *Amt) {
909 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
911 assert(!isa<BasicBlock>(Amt) &&
912 "Passed basic block into allocation size parameter! Use other ctor");
913 assert(Amt->getType()->isIntegerTy(32) &&
914 "Allocation array size is not a 32-bit integer!");
919 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
920 const Twine &Name, Instruction *InsertBefore)
921 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
922 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
924 assert(!Ty->isVoidTy() && "Cannot allocate void!");
928 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
929 const Twine &Name, BasicBlock *InsertAtEnd)
930 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
931 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
933 assert(!Ty->isVoidTy() && "Cannot allocate void!");
937 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
938 Instruction *InsertBefore)
939 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
940 getAISize(Ty->getContext(), 0), InsertBefore) {
942 assert(!Ty->isVoidTy() && "Cannot allocate void!");
946 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
947 BasicBlock *InsertAtEnd)
948 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
949 getAISize(Ty->getContext(), 0), InsertAtEnd) {
951 assert(!Ty->isVoidTy() && "Cannot allocate void!");
955 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
956 const Twine &Name, Instruction *InsertBefore)
957 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
958 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
960 assert(!Ty->isVoidTy() && "Cannot allocate void!");
964 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
965 const Twine &Name, BasicBlock *InsertAtEnd)
966 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
967 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
969 assert(!Ty->isVoidTy() && "Cannot allocate void!");
973 // Out of line virtual method, so the vtable, etc has a home.
974 AllocaInst::~AllocaInst() {
977 void AllocaInst::setAlignment(unsigned Align) {
978 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
979 setInstructionSubclassData(Log2_32(Align) + 1);
980 assert(getAlignment() == Align && "Alignment representation error!");
983 bool AllocaInst::isArrayAllocation() const {
984 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
985 return CI->getZExtValue() != 1;
989 const Type *AllocaInst::getAllocatedType() const {
990 return getType()->getElementType();
993 /// isStaticAlloca - Return true if this alloca is in the entry block of the
994 /// function and is a constant size. If so, the code generator will fold it
995 /// into the prolog/epilog code, so it is basically free.
996 bool AllocaInst::isStaticAlloca() const {
997 // Must be constant size.
998 if (!isa<ConstantInt>(getArraySize())) return false;
1000 // Must be in the entry block.
1001 const BasicBlock *Parent = getParent();
1002 return Parent == &Parent->getParent()->front();
1005 //===----------------------------------------------------------------------===//
1006 // LoadInst Implementation
1007 //===----------------------------------------------------------------------===//
1009 void LoadInst::AssertOK() {
1010 assert(getOperand(0)->getType()->isPointerTy() &&
1011 "Ptr must have pointer type.");
1014 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1015 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1016 Load, Ptr, InsertBef) {
1023 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1024 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1025 Load, Ptr, InsertAE) {
1032 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1033 Instruction *InsertBef)
1034 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1035 Load, Ptr, InsertBef) {
1036 setVolatile(isVolatile);
1042 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1043 unsigned Align, Instruction *InsertBef)
1044 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1045 Load, Ptr, InsertBef) {
1046 setVolatile(isVolatile);
1047 setAlignment(Align);
1052 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1053 unsigned Align, BasicBlock *InsertAE)
1054 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1055 Load, Ptr, InsertAE) {
1056 setVolatile(isVolatile);
1057 setAlignment(Align);
1062 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1063 BasicBlock *InsertAE)
1064 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1065 Load, Ptr, InsertAE) {
1066 setVolatile(isVolatile);
1074 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1075 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1076 Load, Ptr, InsertBef) {
1080 if (Name && Name[0]) setName(Name);
1083 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1084 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1085 Load, Ptr, InsertAE) {
1089 if (Name && Name[0]) setName(Name);
1092 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1093 Instruction *InsertBef)
1094 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1095 Load, Ptr, InsertBef) {
1096 setVolatile(isVolatile);
1099 if (Name && Name[0]) setName(Name);
1102 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1103 BasicBlock *InsertAE)
1104 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1105 Load, Ptr, InsertAE) {
1106 setVolatile(isVolatile);
1109 if (Name && Name[0]) setName(Name);
1112 void LoadInst::setAlignment(unsigned Align) {
1113 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1114 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1115 ((Log2_32(Align)+1)<<1));
1118 //===----------------------------------------------------------------------===//
1119 // StoreInst Implementation
1120 //===----------------------------------------------------------------------===//
1122 void StoreInst::AssertOK() {
1123 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1124 assert(getOperand(1)->getType()->isPointerTy() &&
1125 "Ptr must have pointer type!");
1126 assert(getOperand(0)->getType() ==
1127 cast<PointerType>(getOperand(1)->getType())->getElementType()
1128 && "Ptr must be a pointer to Val type!");
1132 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1133 : Instruction(Type::getVoidTy(val->getContext()), Store,
1134 OperandTraits<StoreInst>::op_begin(this),
1135 OperandTraits<StoreInst>::operands(this),
1144 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1145 : Instruction(Type::getVoidTy(val->getContext()), Store,
1146 OperandTraits<StoreInst>::op_begin(this),
1147 OperandTraits<StoreInst>::operands(this),
1156 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1157 Instruction *InsertBefore)
1158 : Instruction(Type::getVoidTy(val->getContext()), Store,
1159 OperandTraits<StoreInst>::op_begin(this),
1160 OperandTraits<StoreInst>::operands(this),
1164 setVolatile(isVolatile);
1169 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1170 unsigned Align, Instruction *InsertBefore)
1171 : Instruction(Type::getVoidTy(val->getContext()), Store,
1172 OperandTraits<StoreInst>::op_begin(this),
1173 OperandTraits<StoreInst>::operands(this),
1177 setVolatile(isVolatile);
1178 setAlignment(Align);
1182 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1183 unsigned Align, BasicBlock *InsertAtEnd)
1184 : Instruction(Type::getVoidTy(val->getContext()), Store,
1185 OperandTraits<StoreInst>::op_begin(this),
1186 OperandTraits<StoreInst>::operands(this),
1190 setVolatile(isVolatile);
1191 setAlignment(Align);
1195 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1196 BasicBlock *InsertAtEnd)
1197 : Instruction(Type::getVoidTy(val->getContext()), Store,
1198 OperandTraits<StoreInst>::op_begin(this),
1199 OperandTraits<StoreInst>::operands(this),
1203 setVolatile(isVolatile);
1208 void StoreInst::setAlignment(unsigned Align) {
1209 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1210 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1211 ((Log2_32(Align)+1) << 1));
1214 //===----------------------------------------------------------------------===//
1215 // GetElementPtrInst Implementation
1216 //===----------------------------------------------------------------------===//
1218 static unsigned retrieveAddrSpace(const Value *Val) {
1219 return cast<PointerType>(Val->getType())->getAddressSpace();
1222 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1223 const Twine &Name) {
1224 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1225 Use *OL = OperandList;
1228 for (unsigned i = 0; i != NumIdx; ++i)
1234 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1235 assert(NumOperands == 2 && "NumOperands not initialized?");
1236 Use *OL = OperandList;
1243 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1244 : Instruction(GEPI.getType(), GetElementPtr,
1245 OperandTraits<GetElementPtrInst>::op_end(this)
1246 - GEPI.getNumOperands(),
1247 GEPI.getNumOperands()) {
1248 Use *OL = OperandList;
1249 Use *GEPIOL = GEPI.OperandList;
1250 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1252 SubclassOptionalData = GEPI.SubclassOptionalData;
1255 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1256 const Twine &Name, Instruction *InBe)
1257 : Instruction(PointerType::get(
1258 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1260 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1262 init(Ptr, Idx, Name);
1265 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1266 const Twine &Name, BasicBlock *IAE)
1267 : Instruction(PointerType::get(
1268 checkType(getIndexedType(Ptr->getType(),Idx)),
1269 retrieveAddrSpace(Ptr)),
1271 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1273 init(Ptr, Idx, Name);
1276 /// getIndexedType - Returns the type of the element that would be accessed with
1277 /// a gep instruction with the specified parameters.
1279 /// The Idxs pointer should point to a continuous piece of memory containing the
1280 /// indices, either as Value* or uint64_t.
1282 /// A null type is returned if the indices are invalid for the specified
1285 template <typename IndexTy>
1286 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1288 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1289 if (!PTy) return 0; // Type isn't a pointer type!
1290 const Type *Agg = PTy->getElementType();
1292 // Handle the special case of the empty set index set, which is always valid.
1296 // If there is at least one index, the top level type must be sized, otherwise
1297 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1298 // that contain opaque types) under the assumption that it will be resolved to
1299 // a sane type later.
1300 if (!Agg->isSized() && !Agg->isAbstract())
1303 unsigned CurIdx = 1;
1304 for (; CurIdx != NumIdx; ++CurIdx) {
1305 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1306 if (!CT || CT->isPointerTy()) return 0;
1307 IndexTy Index = Idxs[CurIdx];
1308 if (!CT->indexValid(Index)) return 0;
1309 Agg = CT->getTypeAtIndex(Index);
1311 // If the new type forwards to another type, then it is in the middle
1312 // of being refined to another type (and hence, may have dropped all
1313 // references to what it was using before). So, use the new forwarded
1315 if (const Type *Ty = Agg->getForwardedType())
1318 return CurIdx == NumIdx ? Agg : 0;
1321 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1324 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1327 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1328 uint64_t const *Idxs,
1330 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1333 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1334 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1335 if (!PTy) return 0; // Type isn't a pointer type!
1337 // Check the pointer index.
1338 if (!PTy->indexValid(Idx)) return 0;
1340 return PTy->getElementType();
1344 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1345 /// zeros. If so, the result pointer and the first operand have the same
1346 /// value, just potentially different types.
1347 bool GetElementPtrInst::hasAllZeroIndices() const {
1348 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1349 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1350 if (!CI->isZero()) return false;
1358 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1359 /// constant integers. If so, the result pointer and the first operand have
1360 /// a constant offset between them.
1361 bool GetElementPtrInst::hasAllConstantIndices() const {
1362 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1363 if (!isa<ConstantInt>(getOperand(i)))
1369 void GetElementPtrInst::setIsInBounds(bool B) {
1370 cast<GEPOperator>(this)->setIsInBounds(B);
1373 bool GetElementPtrInst::isInBounds() const {
1374 return cast<GEPOperator>(this)->isInBounds();
1377 //===----------------------------------------------------------------------===//
1378 // ExtractElementInst Implementation
1379 //===----------------------------------------------------------------------===//
1381 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1383 Instruction *InsertBef)
1384 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1386 OperandTraits<ExtractElementInst>::op_begin(this),
1388 assert(isValidOperands(Val, Index) &&
1389 "Invalid extractelement instruction operands!");
1395 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1397 BasicBlock *InsertAE)
1398 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1400 OperandTraits<ExtractElementInst>::op_begin(this),
1402 assert(isValidOperands(Val, Index) &&
1403 "Invalid extractelement instruction operands!");
1411 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1412 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1418 //===----------------------------------------------------------------------===//
1419 // InsertElementInst Implementation
1420 //===----------------------------------------------------------------------===//
1422 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1424 Instruction *InsertBef)
1425 : Instruction(Vec->getType(), InsertElement,
1426 OperandTraits<InsertElementInst>::op_begin(this),
1428 assert(isValidOperands(Vec, Elt, Index) &&
1429 "Invalid insertelement instruction operands!");
1436 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1438 BasicBlock *InsertAE)
1439 : Instruction(Vec->getType(), InsertElement,
1440 OperandTraits<InsertElementInst>::op_begin(this),
1442 assert(isValidOperands(Vec, Elt, Index) &&
1443 "Invalid insertelement instruction operands!");
1451 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1452 const Value *Index) {
1453 if (!Vec->getType()->isVectorTy())
1454 return false; // First operand of insertelement must be vector type.
1456 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1457 return false;// Second operand of insertelement must be vector element type.
1459 if (!Index->getType()->isIntegerTy(32))
1460 return false; // Third operand of insertelement must be i32.
1465 //===----------------------------------------------------------------------===//
1466 // ShuffleVectorInst Implementation
1467 //===----------------------------------------------------------------------===//
1469 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1471 Instruction *InsertBefore)
1472 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1473 cast<VectorType>(Mask->getType())->getNumElements()),
1475 OperandTraits<ShuffleVectorInst>::op_begin(this),
1476 OperandTraits<ShuffleVectorInst>::operands(this),
1478 assert(isValidOperands(V1, V2, Mask) &&
1479 "Invalid shuffle vector instruction operands!");
1486 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1488 BasicBlock *InsertAtEnd)
1489 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1490 cast<VectorType>(Mask->getType())->getNumElements()),
1492 OperandTraits<ShuffleVectorInst>::op_begin(this),
1493 OperandTraits<ShuffleVectorInst>::operands(this),
1495 assert(isValidOperands(V1, V2, Mask) &&
1496 "Invalid shuffle vector instruction operands!");
1504 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1505 const Value *Mask) {
1506 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1509 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1510 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1511 !MaskTy->getElementType()->isIntegerTy(32))
1516 /// getMaskValue - Return the index from the shuffle mask for the specified
1517 /// output result. This is either -1 if the element is undef or a number less
1518 /// than 2*numelements.
1519 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1520 const Constant *Mask = cast<Constant>(getOperand(2));
1521 if (isa<UndefValue>(Mask)) return -1;
1522 if (isa<ConstantAggregateZero>(Mask)) return 0;
1523 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1524 assert(i < MaskCV->getNumOperands() && "Index out of range");
1526 if (isa<UndefValue>(MaskCV->getOperand(i)))
1528 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1531 //===----------------------------------------------------------------------===//
1532 // InsertValueInst Class
1533 //===----------------------------------------------------------------------===//
1535 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1536 unsigned NumIdx, const Twine &Name) {
1537 assert(NumOperands == 2 && "NumOperands not initialized?");
1541 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1545 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1546 const Twine &Name) {
1547 assert(NumOperands == 2 && "NumOperands not initialized?");
1551 Indices.push_back(Idx);
1555 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1556 : Instruction(IVI.getType(), InsertValue,
1557 OperandTraits<InsertValueInst>::op_begin(this), 2),
1558 Indices(IVI.Indices) {
1559 Op<0>() = IVI.getOperand(0);
1560 Op<1>() = IVI.getOperand(1);
1561 SubclassOptionalData = IVI.SubclassOptionalData;
1564 InsertValueInst::InsertValueInst(Value *Agg,
1568 Instruction *InsertBefore)
1569 : Instruction(Agg->getType(), InsertValue,
1570 OperandTraits<InsertValueInst>::op_begin(this),
1572 init(Agg, Val, Idx, Name);
1575 InsertValueInst::InsertValueInst(Value *Agg,
1579 BasicBlock *InsertAtEnd)
1580 : Instruction(Agg->getType(), InsertValue,
1581 OperandTraits<InsertValueInst>::op_begin(this),
1583 init(Agg, Val, Idx, Name);
1586 //===----------------------------------------------------------------------===//
1587 // ExtractValueInst Class
1588 //===----------------------------------------------------------------------===//
1590 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1591 const Twine &Name) {
1592 assert(NumOperands == 1 && "NumOperands not initialized?");
1594 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1598 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1599 assert(NumOperands == 1 && "NumOperands not initialized?");
1601 Indices.push_back(Idx);
1605 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1606 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1607 Indices(EVI.Indices) {
1608 SubclassOptionalData = EVI.SubclassOptionalData;
1611 // getIndexedType - Returns the type of the element that would be extracted
1612 // with an extractvalue instruction with the specified parameters.
1614 // A null type is returned if the indices are invalid for the specified
1617 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1618 const unsigned *Idxs,
1620 unsigned CurIdx = 0;
1621 for (; CurIdx != NumIdx; ++CurIdx) {
1622 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1623 if (!CT || CT->isPointerTy() || CT->isVectorTy()) return 0;
1624 unsigned Index = Idxs[CurIdx];
1625 if (!CT->indexValid(Index)) return 0;
1626 Agg = CT->getTypeAtIndex(Index);
1628 // If the new type forwards to another type, then it is in the middle
1629 // of being refined to another type (and hence, may have dropped all
1630 // references to what it was using before). So, use the new forwarded
1632 if (const Type *Ty = Agg->getForwardedType())
1635 return CurIdx == NumIdx ? Agg : 0;
1638 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1640 return getIndexedType(Agg, &Idx, 1);
1643 //===----------------------------------------------------------------------===//
1644 // BinaryOperator Class
1645 //===----------------------------------------------------------------------===//
1647 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1648 /// type is floating-point, to help provide compatibility with an older API.
1650 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1652 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1653 if (Ty->isFPOrFPVectorTy()) {
1654 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1655 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1656 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1661 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1662 const Type *Ty, const Twine &Name,
1663 Instruction *InsertBefore)
1664 : Instruction(Ty, AdjustIType(iType, Ty),
1665 OperandTraits<BinaryOperator>::op_begin(this),
1666 OperandTraits<BinaryOperator>::operands(this),
1670 init(AdjustIType(iType, Ty));
1674 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1675 const Type *Ty, const Twine &Name,
1676 BasicBlock *InsertAtEnd)
1677 : Instruction(Ty, AdjustIType(iType, Ty),
1678 OperandTraits<BinaryOperator>::op_begin(this),
1679 OperandTraits<BinaryOperator>::operands(this),
1683 init(AdjustIType(iType, Ty));
1688 void BinaryOperator::init(BinaryOps iType) {
1689 Value *LHS = getOperand(0), *RHS = getOperand(1);
1690 LHS = LHS; RHS = RHS; // Silence warnings.
1691 assert(LHS->getType() == RHS->getType() &&
1692 "Binary operator operand types must match!");
1697 assert(getType() == LHS->getType() &&
1698 "Arithmetic operation should return same type as operands!");
1699 assert(getType()->isIntOrIntVectorTy() &&
1700 "Tried to create an integer operation on a non-integer type!");
1702 case FAdd: case FSub:
1704 assert(getType() == LHS->getType() &&
1705 "Arithmetic operation should return same type as operands!");
1706 assert(getType()->isFPOrFPVectorTy() &&
1707 "Tried to create a floating-point operation on a "
1708 "non-floating-point type!");
1712 assert(getType() == LHS->getType() &&
1713 "Arithmetic operation should return same type as operands!");
1714 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1715 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1716 "Incorrect operand type (not integer) for S/UDIV");
1719 assert(getType() == LHS->getType() &&
1720 "Arithmetic operation should return same type as operands!");
1721 assert(getType()->isFPOrFPVectorTy() &&
1722 "Incorrect operand type (not floating point) for FDIV");
1726 assert(getType() == LHS->getType() &&
1727 "Arithmetic operation should return same type as operands!");
1728 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1729 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1730 "Incorrect operand type (not integer) for S/UREM");
1733 assert(getType() == LHS->getType() &&
1734 "Arithmetic operation should return same type as operands!");
1735 assert(getType()->isFPOrFPVectorTy() &&
1736 "Incorrect operand type (not floating point) for FREM");
1741 assert(getType() == LHS->getType() &&
1742 "Shift operation should return same type as operands!");
1743 assert((getType()->isIntegerTy() ||
1744 (getType()->isVectorTy() &&
1745 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1746 "Tried to create a shift operation on a non-integral type!");
1750 assert(getType() == LHS->getType() &&
1751 "Logical operation should return same type as operands!");
1752 assert((getType()->isIntegerTy() ||
1753 (getType()->isVectorTy() &&
1754 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1755 "Tried to create a logical operation on a non-integral type!");
1763 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1765 Instruction *InsertBefore) {
1766 assert(S1->getType() == S2->getType() &&
1767 "Cannot create binary operator with two operands of differing type!");
1768 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1771 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1773 BasicBlock *InsertAtEnd) {
1774 BinaryOperator *Res = Create(Op, S1, S2, Name);
1775 InsertAtEnd->getInstList().push_back(Res);
1779 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1780 Instruction *InsertBefore) {
1781 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1782 return new BinaryOperator(Instruction::Sub,
1784 Op->getType(), Name, InsertBefore);
1787 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1788 BasicBlock *InsertAtEnd) {
1789 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1790 return new BinaryOperator(Instruction::Sub,
1792 Op->getType(), Name, InsertAtEnd);
1795 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1796 Instruction *InsertBefore) {
1797 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1798 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1801 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1802 BasicBlock *InsertAtEnd) {
1803 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1804 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1807 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1808 Instruction *InsertBefore) {
1809 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1810 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1813 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1814 BasicBlock *InsertAtEnd) {
1815 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1816 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1819 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1820 Instruction *InsertBefore) {
1821 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1822 return new BinaryOperator(Instruction::FSub,
1824 Op->getType(), Name, InsertBefore);
1827 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1828 BasicBlock *InsertAtEnd) {
1829 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1830 return new BinaryOperator(Instruction::FSub,
1832 Op->getType(), Name, InsertAtEnd);
1835 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1836 Instruction *InsertBefore) {
1838 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1839 C = Constant::getAllOnesValue(PTy->getElementType());
1840 C = ConstantVector::get(
1841 std::vector<Constant*>(PTy->getNumElements(), C));
1843 C = Constant::getAllOnesValue(Op->getType());
1846 return new BinaryOperator(Instruction::Xor, Op, C,
1847 Op->getType(), Name, InsertBefore);
1850 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1851 BasicBlock *InsertAtEnd) {
1853 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1854 // Create a vector of all ones values.
1855 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1856 AllOnes = ConstantVector::get(
1857 std::vector<Constant*>(PTy->getNumElements(), Elt));
1859 AllOnes = Constant::getAllOnesValue(Op->getType());
1862 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1863 Op->getType(), Name, InsertAtEnd);
1867 // isConstantAllOnes - Helper function for several functions below
1868 static inline bool isConstantAllOnes(const Value *V) {
1869 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1870 return CI->isAllOnesValue();
1871 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1872 return CV->isAllOnesValue();
1876 bool BinaryOperator::isNeg(const Value *V) {
1877 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1878 if (Bop->getOpcode() == Instruction::Sub)
1879 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1880 return C->isNegativeZeroValue();
1884 bool BinaryOperator::isFNeg(const Value *V) {
1885 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1886 if (Bop->getOpcode() == Instruction::FSub)
1887 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1888 return C->isNegativeZeroValue();
1892 bool BinaryOperator::isNot(const Value *V) {
1893 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1894 return (Bop->getOpcode() == Instruction::Xor &&
1895 (isConstantAllOnes(Bop->getOperand(1)) ||
1896 isConstantAllOnes(Bop->getOperand(0))));
1900 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1901 return cast<BinaryOperator>(BinOp)->getOperand(1);
1904 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1905 return getNegArgument(const_cast<Value*>(BinOp));
1908 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1909 return cast<BinaryOperator>(BinOp)->getOperand(1);
1912 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1913 return getFNegArgument(const_cast<Value*>(BinOp));
1916 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1917 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1918 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1919 Value *Op0 = BO->getOperand(0);
1920 Value *Op1 = BO->getOperand(1);
1921 if (isConstantAllOnes(Op0)) return Op1;
1923 assert(isConstantAllOnes(Op1));
1927 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1928 return getNotArgument(const_cast<Value*>(BinOp));
1932 // swapOperands - Exchange the two operands to this instruction. This
1933 // instruction is safe to use on any binary instruction and does not
1934 // modify the semantics of the instruction. If the instruction is
1935 // order dependent (SetLT f.e.) the opcode is changed.
1937 bool BinaryOperator::swapOperands() {
1938 if (!isCommutative())
1939 return true; // Can't commute operands
1940 Op<0>().swap(Op<1>());
1944 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1945 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1948 void BinaryOperator::setHasNoSignedWrap(bool b) {
1949 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1952 void BinaryOperator::setIsExact(bool b) {
1953 cast<SDivOperator>(this)->setIsExact(b);
1956 bool BinaryOperator::hasNoUnsignedWrap() const {
1957 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1960 bool BinaryOperator::hasNoSignedWrap() const {
1961 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1964 bool BinaryOperator::isExact() const {
1965 return cast<SDivOperator>(this)->isExact();
1968 //===----------------------------------------------------------------------===//
1970 //===----------------------------------------------------------------------===//
1972 // Just determine if this cast only deals with integral->integral conversion.
1973 bool CastInst::isIntegerCast() const {
1974 switch (getOpcode()) {
1975 default: return false;
1976 case Instruction::ZExt:
1977 case Instruction::SExt:
1978 case Instruction::Trunc:
1980 case Instruction::BitCast:
1981 return getOperand(0)->getType()->isIntegerTy() &&
1982 getType()->isIntegerTy();
1986 bool CastInst::isLosslessCast() const {
1987 // Only BitCast can be lossless, exit fast if we're not BitCast
1988 if (getOpcode() != Instruction::BitCast)
1991 // Identity cast is always lossless
1992 const Type* SrcTy = getOperand(0)->getType();
1993 const Type* DstTy = getType();
1997 // Pointer to pointer is always lossless.
1998 if (SrcTy->isPointerTy())
1999 return DstTy->isPointerTy();
2000 return false; // Other types have no identity values
2003 /// This function determines if the CastInst does not require any bits to be
2004 /// changed in order to effect the cast. Essentially, it identifies cases where
2005 /// no code gen is necessary for the cast, hence the name no-op cast. For
2006 /// example, the following are all no-op casts:
2007 /// # bitcast i32* %x to i8*
2008 /// # bitcast <2 x i32> %x to <4 x i16>
2009 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2010 /// @brief Determine if a cast is a no-op.
2011 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
2012 switch (getOpcode()) {
2014 assert(!"Invalid CastOp");
2015 case Instruction::Trunc:
2016 case Instruction::ZExt:
2017 case Instruction::SExt:
2018 case Instruction::FPTrunc:
2019 case Instruction::FPExt:
2020 case Instruction::UIToFP:
2021 case Instruction::SIToFP:
2022 case Instruction::FPToUI:
2023 case Instruction::FPToSI:
2024 return false; // These always modify bits
2025 case Instruction::BitCast:
2026 return true; // BitCast never modifies bits.
2027 case Instruction::PtrToInt:
2028 return IntPtrTy->getScalarSizeInBits() ==
2029 getType()->getScalarSizeInBits();
2030 case Instruction::IntToPtr:
2031 return IntPtrTy->getScalarSizeInBits() ==
2032 getOperand(0)->getType()->getScalarSizeInBits();
2036 /// This function determines if a pair of casts can be eliminated and what
2037 /// opcode should be used in the elimination. This assumes that there are two
2038 /// instructions like this:
2039 /// * %F = firstOpcode SrcTy %x to MidTy
2040 /// * %S = secondOpcode MidTy %F to DstTy
2041 /// The function returns a resultOpcode so these two casts can be replaced with:
2042 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2043 /// If no such cast is permited, the function returns 0.
2044 unsigned CastInst::isEliminableCastPair(
2045 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2046 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
2048 // Define the 144 possibilities for these two cast instructions. The values
2049 // in this matrix determine what to do in a given situation and select the
2050 // case in the switch below. The rows correspond to firstOp, the columns
2051 // correspond to secondOp. In looking at the table below, keep in mind
2052 // the following cast properties:
2054 // Size Compare Source Destination
2055 // Operator Src ? Size Type Sign Type Sign
2056 // -------- ------------ ------------------- ---------------------
2057 // TRUNC > Integer Any Integral Any
2058 // ZEXT < Integral Unsigned Integer Any
2059 // SEXT < Integral Signed Integer Any
2060 // FPTOUI n/a FloatPt n/a Integral Unsigned
2061 // FPTOSI n/a FloatPt n/a Integral Signed
2062 // UITOFP n/a Integral Unsigned FloatPt n/a
2063 // SITOFP n/a Integral Signed FloatPt n/a
2064 // FPTRUNC > FloatPt n/a FloatPt n/a
2065 // FPEXT < FloatPt n/a FloatPt n/a
2066 // PTRTOINT n/a Pointer n/a Integral Unsigned
2067 // INTTOPTR n/a Integral Unsigned Pointer n/a
2068 // BITCONVERT = FirstClass n/a FirstClass n/a
2070 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2071 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2072 // into "fptoui double to i64", but this loses information about the range
2073 // of the produced value (we no longer know the top-part is all zeros).
2074 // Further this conversion is often much more expensive for typical hardware,
2075 // and causes issues when building libgcc. We disallow fptosi+sext for the
2077 const unsigned numCastOps =
2078 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2079 static const uint8_t CastResults[numCastOps][numCastOps] = {
2080 // T F F U S F F P I B -+
2081 // R Z S P P I I T P 2 N T |
2082 // U E E 2 2 2 2 R E I T C +- secondOp
2083 // N X X U S F F N X N 2 V |
2084 // C T T I I P P C T T P T -+
2085 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2086 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2087 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2088 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2089 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2090 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2091 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2092 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2093 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2094 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2095 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2096 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2099 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2100 [secondOp-Instruction::CastOpsBegin];
2103 // categorically disallowed
2106 // allowed, use first cast's opcode
2109 // allowed, use second cast's opcode
2112 // no-op cast in second op implies firstOp as long as the DestTy
2113 // is integer and we are not converting between a vector and a
2115 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2119 // no-op cast in second op implies firstOp as long as the DestTy
2120 // is floating point.
2121 if (DstTy->isFloatingPointTy())
2125 // no-op cast in first op implies secondOp as long as the SrcTy
2127 if (SrcTy->isIntegerTy())
2131 // no-op cast in first op implies secondOp as long as the SrcTy
2132 // is a floating point.
2133 if (SrcTy->isFloatingPointTy())
2137 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2140 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2141 unsigned MidSize = MidTy->getScalarSizeInBits();
2142 if (MidSize >= PtrSize)
2143 return Instruction::BitCast;
2147 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2148 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2149 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2150 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2151 unsigned DstSize = DstTy->getScalarSizeInBits();
2152 if (SrcSize == DstSize)
2153 return Instruction::BitCast;
2154 else if (SrcSize < DstSize)
2158 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2159 return Instruction::ZExt;
2161 // fpext followed by ftrunc is allowed if the bit size returned to is
2162 // the same as the original, in which case its just a bitcast
2164 return Instruction::BitCast;
2165 return 0; // If the types are not the same we can't eliminate it.
2167 // bitcast followed by ptrtoint is allowed as long as the bitcast
2168 // is a pointer to pointer cast.
2169 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2173 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2174 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2178 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2181 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2182 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2183 unsigned DstSize = DstTy->getScalarSizeInBits();
2184 if (SrcSize <= PtrSize && SrcSize == DstSize)
2185 return Instruction::BitCast;
2189 // cast combination can't happen (error in input). This is for all cases
2190 // where the MidTy is not the same for the two cast instructions.
2191 assert(!"Invalid Cast Combination");
2194 assert(!"Error in CastResults table!!!");
2200 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2201 const Twine &Name, Instruction *InsertBefore) {
2202 // Construct and return the appropriate CastInst subclass
2204 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2205 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2206 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2207 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2208 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2209 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2210 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2211 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2212 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2213 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2214 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2215 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2217 assert(!"Invalid opcode provided");
2222 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2223 const Twine &Name, BasicBlock *InsertAtEnd) {
2224 // Construct and return the appropriate CastInst subclass
2226 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2227 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2228 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2229 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2230 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2231 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2232 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2233 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2234 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2235 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2236 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2237 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2239 assert(!"Invalid opcode provided");
2244 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2246 Instruction *InsertBefore) {
2247 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2248 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2249 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2252 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2254 BasicBlock *InsertAtEnd) {
2255 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2256 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2257 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2260 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2262 Instruction *InsertBefore) {
2263 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2264 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2265 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2268 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2270 BasicBlock *InsertAtEnd) {
2271 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2272 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2273 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2276 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2278 Instruction *InsertBefore) {
2279 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2280 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2281 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2284 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2286 BasicBlock *InsertAtEnd) {
2287 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2288 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2289 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2292 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2294 BasicBlock *InsertAtEnd) {
2295 assert(S->getType()->isPointerTy() && "Invalid cast");
2296 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2299 if (Ty->isIntegerTy())
2300 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2301 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2304 /// @brief Create a BitCast or a PtrToInt cast instruction
2305 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2307 Instruction *InsertBefore) {
2308 assert(S->getType()->isPointerTy() && "Invalid cast");
2309 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2312 if (Ty->isIntegerTy())
2313 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2314 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2317 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2318 bool isSigned, const Twine &Name,
2319 Instruction *InsertBefore) {
2320 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2321 "Invalid integer cast");
2322 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2323 unsigned DstBits = Ty->getScalarSizeInBits();
2324 Instruction::CastOps opcode =
2325 (SrcBits == DstBits ? Instruction::BitCast :
2326 (SrcBits > DstBits ? Instruction::Trunc :
2327 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2328 return Create(opcode, C, Ty, Name, InsertBefore);
2331 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2332 bool isSigned, const Twine &Name,
2333 BasicBlock *InsertAtEnd) {
2334 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2336 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2337 unsigned DstBits = Ty->getScalarSizeInBits();
2338 Instruction::CastOps opcode =
2339 (SrcBits == DstBits ? Instruction::BitCast :
2340 (SrcBits > DstBits ? Instruction::Trunc :
2341 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2342 return Create(opcode, C, Ty, Name, InsertAtEnd);
2345 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2347 Instruction *InsertBefore) {
2348 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2350 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2351 unsigned DstBits = Ty->getScalarSizeInBits();
2352 Instruction::CastOps opcode =
2353 (SrcBits == DstBits ? Instruction::BitCast :
2354 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2355 return Create(opcode, C, Ty, Name, InsertBefore);
2358 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2360 BasicBlock *InsertAtEnd) {
2361 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2363 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2364 unsigned DstBits = Ty->getScalarSizeInBits();
2365 Instruction::CastOps opcode =
2366 (SrcBits == DstBits ? Instruction::BitCast :
2367 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2368 return Create(opcode, C, Ty, Name, InsertAtEnd);
2371 // Check whether it is valid to call getCastOpcode for these types.
2372 // This routine must be kept in sync with getCastOpcode.
2373 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2374 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2377 if (SrcTy == DestTy)
2380 // Get the bit sizes, we'll need these
2381 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2382 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2384 // Run through the possibilities ...
2385 if (DestTy->isIntegerTy()) { // Casting to integral
2386 if (SrcTy->isIntegerTy()) { // Casting from integral
2388 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2390 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2391 // Casting from vector
2392 return DestBits == PTy->getBitWidth();
2393 } else { // Casting from something else
2394 return SrcTy->isPointerTy();
2396 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2397 if (SrcTy->isIntegerTy()) { // Casting from integral
2399 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2401 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2402 // Casting from vector
2403 return DestBits == PTy->getBitWidth();
2404 } else { // Casting from something else
2407 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2408 // Casting to vector
2409 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2410 // Casting from vector
2411 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2412 } else { // Casting from something else
2413 return DestPTy->getBitWidth() == SrcBits;
2415 } else if (DestTy->isPointerTy()) { // Casting to pointer
2416 if (SrcTy->isPointerTy()) { // Casting from pointer
2418 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2420 } else { // Casting from something else
2423 } else { // Casting to something else
2428 // Provide a way to get a "cast" where the cast opcode is inferred from the
2429 // types and size of the operand. This, basically, is a parallel of the
2430 // logic in the castIsValid function below. This axiom should hold:
2431 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2432 // should not assert in castIsValid. In other words, this produces a "correct"
2433 // casting opcode for the arguments passed to it.
2434 // This routine must be kept in sync with isCastable.
2435 Instruction::CastOps
2436 CastInst::getCastOpcode(
2437 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2438 // Get the bit sizes, we'll need these
2439 const Type *SrcTy = Src->getType();
2440 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2441 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2443 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2444 "Only first class types are castable!");
2446 // Run through the possibilities ...
2447 if (DestTy->isIntegerTy()) { // Casting to integral
2448 if (SrcTy->isIntegerTy()) { // Casting from integral
2449 if (DestBits < SrcBits)
2450 return Trunc; // int -> smaller int
2451 else if (DestBits > SrcBits) { // its an extension
2453 return SExt; // signed -> SEXT
2455 return ZExt; // unsigned -> ZEXT
2457 return BitCast; // Same size, No-op cast
2459 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2461 return FPToSI; // FP -> sint
2463 return FPToUI; // FP -> uint
2464 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2465 assert(DestBits == PTy->getBitWidth() &&
2466 "Casting vector to integer of different width");
2468 return BitCast; // Same size, no-op cast
2470 assert(SrcTy->isPointerTy() &&
2471 "Casting from a value that is not first-class type");
2472 return PtrToInt; // ptr -> int
2474 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2475 if (SrcTy->isIntegerTy()) { // Casting from integral
2477 return SIToFP; // sint -> FP
2479 return UIToFP; // uint -> FP
2480 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2481 if (DestBits < SrcBits) {
2482 return FPTrunc; // FP -> smaller FP
2483 } else if (DestBits > SrcBits) {
2484 return FPExt; // FP -> larger FP
2486 return BitCast; // same size, no-op cast
2488 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2489 assert(DestBits == PTy->getBitWidth() &&
2490 "Casting vector to floating point of different width");
2492 return BitCast; // same size, no-op cast
2494 llvm_unreachable("Casting pointer or non-first class to float");
2496 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2497 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2498 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2499 "Casting vector to vector of different widths");
2501 return BitCast; // vector -> vector
2502 } else if (DestPTy->getBitWidth() == SrcBits) {
2503 return BitCast; // float/int -> vector
2505 assert(!"Illegal cast to vector (wrong type or size)");
2507 } else if (DestTy->isPointerTy()) {
2508 if (SrcTy->isPointerTy()) {
2509 return BitCast; // ptr -> ptr
2510 } else if (SrcTy->isIntegerTy()) {
2511 return IntToPtr; // int -> ptr
2513 assert(!"Casting pointer to other than pointer or int");
2516 assert(!"Casting to type that is not first-class");
2519 // If we fall through to here we probably hit an assertion cast above
2520 // and assertions are not turned on. Anything we return is an error, so
2521 // BitCast is as good a choice as any.
2525 //===----------------------------------------------------------------------===//
2526 // CastInst SubClass Constructors
2527 //===----------------------------------------------------------------------===//
2529 /// Check that the construction parameters for a CastInst are correct. This
2530 /// could be broken out into the separate constructors but it is useful to have
2531 /// it in one place and to eliminate the redundant code for getting the sizes
2532 /// of the types involved.
2534 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2536 // Check for type sanity on the arguments
2537 const Type *SrcTy = S->getType();
2538 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2539 SrcTy->isAggregateType() || DstTy->isAggregateType())
2542 // Get the size of the types in bits, we'll need this later
2543 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2544 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2546 // Switch on the opcode provided
2548 default: return false; // This is an input error
2549 case Instruction::Trunc:
2550 return SrcTy->isIntOrIntVectorTy() &&
2551 DstTy->isIntOrIntVectorTy()&& SrcBitSize > DstBitSize;
2552 case Instruction::ZExt:
2553 return SrcTy->isIntOrIntVectorTy() &&
2554 DstTy->isIntOrIntVectorTy()&& SrcBitSize < DstBitSize;
2555 case Instruction::SExt:
2556 return SrcTy->isIntOrIntVectorTy() &&
2557 DstTy->isIntOrIntVectorTy()&& SrcBitSize < DstBitSize;
2558 case Instruction::FPTrunc:
2559 return SrcTy->isFPOrFPVectorTy() &&
2560 DstTy->isFPOrFPVectorTy() &&
2561 SrcBitSize > DstBitSize;
2562 case Instruction::FPExt:
2563 return SrcTy->isFPOrFPVectorTy() &&
2564 DstTy->isFPOrFPVectorTy() &&
2565 SrcBitSize < DstBitSize;
2566 case Instruction::UIToFP:
2567 case Instruction::SIToFP:
2568 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2569 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2570 return SVTy->getElementType()->isIntOrIntVectorTy() &&
2571 DVTy->getElementType()->isFPOrFPVectorTy() &&
2572 SVTy->getNumElements() == DVTy->getNumElements();
2575 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy();
2576 case Instruction::FPToUI:
2577 case Instruction::FPToSI:
2578 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2579 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2580 return SVTy->getElementType()->isFPOrFPVectorTy() &&
2581 DVTy->getElementType()->isIntOrIntVectorTy() &&
2582 SVTy->getNumElements() == DVTy->getNumElements();
2585 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy();
2586 case Instruction::PtrToInt:
2587 return SrcTy->isPointerTy() && DstTy->isIntegerTy();
2588 case Instruction::IntToPtr:
2589 return SrcTy->isIntegerTy() && DstTy->isPointerTy();
2590 case Instruction::BitCast:
2591 // BitCast implies a no-op cast of type only. No bits change.
2592 // However, you can't cast pointers to anything but pointers.
2593 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2596 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2597 // these cases, the cast is okay if the source and destination bit widths
2599 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2603 TruncInst::TruncInst(
2604 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2605 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2606 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2609 TruncInst::TruncInst(
2610 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2611 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2612 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2616 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2617 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2618 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2622 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2623 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2624 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2627 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2628 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2629 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2633 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2634 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2635 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2638 FPTruncInst::FPTruncInst(
2639 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2640 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2641 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2644 FPTruncInst::FPTruncInst(
2645 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2646 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2647 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2650 FPExtInst::FPExtInst(
2651 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2652 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2653 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2656 FPExtInst::FPExtInst(
2657 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2658 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2659 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2662 UIToFPInst::UIToFPInst(
2663 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2664 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2665 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2668 UIToFPInst::UIToFPInst(
2669 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2670 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2671 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2674 SIToFPInst::SIToFPInst(
2675 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2676 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2677 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2680 SIToFPInst::SIToFPInst(
2681 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2682 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2683 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2686 FPToUIInst::FPToUIInst(
2687 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2688 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2689 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2692 FPToUIInst::FPToUIInst(
2693 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2694 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2695 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2698 FPToSIInst::FPToSIInst(
2699 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2700 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2701 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2704 FPToSIInst::FPToSIInst(
2705 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2706 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2707 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2710 PtrToIntInst::PtrToIntInst(
2711 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2712 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2713 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2716 PtrToIntInst::PtrToIntInst(
2717 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2718 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2719 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2722 IntToPtrInst::IntToPtrInst(
2723 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2724 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2725 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2728 IntToPtrInst::IntToPtrInst(
2729 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2730 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2731 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2734 BitCastInst::BitCastInst(
2735 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2736 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2737 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2740 BitCastInst::BitCastInst(
2741 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2742 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2743 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2746 //===----------------------------------------------------------------------===//
2748 //===----------------------------------------------------------------------===//
2750 void CmpInst::Anchor() const {}
2752 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2753 Value *LHS, Value *RHS, const Twine &Name,
2754 Instruction *InsertBefore)
2755 : Instruction(ty, op,
2756 OperandTraits<CmpInst>::op_begin(this),
2757 OperandTraits<CmpInst>::operands(this),
2761 setPredicate((Predicate)predicate);
2765 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2766 Value *LHS, Value *RHS, const Twine &Name,
2767 BasicBlock *InsertAtEnd)
2768 : Instruction(ty, op,
2769 OperandTraits<CmpInst>::op_begin(this),
2770 OperandTraits<CmpInst>::operands(this),
2774 setPredicate((Predicate)predicate);
2779 CmpInst::Create(OtherOps Op, unsigned short predicate,
2780 Value *S1, Value *S2,
2781 const Twine &Name, Instruction *InsertBefore) {
2782 if (Op == Instruction::ICmp) {
2784 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2787 return new ICmpInst(CmpInst::Predicate(predicate),
2792 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2795 return new FCmpInst(CmpInst::Predicate(predicate),
2800 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2801 const Twine &Name, BasicBlock *InsertAtEnd) {
2802 if (Op == Instruction::ICmp) {
2803 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2806 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2810 void CmpInst::swapOperands() {
2811 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2814 cast<FCmpInst>(this)->swapOperands();
2817 bool CmpInst::isCommutative() {
2818 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2819 return IC->isCommutative();
2820 return cast<FCmpInst>(this)->isCommutative();
2823 bool CmpInst::isEquality() {
2824 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2825 return IC->isEquality();
2826 return cast<FCmpInst>(this)->isEquality();
2830 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2832 default: assert(!"Unknown cmp predicate!");
2833 case ICMP_EQ: return ICMP_NE;
2834 case ICMP_NE: return ICMP_EQ;
2835 case ICMP_UGT: return ICMP_ULE;
2836 case ICMP_ULT: return ICMP_UGE;
2837 case ICMP_UGE: return ICMP_ULT;
2838 case ICMP_ULE: return ICMP_UGT;
2839 case ICMP_SGT: return ICMP_SLE;
2840 case ICMP_SLT: return ICMP_SGE;
2841 case ICMP_SGE: return ICMP_SLT;
2842 case ICMP_SLE: return ICMP_SGT;
2844 case FCMP_OEQ: return FCMP_UNE;
2845 case FCMP_ONE: return FCMP_UEQ;
2846 case FCMP_OGT: return FCMP_ULE;
2847 case FCMP_OLT: return FCMP_UGE;
2848 case FCMP_OGE: return FCMP_ULT;
2849 case FCMP_OLE: return FCMP_UGT;
2850 case FCMP_UEQ: return FCMP_ONE;
2851 case FCMP_UNE: return FCMP_OEQ;
2852 case FCMP_UGT: return FCMP_OLE;
2853 case FCMP_ULT: return FCMP_OGE;
2854 case FCMP_UGE: return FCMP_OLT;
2855 case FCMP_ULE: return FCMP_OGT;
2856 case FCMP_ORD: return FCMP_UNO;
2857 case FCMP_UNO: return FCMP_ORD;
2858 case FCMP_TRUE: return FCMP_FALSE;
2859 case FCMP_FALSE: return FCMP_TRUE;
2863 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2865 default: assert(! "Unknown icmp predicate!");
2866 case ICMP_EQ: case ICMP_NE:
2867 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2869 case ICMP_UGT: return ICMP_SGT;
2870 case ICMP_ULT: return ICMP_SLT;
2871 case ICMP_UGE: return ICMP_SGE;
2872 case ICMP_ULE: return ICMP_SLE;
2876 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2878 default: assert(! "Unknown icmp predicate!");
2879 case ICMP_EQ: case ICMP_NE:
2880 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2882 case ICMP_SGT: return ICMP_UGT;
2883 case ICMP_SLT: return ICMP_ULT;
2884 case ICMP_SGE: return ICMP_UGE;
2885 case ICMP_SLE: return ICMP_ULE;
2889 /// Initialize a set of values that all satisfy the condition with C.
2892 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2895 uint32_t BitWidth = C.getBitWidth();
2897 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2898 case ICmpInst::ICMP_EQ: Upper++; break;
2899 case ICmpInst::ICMP_NE: Lower++; break;
2900 case ICmpInst::ICMP_ULT:
2901 Lower = APInt::getMinValue(BitWidth);
2902 // Check for an empty-set condition.
2904 return ConstantRange(BitWidth, /*isFullSet=*/false);
2906 case ICmpInst::ICMP_SLT:
2907 Lower = APInt::getSignedMinValue(BitWidth);
2908 // Check for an empty-set condition.
2910 return ConstantRange(BitWidth, /*isFullSet=*/false);
2912 case ICmpInst::ICMP_UGT:
2913 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2914 // Check for an empty-set condition.
2916 return ConstantRange(BitWidth, /*isFullSet=*/false);
2918 case ICmpInst::ICMP_SGT:
2919 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2920 // Check for an empty-set condition.
2922 return ConstantRange(BitWidth, /*isFullSet=*/false);
2924 case ICmpInst::ICMP_ULE:
2925 Lower = APInt::getMinValue(BitWidth); Upper++;
2926 // Check for a full-set condition.
2928 return ConstantRange(BitWidth, /*isFullSet=*/true);
2930 case ICmpInst::ICMP_SLE:
2931 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2932 // Check for a full-set condition.
2934 return ConstantRange(BitWidth, /*isFullSet=*/true);
2936 case ICmpInst::ICMP_UGE:
2937 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2938 // Check for a full-set condition.
2940 return ConstantRange(BitWidth, /*isFullSet=*/true);
2942 case ICmpInst::ICMP_SGE:
2943 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2944 // Check for a full-set condition.
2946 return ConstantRange(BitWidth, /*isFullSet=*/true);
2949 return ConstantRange(Lower, Upper);
2952 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2954 default: assert(!"Unknown cmp predicate!");
2955 case ICMP_EQ: case ICMP_NE:
2957 case ICMP_SGT: return ICMP_SLT;
2958 case ICMP_SLT: return ICMP_SGT;
2959 case ICMP_SGE: return ICMP_SLE;
2960 case ICMP_SLE: return ICMP_SGE;
2961 case ICMP_UGT: return ICMP_ULT;
2962 case ICMP_ULT: return ICMP_UGT;
2963 case ICMP_UGE: return ICMP_ULE;
2964 case ICMP_ULE: return ICMP_UGE;
2966 case FCMP_FALSE: case FCMP_TRUE:
2967 case FCMP_OEQ: case FCMP_ONE:
2968 case FCMP_UEQ: case FCMP_UNE:
2969 case FCMP_ORD: case FCMP_UNO:
2971 case FCMP_OGT: return FCMP_OLT;
2972 case FCMP_OLT: return FCMP_OGT;
2973 case FCMP_OGE: return FCMP_OLE;
2974 case FCMP_OLE: return FCMP_OGE;
2975 case FCMP_UGT: return FCMP_ULT;
2976 case FCMP_ULT: return FCMP_UGT;
2977 case FCMP_UGE: return FCMP_ULE;
2978 case FCMP_ULE: return FCMP_UGE;
2982 bool CmpInst::isUnsigned(unsigned short predicate) {
2983 switch (predicate) {
2984 default: return false;
2985 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2986 case ICmpInst::ICMP_UGE: return true;
2990 bool CmpInst::isSigned(unsigned short predicate) {
2991 switch (predicate) {
2992 default: return false;
2993 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2994 case ICmpInst::ICMP_SGE: return true;
2998 bool CmpInst::isOrdered(unsigned short predicate) {
2999 switch (predicate) {
3000 default: return false;
3001 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3002 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3003 case FCmpInst::FCMP_ORD: return true;
3007 bool CmpInst::isUnordered(unsigned short predicate) {
3008 switch (predicate) {
3009 default: return false;
3010 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3011 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3012 case FCmpInst::FCMP_UNO: return true;
3016 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3018 default: return false;
3019 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3020 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3024 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3026 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3027 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3028 default: return false;
3033 //===----------------------------------------------------------------------===//
3034 // SwitchInst Implementation
3035 //===----------------------------------------------------------------------===//
3037 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
3038 assert(Value && Default);
3039 ReservedSpace = 2+NumCases*2;
3041 OperandList = allocHungoffUses(ReservedSpace);
3043 OperandList[0] = Value;
3044 OperandList[1] = Default;
3047 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3048 /// switch on and a default destination. The number of additional cases can
3049 /// be specified here to make memory allocation more efficient. This
3050 /// constructor can also autoinsert before another instruction.
3051 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3052 Instruction *InsertBefore)
3053 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3054 0, 0, InsertBefore) {
3055 init(Value, Default, NumCases);
3058 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3059 /// switch on and a default destination. The number of additional cases can
3060 /// be specified here to make memory allocation more efficient. This
3061 /// constructor also autoinserts at the end of the specified BasicBlock.
3062 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3063 BasicBlock *InsertAtEnd)
3064 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3065 0, 0, InsertAtEnd) {
3066 init(Value, Default, NumCases);
3069 SwitchInst::SwitchInst(const SwitchInst &SI)
3070 : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch,
3071 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
3072 Use *OL = OperandList, *InOL = SI.OperandList;
3073 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
3075 OL[i+1] = InOL[i+1];
3077 SubclassOptionalData = SI.SubclassOptionalData;
3080 SwitchInst::~SwitchInst() {
3081 dropHungoffUses(OperandList);
3085 /// addCase - Add an entry to the switch instruction...
3087 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3088 unsigned OpNo = NumOperands;
3089 if (OpNo+2 > ReservedSpace)
3090 resizeOperands(0); // Get more space!
3091 // Initialize some new operands.
3092 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3093 NumOperands = OpNo+2;
3094 OperandList[OpNo] = OnVal;
3095 OperandList[OpNo+1] = Dest;
3098 /// removeCase - This method removes the specified successor from the switch
3099 /// instruction. Note that this cannot be used to remove the default
3100 /// destination (successor #0).
3102 void SwitchInst::removeCase(unsigned idx) {
3103 assert(idx != 0 && "Cannot remove the default case!");
3104 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3106 unsigned NumOps = getNumOperands();
3107 Use *OL = OperandList;
3109 // Move everything after this operand down.
3111 // FIXME: we could just swap with the end of the list, then erase. However,
3112 // client might not expect this to happen. The code as it is thrashes the
3113 // use/def lists, which is kinda lame.
3114 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
3116 OL[i-2+1] = OL[i+1];
3119 // Nuke the last value.
3120 OL[NumOps-2].set(0);
3121 OL[NumOps-2+1].set(0);
3122 NumOperands = NumOps-2;
3125 /// resizeOperands - resize operands - This adjusts the length of the operands
3126 /// list according to the following behavior:
3127 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
3128 /// of operation. This grows the number of ops by 3 times.
3129 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
3130 /// 3. If NumOps == NumOperands, trim the reserved space.
3132 void SwitchInst::resizeOperands(unsigned NumOps) {
3133 unsigned e = getNumOperands();
3136 } else if (NumOps*2 > NumOperands) {
3137 // No resize needed.
3138 if (ReservedSpace >= NumOps) return;
3139 } else if (NumOps == NumOperands) {
3140 if (ReservedSpace == NumOps) return;
3145 ReservedSpace = NumOps;
3146 Use *NewOps = allocHungoffUses(NumOps);
3147 Use *OldOps = OperandList;
3148 for (unsigned i = 0; i != e; ++i) {
3149 NewOps[i] = OldOps[i];
3151 OperandList = NewOps;
3152 if (OldOps) Use::zap(OldOps, OldOps + e, true);
3156 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3157 return getSuccessor(idx);
3159 unsigned SwitchInst::getNumSuccessorsV() const {
3160 return getNumSuccessors();
3162 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3163 setSuccessor(idx, B);
3166 //===----------------------------------------------------------------------===//
3167 // SwitchInst Implementation
3168 //===----------------------------------------------------------------------===//
3170 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3171 assert(Address && Address->getType()->isPointerTy() &&
3172 "Address of indirectbr must be a pointer");
3173 ReservedSpace = 1+NumDests;
3175 OperandList = allocHungoffUses(ReservedSpace);
3177 OperandList[0] = Address;
3181 /// resizeOperands - resize operands - This adjusts the length of the operands
3182 /// list according to the following behavior:
3183 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
3184 /// of operation. This grows the number of ops by 2 times.
3185 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
3186 /// 3. If NumOps == NumOperands, trim the reserved space.
3188 void IndirectBrInst::resizeOperands(unsigned NumOps) {
3189 unsigned e = getNumOperands();
3192 } else if (NumOps*2 > NumOperands) {
3193 // No resize needed.
3194 if (ReservedSpace >= NumOps) return;
3195 } else if (NumOps == NumOperands) {
3196 if (ReservedSpace == NumOps) return;
3201 ReservedSpace = NumOps;
3202 Use *NewOps = allocHungoffUses(NumOps);
3203 Use *OldOps = OperandList;
3204 for (unsigned i = 0; i != e; ++i)
3205 NewOps[i] = OldOps[i];
3206 OperandList = NewOps;
3207 if (OldOps) Use::zap(OldOps, OldOps + e, true);
3210 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3211 Instruction *InsertBefore)
3212 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3213 0, 0, InsertBefore) {
3214 init(Address, NumCases);
3217 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3218 BasicBlock *InsertAtEnd)
3219 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3220 0, 0, InsertAtEnd) {
3221 init(Address, NumCases);
3224 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3225 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3226 allocHungoffUses(IBI.getNumOperands()),
3227 IBI.getNumOperands()) {
3228 Use *OL = OperandList, *InOL = IBI.OperandList;
3229 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3231 SubclassOptionalData = IBI.SubclassOptionalData;
3234 IndirectBrInst::~IndirectBrInst() {
3235 dropHungoffUses(OperandList);
3238 /// addDestination - Add a destination.
3240 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3241 unsigned OpNo = NumOperands;
3242 if (OpNo+1 > ReservedSpace)
3243 resizeOperands(0); // Get more space!
3244 // Initialize some new operands.
3245 assert(OpNo < ReservedSpace && "Growing didn't work!");
3246 NumOperands = OpNo+1;
3247 OperandList[OpNo] = DestBB;
3250 /// removeDestination - This method removes the specified successor from the
3251 /// indirectbr instruction.
3252 void IndirectBrInst::removeDestination(unsigned idx) {
3253 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3255 unsigned NumOps = getNumOperands();
3256 Use *OL = OperandList;
3258 // Replace this value with the last one.
3259 OL[idx+1] = OL[NumOps-1];
3261 // Nuke the last value.
3262 OL[NumOps-1].set(0);
3263 NumOperands = NumOps-1;
3266 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3267 return getSuccessor(idx);
3269 unsigned IndirectBrInst::getNumSuccessorsV() const {
3270 return getNumSuccessors();
3272 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3273 setSuccessor(idx, B);
3276 //===----------------------------------------------------------------------===//
3277 // clone_impl() implementations
3278 //===----------------------------------------------------------------------===//
3280 // Define these methods here so vtables don't get emitted into every translation
3281 // unit that uses these classes.
3283 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3284 return new (getNumOperands()) GetElementPtrInst(*this);
3287 BinaryOperator *BinaryOperator::clone_impl() const {
3288 return Create(getOpcode(), Op<0>(), Op<1>());
3291 FCmpInst* FCmpInst::clone_impl() const {
3292 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3295 ICmpInst* ICmpInst::clone_impl() const {
3296 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3299 ExtractValueInst *ExtractValueInst::clone_impl() const {
3300 return new ExtractValueInst(*this);
3303 InsertValueInst *InsertValueInst::clone_impl() const {
3304 return new InsertValueInst(*this);
3307 AllocaInst *AllocaInst::clone_impl() const {
3308 return new AllocaInst(getAllocatedType(),
3309 (Value*)getOperand(0),
3313 LoadInst *LoadInst::clone_impl() const {
3314 return new LoadInst(getOperand(0),
3315 Twine(), isVolatile(),
3319 StoreInst *StoreInst::clone_impl() const {
3320 return new StoreInst(getOperand(0), getOperand(1),
3321 isVolatile(), getAlignment());
3324 TruncInst *TruncInst::clone_impl() const {
3325 return new TruncInst(getOperand(0), getType());
3328 ZExtInst *ZExtInst::clone_impl() const {
3329 return new ZExtInst(getOperand(0), getType());
3332 SExtInst *SExtInst::clone_impl() const {
3333 return new SExtInst(getOperand(0), getType());
3336 FPTruncInst *FPTruncInst::clone_impl() const {
3337 return new FPTruncInst(getOperand(0), getType());
3340 FPExtInst *FPExtInst::clone_impl() const {
3341 return new FPExtInst(getOperand(0), getType());
3344 UIToFPInst *UIToFPInst::clone_impl() const {
3345 return new UIToFPInst(getOperand(0), getType());
3348 SIToFPInst *SIToFPInst::clone_impl() const {
3349 return new SIToFPInst(getOperand(0), getType());
3352 FPToUIInst *FPToUIInst::clone_impl() const {
3353 return new FPToUIInst(getOperand(0), getType());
3356 FPToSIInst *FPToSIInst::clone_impl() const {
3357 return new FPToSIInst(getOperand(0), getType());
3360 PtrToIntInst *PtrToIntInst::clone_impl() const {
3361 return new PtrToIntInst(getOperand(0), getType());
3364 IntToPtrInst *IntToPtrInst::clone_impl() const {
3365 return new IntToPtrInst(getOperand(0), getType());
3368 BitCastInst *BitCastInst::clone_impl() const {
3369 return new BitCastInst(getOperand(0), getType());
3372 CallInst *CallInst::clone_impl() const {
3373 return new(getNumOperands()) CallInst(*this);
3376 SelectInst *SelectInst::clone_impl() const {
3377 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3380 VAArgInst *VAArgInst::clone_impl() const {
3381 return new VAArgInst(getOperand(0), getType());
3384 ExtractElementInst *ExtractElementInst::clone_impl() const {
3385 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3388 InsertElementInst *InsertElementInst::clone_impl() const {
3389 return InsertElementInst::Create(getOperand(0),
3394 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3395 return new ShuffleVectorInst(getOperand(0),
3400 PHINode *PHINode::clone_impl() const {
3401 return new PHINode(*this);
3404 ReturnInst *ReturnInst::clone_impl() const {
3405 return new(getNumOperands()) ReturnInst(*this);
3408 BranchInst *BranchInst::clone_impl() const {
3409 unsigned Ops(getNumOperands());
3410 return new(Ops, Ops == 1) BranchInst(*this);
3413 SwitchInst *SwitchInst::clone_impl() const {
3414 return new SwitchInst(*this);
3417 IndirectBrInst *IndirectBrInst::clone_impl() const {
3418 return new IndirectBrInst(*this);
3422 InvokeInst *InvokeInst::clone_impl() const {
3423 return new(getNumOperands()) InvokeInst(*this);
3426 UnwindInst *UnwindInst::clone_impl() const {
3427 LLVMContext &Context = getContext();
3428 return new UnwindInst(Context);
3431 UnreachableInst *UnreachableInst::clone_impl() const {
3432 LLVMContext &Context = getContext();
3433 return new UnreachableInst(Context);