pass machinemoduleinfo down into getSymbolForDwarfGlobalReference,
[llvm/avr.git] / lib / VMCore / Instructions.cpp
blobbf0d0427f37ac03d7274a2c581aba791f1c1ea1e
1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements all of the non-inline methods for the LLVM instruction
11 // classes.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/Operator.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/MathExtras.h"
26 using namespace llvm;
28 //===----------------------------------------------------------------------===//
29 // CallSite Class
30 //===----------------------------------------------------------------------===//
32 #define CALLSITE_DELEGATE_GETTER(METHOD) \
33 Instruction *II(getInstruction()); \
34 return isCall() \
35 ? cast<CallInst>(II)->METHOD \
36 : cast<InvokeInst>(II)->METHOD
38 #define CALLSITE_DELEGATE_SETTER(METHOD) \
39 Instruction *II(getInstruction()); \
40 if (isCall()) \
41 cast<CallInst>(II)->METHOD; \
42 else \
43 cast<InvokeInst>(II)->METHOD
45 CallSite::CallSite(Instruction *C) {
46 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
47 I.setPointer(C);
48 I.setInt(isa<CallInst>(C));
50 CallingConv::ID CallSite::getCallingConv() const {
51 CALLSITE_DELEGATE_GETTER(getCallingConv());
53 void CallSite::setCallingConv(CallingConv::ID CC) {
54 CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
56 const AttrListPtr &CallSite::getAttributes() const {
57 CALLSITE_DELEGATE_GETTER(getAttributes());
59 void CallSite::setAttributes(const AttrListPtr &PAL) {
60 CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
62 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
63 CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
65 uint16_t CallSite::getParamAlignment(uint16_t i) const {
66 CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
68 bool CallSite::doesNotAccessMemory() const {
69 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
71 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
72 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
74 bool CallSite::onlyReadsMemory() const {
75 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
77 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
78 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
80 bool CallSite::doesNotReturn() const {
81 CALLSITE_DELEGATE_GETTER(doesNotReturn());
83 void CallSite::setDoesNotReturn(bool doesNotReturn) {
84 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
86 bool CallSite::doesNotThrow() const {
87 CALLSITE_DELEGATE_GETTER(doesNotThrow());
89 void CallSite::setDoesNotThrow(bool doesNotThrow) {
90 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
93 bool CallSite::hasArgument(const Value *Arg) const {
94 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
95 if (AI->get() == Arg)
96 return true;
97 return false;
100 #undef CALLSITE_DELEGATE_GETTER
101 #undef CALLSITE_DELEGATE_SETTER
103 //===----------------------------------------------------------------------===//
104 // TerminatorInst Class
105 //===----------------------------------------------------------------------===//
107 // Out of line virtual method, so the vtable, etc has a home.
108 TerminatorInst::~TerminatorInst() {
111 //===----------------------------------------------------------------------===//
112 // UnaryInstruction Class
113 //===----------------------------------------------------------------------===//
115 // Out of line virtual method, so the vtable, etc has a home.
116 UnaryInstruction::~UnaryInstruction() {
119 //===----------------------------------------------------------------------===//
120 // SelectInst Class
121 //===----------------------------------------------------------------------===//
123 /// areInvalidOperands - Return a string if the specified operands are invalid
124 /// for a select operation, otherwise return null.
125 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
126 if (Op1->getType() != Op2->getType())
127 return "both values to select must have same type";
129 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
130 // Vector select.
131 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
132 return "vector select condition element type must be i1";
133 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
134 if (ET == 0)
135 return "selected values for vector select must be vectors";
136 if (ET->getNumElements() != VT->getNumElements())
137 return "vector select requires selected vectors to have "
138 "the same vector length as select condition";
139 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
140 return "select condition must be i1 or <n x i1>";
142 return 0;
146 //===----------------------------------------------------------------------===//
147 // PHINode Class
148 //===----------------------------------------------------------------------===//
150 PHINode::PHINode(const PHINode &PN)
151 : Instruction(PN.getType(), Instruction::PHI,
152 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
153 ReservedSpace(PN.getNumOperands()) {
154 Use *OL = OperandList;
155 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
156 OL[i] = PN.getOperand(i);
157 OL[i+1] = PN.getOperand(i+1);
159 SubclassOptionalData = PN.SubclassOptionalData;
162 PHINode::~PHINode() {
163 if (OperandList)
164 dropHungoffUses(OperandList);
167 // removeIncomingValue - Remove an incoming value. This is useful if a
168 // predecessor basic block is deleted.
169 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
170 unsigned NumOps = getNumOperands();
171 Use *OL = OperandList;
172 assert(Idx*2 < NumOps && "BB not in PHI node!");
173 Value *Removed = OL[Idx*2];
175 // Move everything after this operand down.
177 // FIXME: we could just swap with the end of the list, then erase. However,
178 // client might not expect this to happen. The code as it is thrashes the
179 // use/def lists, which is kinda lame.
180 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
181 OL[i-2] = OL[i];
182 OL[i-2+1] = OL[i+1];
185 // Nuke the last value.
186 OL[NumOps-2].set(0);
187 OL[NumOps-2+1].set(0);
188 NumOperands = NumOps-2;
190 // If the PHI node is dead, because it has zero entries, nuke it now.
191 if (NumOps == 2 && DeletePHIIfEmpty) {
192 // If anyone is using this PHI, make them use a dummy value instead...
193 replaceAllUsesWith(UndefValue::get(getType()));
194 eraseFromParent();
196 return Removed;
199 /// resizeOperands - resize operands - This adjusts the length of the operands
200 /// list according to the following behavior:
201 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
202 /// of operation. This grows the number of ops by 1.5 times.
203 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
204 /// 3. If NumOps == NumOperands, trim the reserved space.
206 void PHINode::resizeOperands(unsigned NumOps) {
207 unsigned e = getNumOperands();
208 if (NumOps == 0) {
209 NumOps = e*3/2;
210 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
211 } else if (NumOps*2 > NumOperands) {
212 // No resize needed.
213 if (ReservedSpace >= NumOps) return;
214 } else if (NumOps == NumOperands) {
215 if (ReservedSpace == NumOps) return;
216 } else {
217 return;
220 ReservedSpace = NumOps;
221 Use *OldOps = OperandList;
222 Use *NewOps = allocHungoffUses(NumOps);
223 std::copy(OldOps, OldOps + e, NewOps);
224 OperandList = NewOps;
225 if (OldOps) Use::zap(OldOps, OldOps + e, true);
228 /// hasConstantValue - If the specified PHI node always merges together the same
229 /// value, return the value, otherwise return null.
231 /// If the PHI has undef operands, but all the rest of the operands are
232 /// some unique value, return that value if it can be proved that the
233 /// value dominates the PHI. If DT is null, use a conservative check,
234 /// otherwise use DT to test for dominance.
236 Value *PHINode::hasConstantValue(DominatorTree *DT) const {
237 // If the PHI node only has one incoming value, eliminate the PHI node...
238 if (getNumIncomingValues() == 1) {
239 if (getIncomingValue(0) != this) // not X = phi X
240 return getIncomingValue(0);
241 else
242 return UndefValue::get(getType()); // Self cycle is dead.
245 // Otherwise if all of the incoming values are the same for the PHI, replace
246 // the PHI node with the incoming value.
248 Value *InVal = 0;
249 bool HasUndefInput = false;
250 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
251 if (isa<UndefValue>(getIncomingValue(i))) {
252 HasUndefInput = true;
253 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
254 if (InVal && getIncomingValue(i) != InVal)
255 return 0; // Not the same, bail out.
256 else
257 InVal = getIncomingValue(i);
260 // The only case that could cause InVal to be null is if we have a PHI node
261 // that only has entries for itself. In this case, there is no entry into the
262 // loop, so kill the PHI.
264 if (InVal == 0) InVal = UndefValue::get(getType());
266 // If we have a PHI node like phi(X, undef, X), where X is defined by some
267 // instruction, we cannot always return X as the result of the PHI node. Only
268 // do this if X is not an instruction (thus it must dominate the PHI block),
269 // or if the client is prepared to deal with this possibility.
270 if (HasUndefInput)
271 if (Instruction *IV = dyn_cast<Instruction>(InVal)) {
272 if (DT) {
273 // We have a DominatorTree. Do a precise test.
274 if (!DT->dominates(IV, this))
275 return 0;
276 } else {
277 // If it's in the entry block, it dominates everything.
278 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
279 isa<InvokeInst>(IV))
280 return 0; // Cannot guarantee that InVal dominates this PHINode.
284 // All of the incoming values are the same, return the value now.
285 return InVal;
289 //===----------------------------------------------------------------------===//
290 // CallInst Implementation
291 //===----------------------------------------------------------------------===//
293 CallInst::~CallInst() {
296 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
297 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
298 Use *OL = OperandList;
299 OL[0] = Func;
301 const FunctionType *FTy =
302 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
303 FTy = FTy; // silence warning.
305 assert((NumParams == FTy->getNumParams() ||
306 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
307 "Calling a function with bad signature!");
308 for (unsigned i = 0; i != NumParams; ++i) {
309 assert((i >= FTy->getNumParams() ||
310 FTy->getParamType(i) == Params[i]->getType()) &&
311 "Calling a function with a bad signature!");
312 OL[i+1] = Params[i];
316 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
317 assert(NumOperands == 3 && "NumOperands not set up?");
318 Use *OL = OperandList;
319 OL[0] = Func;
320 OL[1] = Actual1;
321 OL[2] = Actual2;
323 const FunctionType *FTy =
324 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
325 FTy = FTy; // silence warning.
327 assert((FTy->getNumParams() == 2 ||
328 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
329 "Calling a function with bad signature");
330 assert((0 >= FTy->getNumParams() ||
331 FTy->getParamType(0) == Actual1->getType()) &&
332 "Calling a function with a bad signature!");
333 assert((1 >= FTy->getNumParams() ||
334 FTy->getParamType(1) == Actual2->getType()) &&
335 "Calling a function with a bad signature!");
338 void CallInst::init(Value *Func, Value *Actual) {
339 assert(NumOperands == 2 && "NumOperands not set up?");
340 Use *OL = OperandList;
341 OL[0] = Func;
342 OL[1] = Actual;
344 const FunctionType *FTy =
345 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
346 FTy = FTy; // silence warning.
348 assert((FTy->getNumParams() == 1 ||
349 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
350 "Calling a function with bad signature");
351 assert((0 == FTy->getNumParams() ||
352 FTy->getParamType(0) == Actual->getType()) &&
353 "Calling a function with a bad signature!");
356 void CallInst::init(Value *Func) {
357 assert(NumOperands == 1 && "NumOperands not set up?");
358 Use *OL = OperandList;
359 OL[0] = Func;
361 const FunctionType *FTy =
362 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
363 FTy = FTy; // silence warning.
365 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
368 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
369 Instruction *InsertBefore)
370 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
371 ->getElementType())->getReturnType(),
372 Instruction::Call,
373 OperandTraits<CallInst>::op_end(this) - 2,
374 2, InsertBefore) {
375 init(Func, Actual);
376 setName(Name);
379 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
380 BasicBlock *InsertAtEnd)
381 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
382 ->getElementType())->getReturnType(),
383 Instruction::Call,
384 OperandTraits<CallInst>::op_end(this) - 2,
385 2, InsertAtEnd) {
386 init(Func, Actual);
387 setName(Name);
389 CallInst::CallInst(Value *Func, const Twine &Name,
390 Instruction *InsertBefore)
391 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
392 ->getElementType())->getReturnType(),
393 Instruction::Call,
394 OperandTraits<CallInst>::op_end(this) - 1,
395 1, InsertBefore) {
396 init(Func);
397 setName(Name);
400 CallInst::CallInst(Value *Func, const Twine &Name,
401 BasicBlock *InsertAtEnd)
402 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
403 ->getElementType())->getReturnType(),
404 Instruction::Call,
405 OperandTraits<CallInst>::op_end(this) - 1,
406 1, InsertAtEnd) {
407 init(Func);
408 setName(Name);
411 CallInst::CallInst(const CallInst &CI)
412 : Instruction(CI.getType(), Instruction::Call,
413 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
414 CI.getNumOperands()) {
415 setAttributes(CI.getAttributes());
416 SubclassData = CI.SubclassData;
417 Use *OL = OperandList;
418 Use *InOL = CI.OperandList;
419 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
420 OL[i] = InOL[i];
421 SubclassOptionalData = CI.SubclassOptionalData;
424 void CallInst::addAttribute(unsigned i, Attributes attr) {
425 AttrListPtr PAL = getAttributes();
426 PAL = PAL.addAttr(i, attr);
427 setAttributes(PAL);
430 void CallInst::removeAttribute(unsigned i, Attributes attr) {
431 AttrListPtr PAL = getAttributes();
432 PAL = PAL.removeAttr(i, attr);
433 setAttributes(PAL);
436 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
437 if (AttributeList.paramHasAttr(i, attr))
438 return true;
439 if (const Function *F = getCalledFunction())
440 return F->paramHasAttr(i, attr);
441 return false;
444 /// IsConstantOne - Return true only if val is constant int 1
445 static bool IsConstantOne(Value *val) {
446 assert(val && "IsConstantOne does not work with NULL val");
447 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
450 static Value *checkArraySize(Value *Amt, const Type *IntPtrTy) {
451 if (!Amt)
452 Amt = ConstantInt::get(IntPtrTy, 1);
453 else {
454 assert(!isa<BasicBlock>(Amt) &&
455 "Passed basic block into malloc size parameter! Use other ctor");
456 assert(Amt->getType() == IntPtrTy &&
457 "Malloc array size is not an intptr!");
459 return Amt;
462 static Value *createMalloc(Instruction *InsertBefore, BasicBlock *InsertAtEnd,
463 const Type *AllocTy, const Type *IntPtrTy,
464 Value *ArraySize, const Twine &NameStr) {
465 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
466 "createMalloc needs only InsertBefore or InsertAtEnd");
467 const PointerType *AllocPtrType = dyn_cast<PointerType>(AllocTy);
468 assert(AllocPtrType && "CreateMalloc passed a non-pointer allocation type");
470 ArraySize = checkArraySize(ArraySize, IntPtrTy);
472 // malloc(type) becomes i8 *malloc(size)
473 Value *AllocSize = ConstantExpr::getSizeOf(AllocPtrType->getElementType());
474 AllocSize = ConstantExpr::getTruncOrBitCast(cast<Constant>(AllocSize),
475 IntPtrTy);
476 if (!IsConstantOne(ArraySize)) {
477 if (IsConstantOne(AllocSize)) {
478 AllocSize = ArraySize; // Operand * 1 = Operand
479 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
480 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
481 false /*ZExt*/);
482 // Malloc arg is constant product of type size and array size
483 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
484 } else {
485 Value *Scale = ArraySize;
486 if (Scale->getType() != IntPtrTy) {
487 if (InsertBefore)
488 Scale = CastInst::CreateIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
489 "", InsertBefore);
490 else
491 Scale = CastInst::CreateIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
492 "", InsertAtEnd);
494 // Multiply type size by the array size...
495 if (InsertBefore)
496 AllocSize = BinaryOperator::CreateMul(Scale, AllocSize,
497 "", InsertBefore);
498 else
499 AllocSize = BinaryOperator::CreateMul(Scale, AllocSize,
500 "", InsertAtEnd);
504 // Create the call to Malloc.
505 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
506 Module* M = BB->getParent()->getParent();
507 const Type *BPTy = PointerType::getUnqual(Type::getInt8Ty(BB->getContext()));
508 // prototype malloc as "void *malloc(size_t)"
509 Constant *MallocFunc = M->getOrInsertFunction("malloc", BPTy,
510 IntPtrTy, NULL);
511 CallInst *MCall = NULL;
512 if (InsertBefore)
513 MCall = CallInst::Create(MallocFunc, AllocSize, NameStr, InsertBefore);
514 else
515 MCall = CallInst::Create(MallocFunc, AllocSize, NameStr, InsertAtEnd);
516 MCall->setTailCall();
518 // Create a cast instruction to convert to the right type...
519 assert(MCall->getType() != Type::getVoidTy(BB->getContext()) &&
520 "Malloc has void return type");
521 Value *MCast;
522 if (InsertBefore)
523 MCast = new BitCastInst(MCall, AllocPtrType, NameStr, InsertBefore);
524 else
525 MCast = new BitCastInst(MCall, AllocPtrType, NameStr);
526 return MCast;
529 /// CreateMalloc - Generate the IR for a call to malloc:
530 /// 1. Compute the malloc call's argument as the specified type's size,
531 /// possibly multiplied by the array size if the array size is not
532 /// constant 1.
533 /// 2. Call malloc with that argument.
534 /// 3. Bitcast the result of the malloc call to the specified type.
535 Value *CallInst::CreateMalloc(Instruction *InsertBefore,
536 const Type *AllocTy, const Type *IntPtrTy,
537 Value *ArraySize, const Twine &NameStr) {
538 return createMalloc(InsertBefore, NULL, AllocTy,
539 IntPtrTy, ArraySize, NameStr);
542 /// CreateMalloc - Generate the IR for a call to malloc:
543 /// 1. Compute the malloc call's argument as the specified type's size,
544 /// possibly multiplied by the array size if the array size is not
545 /// constant 1.
546 /// 2. Call malloc with that argument.
547 /// 3. Bitcast the result of the malloc call to the specified type.
548 /// Note: This function does not add the bitcast to the basic block, that is the
549 /// responsibility of the caller.
550 Value *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
551 const Type *AllocTy, const Type *IntPtrTy,
552 Value *ArraySize, const Twine &NameStr) {
553 return createMalloc(NULL, InsertAtEnd, AllocTy,
554 IntPtrTy, ArraySize, NameStr);
557 //===----------------------------------------------------------------------===//
558 // InvokeInst Implementation
559 //===----------------------------------------------------------------------===//
561 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
562 Value* const *Args, unsigned NumArgs) {
563 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
564 Use *OL = OperandList;
565 OL[0] = Fn;
566 OL[1] = IfNormal;
567 OL[2] = IfException;
568 const FunctionType *FTy =
569 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
570 FTy = FTy; // silence warning.
572 assert(((NumArgs == FTy->getNumParams()) ||
573 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
574 "Calling a function with bad signature");
576 for (unsigned i = 0, e = NumArgs; i != e; i++) {
577 assert((i >= FTy->getNumParams() ||
578 FTy->getParamType(i) == Args[i]->getType()) &&
579 "Invoking a function with a bad signature!");
581 OL[i+3] = Args[i];
585 InvokeInst::InvokeInst(const InvokeInst &II)
586 : TerminatorInst(II.getType(), Instruction::Invoke,
587 OperandTraits<InvokeInst>::op_end(this)
588 - II.getNumOperands(),
589 II.getNumOperands()) {
590 setAttributes(II.getAttributes());
591 SubclassData = II.SubclassData;
592 Use *OL = OperandList, *InOL = II.OperandList;
593 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
594 OL[i] = InOL[i];
595 SubclassOptionalData = II.SubclassOptionalData;
598 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
599 return getSuccessor(idx);
601 unsigned InvokeInst::getNumSuccessorsV() const {
602 return getNumSuccessors();
604 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
605 return setSuccessor(idx, B);
608 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
609 if (AttributeList.paramHasAttr(i, attr))
610 return true;
611 if (const Function *F = getCalledFunction())
612 return F->paramHasAttr(i, attr);
613 return false;
616 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
617 AttrListPtr PAL = getAttributes();
618 PAL = PAL.addAttr(i, attr);
619 setAttributes(PAL);
622 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
623 AttrListPtr PAL = getAttributes();
624 PAL = PAL.removeAttr(i, attr);
625 setAttributes(PAL);
629 //===----------------------------------------------------------------------===//
630 // ReturnInst Implementation
631 //===----------------------------------------------------------------------===//
633 ReturnInst::ReturnInst(const ReturnInst &RI)
634 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
635 OperandTraits<ReturnInst>::op_end(this) -
636 RI.getNumOperands(),
637 RI.getNumOperands()) {
638 if (RI.getNumOperands())
639 Op<0>() = RI.Op<0>();
640 SubclassOptionalData = RI.SubclassOptionalData;
643 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
644 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
645 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
646 InsertBefore) {
647 if (retVal)
648 Op<0>() = retVal;
650 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
651 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
652 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
653 InsertAtEnd) {
654 if (retVal)
655 Op<0>() = retVal;
657 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
658 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
659 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
662 unsigned ReturnInst::getNumSuccessorsV() const {
663 return getNumSuccessors();
666 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
667 /// emit the vtable for the class in this translation unit.
668 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
669 llvm_unreachable("ReturnInst has no successors!");
672 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
673 llvm_unreachable("ReturnInst has no successors!");
674 return 0;
677 ReturnInst::~ReturnInst() {
680 //===----------------------------------------------------------------------===//
681 // UnwindInst Implementation
682 //===----------------------------------------------------------------------===//
684 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
685 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
686 0, 0, InsertBefore) {
688 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
689 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
690 0, 0, InsertAtEnd) {
694 unsigned UnwindInst::getNumSuccessorsV() const {
695 return getNumSuccessors();
698 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
699 llvm_unreachable("UnwindInst has no successors!");
702 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
703 llvm_unreachable("UnwindInst has no successors!");
704 return 0;
707 //===----------------------------------------------------------------------===//
708 // UnreachableInst Implementation
709 //===----------------------------------------------------------------------===//
711 UnreachableInst::UnreachableInst(LLVMContext &Context,
712 Instruction *InsertBefore)
713 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
714 0, 0, InsertBefore) {
716 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
717 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
718 0, 0, InsertAtEnd) {
721 unsigned UnreachableInst::getNumSuccessorsV() const {
722 return getNumSuccessors();
725 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
726 llvm_unreachable("UnwindInst has no successors!");
729 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
730 llvm_unreachable("UnwindInst has no successors!");
731 return 0;
734 //===----------------------------------------------------------------------===//
735 // BranchInst Implementation
736 //===----------------------------------------------------------------------===//
738 void BranchInst::AssertOK() {
739 if (isConditional())
740 assert(getCondition()->getType() == Type::getInt1Ty(getContext()) &&
741 "May only branch on boolean predicates!");
744 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
745 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
746 OperandTraits<BranchInst>::op_end(this) - 1,
747 1, InsertBefore) {
748 assert(IfTrue != 0 && "Branch destination may not be null!");
749 Op<-1>() = IfTrue;
751 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
752 Instruction *InsertBefore)
753 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
754 OperandTraits<BranchInst>::op_end(this) - 3,
755 3, InsertBefore) {
756 Op<-1>() = IfTrue;
757 Op<-2>() = IfFalse;
758 Op<-3>() = Cond;
759 #ifndef NDEBUG
760 AssertOK();
761 #endif
764 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
765 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
766 OperandTraits<BranchInst>::op_end(this) - 1,
767 1, InsertAtEnd) {
768 assert(IfTrue != 0 && "Branch destination may not be null!");
769 Op<-1>() = IfTrue;
772 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
773 BasicBlock *InsertAtEnd)
774 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
775 OperandTraits<BranchInst>::op_end(this) - 3,
776 3, InsertAtEnd) {
777 Op<-1>() = IfTrue;
778 Op<-2>() = IfFalse;
779 Op<-3>() = Cond;
780 #ifndef NDEBUG
781 AssertOK();
782 #endif
786 BranchInst::BranchInst(const BranchInst &BI) :
787 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
788 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
789 BI.getNumOperands()) {
790 Op<-1>() = BI.Op<-1>();
791 if (BI.getNumOperands() != 1) {
792 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
793 Op<-3>() = BI.Op<-3>();
794 Op<-2>() = BI.Op<-2>();
796 SubclassOptionalData = BI.SubclassOptionalData;
800 Use* Use::getPrefix() {
801 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
802 if (PotentialPrefix.getOpaqueValue())
803 return 0;
805 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
808 BranchInst::~BranchInst() {
809 if (NumOperands == 1) {
810 if (Use *Prefix = OperandList->getPrefix()) {
811 Op<-1>() = 0;
813 // mark OperandList to have a special value for scrutiny
814 // by baseclass destructors and operator delete
815 OperandList = Prefix;
816 } else {
817 NumOperands = 3;
818 OperandList = op_begin();
824 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
825 return getSuccessor(idx);
827 unsigned BranchInst::getNumSuccessorsV() const {
828 return getNumSuccessors();
830 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
831 setSuccessor(idx, B);
835 //===----------------------------------------------------------------------===//
836 // AllocationInst Implementation
837 //===----------------------------------------------------------------------===//
839 static Value *getAISize(LLVMContext &Context, Value *Amt) {
840 if (!Amt)
841 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
842 else {
843 assert(!isa<BasicBlock>(Amt) &&
844 "Passed basic block into allocation size parameter! Use other ctor");
845 assert(Amt->getType() == Type::getInt32Ty(Context) &&
846 "Malloc/Allocation array size is not a 32-bit integer!");
848 return Amt;
851 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
852 unsigned Align, const Twine &Name,
853 Instruction *InsertBefore)
854 : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
855 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
856 setAlignment(Align);
857 assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!");
858 setName(Name);
861 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
862 unsigned Align, const Twine &Name,
863 BasicBlock *InsertAtEnd)
864 : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
865 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
866 setAlignment(Align);
867 assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!");
868 setName(Name);
871 // Out of line virtual method, so the vtable, etc has a home.
872 AllocationInst::~AllocationInst() {
875 void AllocationInst::setAlignment(unsigned Align) {
876 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
877 SubclassData = Log2_32(Align) + 1;
878 assert(getAlignment() == Align && "Alignment representation error!");
881 bool AllocationInst::isArrayAllocation() const {
882 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
883 return CI->getZExtValue() != 1;
884 return true;
887 const Type *AllocationInst::getAllocatedType() const {
888 return getType()->getElementType();
891 /// isStaticAlloca - Return true if this alloca is in the entry block of the
892 /// function and is a constant size. If so, the code generator will fold it
893 /// into the prolog/epilog code, so it is basically free.
894 bool AllocaInst::isStaticAlloca() const {
895 // Must be constant size.
896 if (!isa<ConstantInt>(getArraySize())) return false;
898 // Must be in the entry block.
899 const BasicBlock *Parent = getParent();
900 return Parent == &Parent->getParent()->front();
903 //===----------------------------------------------------------------------===//
904 // FreeInst Implementation
905 //===----------------------------------------------------------------------===//
907 void FreeInst::AssertOK() {
908 assert(isa<PointerType>(getOperand(0)->getType()) &&
909 "Can not free something of nonpointer type!");
912 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
913 : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
914 Free, Ptr, InsertBefore) {
915 AssertOK();
918 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
919 : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
920 Free, Ptr, InsertAtEnd) {
921 AssertOK();
925 //===----------------------------------------------------------------------===//
926 // LoadInst Implementation
927 //===----------------------------------------------------------------------===//
929 void LoadInst::AssertOK() {
930 assert(isa<PointerType>(getOperand(0)->getType()) &&
931 "Ptr must have pointer type.");
934 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
935 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
936 Load, Ptr, InsertBef) {
937 setVolatile(false);
938 setAlignment(0);
939 AssertOK();
940 setName(Name);
943 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
944 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
945 Load, Ptr, InsertAE) {
946 setVolatile(false);
947 setAlignment(0);
948 AssertOK();
949 setName(Name);
952 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
953 Instruction *InsertBef)
954 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
955 Load, Ptr, InsertBef) {
956 setVolatile(isVolatile);
957 setAlignment(0);
958 AssertOK();
959 setName(Name);
962 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
963 unsigned Align, Instruction *InsertBef)
964 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
965 Load, Ptr, InsertBef) {
966 setVolatile(isVolatile);
967 setAlignment(Align);
968 AssertOK();
969 setName(Name);
972 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
973 unsigned Align, BasicBlock *InsertAE)
974 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
975 Load, Ptr, InsertAE) {
976 setVolatile(isVolatile);
977 setAlignment(Align);
978 AssertOK();
979 setName(Name);
982 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
983 BasicBlock *InsertAE)
984 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
985 Load, Ptr, InsertAE) {
986 setVolatile(isVolatile);
987 setAlignment(0);
988 AssertOK();
989 setName(Name);
994 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
995 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
996 Load, Ptr, InsertBef) {
997 setVolatile(false);
998 setAlignment(0);
999 AssertOK();
1000 if (Name && Name[0]) setName(Name);
1003 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1004 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1005 Load, Ptr, InsertAE) {
1006 setVolatile(false);
1007 setAlignment(0);
1008 AssertOK();
1009 if (Name && Name[0]) setName(Name);
1012 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1013 Instruction *InsertBef)
1014 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1015 Load, Ptr, InsertBef) {
1016 setVolatile(isVolatile);
1017 setAlignment(0);
1018 AssertOK();
1019 if (Name && Name[0]) setName(Name);
1022 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1023 BasicBlock *InsertAE)
1024 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1025 Load, Ptr, InsertAE) {
1026 setVolatile(isVolatile);
1027 setAlignment(0);
1028 AssertOK();
1029 if (Name && Name[0]) setName(Name);
1032 void LoadInst::setAlignment(unsigned Align) {
1033 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1034 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1037 //===----------------------------------------------------------------------===//
1038 // StoreInst Implementation
1039 //===----------------------------------------------------------------------===//
1041 void StoreInst::AssertOK() {
1042 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1043 assert(isa<PointerType>(getOperand(1)->getType()) &&
1044 "Ptr must have pointer type!");
1045 assert(getOperand(0)->getType() ==
1046 cast<PointerType>(getOperand(1)->getType())->getElementType()
1047 && "Ptr must be a pointer to Val type!");
1051 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1052 : Instruction(Type::getVoidTy(val->getContext()), Store,
1053 OperandTraits<StoreInst>::op_begin(this),
1054 OperandTraits<StoreInst>::operands(this),
1055 InsertBefore) {
1056 Op<0>() = val;
1057 Op<1>() = addr;
1058 setVolatile(false);
1059 setAlignment(0);
1060 AssertOK();
1063 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1064 : Instruction(Type::getVoidTy(val->getContext()), Store,
1065 OperandTraits<StoreInst>::op_begin(this),
1066 OperandTraits<StoreInst>::operands(this),
1067 InsertAtEnd) {
1068 Op<0>() = val;
1069 Op<1>() = addr;
1070 setVolatile(false);
1071 setAlignment(0);
1072 AssertOK();
1075 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1076 Instruction *InsertBefore)
1077 : Instruction(Type::getVoidTy(val->getContext()), Store,
1078 OperandTraits<StoreInst>::op_begin(this),
1079 OperandTraits<StoreInst>::operands(this),
1080 InsertBefore) {
1081 Op<0>() = val;
1082 Op<1>() = addr;
1083 setVolatile(isVolatile);
1084 setAlignment(0);
1085 AssertOK();
1088 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1089 unsigned Align, Instruction *InsertBefore)
1090 : Instruction(Type::getVoidTy(val->getContext()), Store,
1091 OperandTraits<StoreInst>::op_begin(this),
1092 OperandTraits<StoreInst>::operands(this),
1093 InsertBefore) {
1094 Op<0>() = val;
1095 Op<1>() = addr;
1096 setVolatile(isVolatile);
1097 setAlignment(Align);
1098 AssertOK();
1101 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1102 unsigned Align, BasicBlock *InsertAtEnd)
1103 : Instruction(Type::getVoidTy(val->getContext()), Store,
1104 OperandTraits<StoreInst>::op_begin(this),
1105 OperandTraits<StoreInst>::operands(this),
1106 InsertAtEnd) {
1107 Op<0>() = val;
1108 Op<1>() = addr;
1109 setVolatile(isVolatile);
1110 setAlignment(Align);
1111 AssertOK();
1114 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1115 BasicBlock *InsertAtEnd)
1116 : Instruction(Type::getVoidTy(val->getContext()), Store,
1117 OperandTraits<StoreInst>::op_begin(this),
1118 OperandTraits<StoreInst>::operands(this),
1119 InsertAtEnd) {
1120 Op<0>() = val;
1121 Op<1>() = addr;
1122 setVolatile(isVolatile);
1123 setAlignment(0);
1124 AssertOK();
1127 void StoreInst::setAlignment(unsigned Align) {
1128 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1129 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1132 //===----------------------------------------------------------------------===//
1133 // GetElementPtrInst Implementation
1134 //===----------------------------------------------------------------------===//
1136 static unsigned retrieveAddrSpace(const Value *Val) {
1137 return cast<PointerType>(Val->getType())->getAddressSpace();
1140 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1141 const Twine &Name) {
1142 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1143 Use *OL = OperandList;
1144 OL[0] = Ptr;
1146 for (unsigned i = 0; i != NumIdx; ++i)
1147 OL[i+1] = Idx[i];
1149 setName(Name);
1152 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1153 assert(NumOperands == 2 && "NumOperands not initialized?");
1154 Use *OL = OperandList;
1155 OL[0] = Ptr;
1156 OL[1] = Idx;
1158 setName(Name);
1161 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1162 : Instruction(GEPI.getType(), GetElementPtr,
1163 OperandTraits<GetElementPtrInst>::op_end(this)
1164 - GEPI.getNumOperands(),
1165 GEPI.getNumOperands()) {
1166 Use *OL = OperandList;
1167 Use *GEPIOL = GEPI.OperandList;
1168 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1169 OL[i] = GEPIOL[i];
1170 SubclassOptionalData = GEPI.SubclassOptionalData;
1173 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1174 const Twine &Name, Instruction *InBe)
1175 : Instruction(PointerType::get(
1176 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1177 GetElementPtr,
1178 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1179 2, InBe) {
1180 init(Ptr, Idx, Name);
1183 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1184 const Twine &Name, BasicBlock *IAE)
1185 : Instruction(PointerType::get(
1186 checkType(getIndexedType(Ptr->getType(),Idx)),
1187 retrieveAddrSpace(Ptr)),
1188 GetElementPtr,
1189 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1190 2, IAE) {
1191 init(Ptr, Idx, Name);
1194 /// getIndexedType - Returns the type of the element that would be accessed with
1195 /// a gep instruction with the specified parameters.
1197 /// The Idxs pointer should point to a continuous piece of memory containing the
1198 /// indices, either as Value* or uint64_t.
1200 /// A null type is returned if the indices are invalid for the specified
1201 /// pointer type.
1203 template <typename IndexTy>
1204 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1205 unsigned NumIdx) {
1206 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1207 if (!PTy) return 0; // Type isn't a pointer type!
1208 const Type *Agg = PTy->getElementType();
1210 // Handle the special case of the empty set index set, which is always valid.
1211 if (NumIdx == 0)
1212 return Agg;
1214 // If there is at least one index, the top level type must be sized, otherwise
1215 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1216 // that contain opaque types) under the assumption that it will be resolved to
1217 // a sane type later.
1218 if (!Agg->isSized() && !Agg->isAbstract())
1219 return 0;
1221 unsigned CurIdx = 1;
1222 for (; CurIdx != NumIdx; ++CurIdx) {
1223 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1224 if (!CT || isa<PointerType>(CT)) return 0;
1225 IndexTy Index = Idxs[CurIdx];
1226 if (!CT->indexValid(Index)) return 0;
1227 Agg = CT->getTypeAtIndex(Index);
1229 // If the new type forwards to another type, then it is in the middle
1230 // of being refined to another type (and hence, may have dropped all
1231 // references to what it was using before). So, use the new forwarded
1232 // type.
1233 if (const Type *Ty = Agg->getForwardedType())
1234 Agg = Ty;
1236 return CurIdx == NumIdx ? Agg : 0;
1239 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1240 Value* const *Idxs,
1241 unsigned NumIdx) {
1242 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1245 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1246 uint64_t const *Idxs,
1247 unsigned NumIdx) {
1248 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1251 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1252 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1253 if (!PTy) return 0; // Type isn't a pointer type!
1255 // Check the pointer index.
1256 if (!PTy->indexValid(Idx)) return 0;
1258 return PTy->getElementType();
1262 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1263 /// zeros. If so, the result pointer and the first operand have the same
1264 /// value, just potentially different types.
1265 bool GetElementPtrInst::hasAllZeroIndices() const {
1266 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1267 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1268 if (!CI->isZero()) return false;
1269 } else {
1270 return false;
1273 return true;
1276 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1277 /// constant integers. If so, the result pointer and the first operand have
1278 /// a constant offset between them.
1279 bool GetElementPtrInst::hasAllConstantIndices() const {
1280 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1281 if (!isa<ConstantInt>(getOperand(i)))
1282 return false;
1284 return true;
1287 void GetElementPtrInst::setIsInBounds(bool B) {
1288 cast<GEPOperator>(this)->setIsInBounds(B);
1291 //===----------------------------------------------------------------------===//
1292 // ExtractElementInst Implementation
1293 //===----------------------------------------------------------------------===//
1295 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1296 const Twine &Name,
1297 Instruction *InsertBef)
1298 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1299 ExtractElement,
1300 OperandTraits<ExtractElementInst>::op_begin(this),
1301 2, InsertBef) {
1302 assert(isValidOperands(Val, Index) &&
1303 "Invalid extractelement instruction operands!");
1304 Op<0>() = Val;
1305 Op<1>() = Index;
1306 setName(Name);
1309 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1310 const Twine &Name,
1311 BasicBlock *InsertAE)
1312 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1313 ExtractElement,
1314 OperandTraits<ExtractElementInst>::op_begin(this),
1315 2, InsertAE) {
1316 assert(isValidOperands(Val, Index) &&
1317 "Invalid extractelement instruction operands!");
1319 Op<0>() = Val;
1320 Op<1>() = Index;
1321 setName(Name);
1325 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1326 if (!isa<VectorType>(Val->getType()) ||
1327 Index->getType() != Type::getInt32Ty(Val->getContext()))
1328 return false;
1329 return true;
1333 //===----------------------------------------------------------------------===//
1334 // InsertElementInst Implementation
1335 //===----------------------------------------------------------------------===//
1337 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1338 const Twine &Name,
1339 Instruction *InsertBef)
1340 : Instruction(Vec->getType(), InsertElement,
1341 OperandTraits<InsertElementInst>::op_begin(this),
1342 3, InsertBef) {
1343 assert(isValidOperands(Vec, Elt, Index) &&
1344 "Invalid insertelement instruction operands!");
1345 Op<0>() = Vec;
1346 Op<1>() = Elt;
1347 Op<2>() = Index;
1348 setName(Name);
1351 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1352 const Twine &Name,
1353 BasicBlock *InsertAE)
1354 : Instruction(Vec->getType(), InsertElement,
1355 OperandTraits<InsertElementInst>::op_begin(this),
1356 3, InsertAE) {
1357 assert(isValidOperands(Vec, Elt, Index) &&
1358 "Invalid insertelement instruction operands!");
1360 Op<0>() = Vec;
1361 Op<1>() = Elt;
1362 Op<2>() = Index;
1363 setName(Name);
1366 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1367 const Value *Index) {
1368 if (!isa<VectorType>(Vec->getType()))
1369 return false; // First operand of insertelement must be vector type.
1371 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1372 return false;// Second operand of insertelement must be vector element type.
1374 if (Index->getType() != Type::getInt32Ty(Vec->getContext()))
1375 return false; // Third operand of insertelement must be i32.
1376 return true;
1380 //===----------------------------------------------------------------------===//
1381 // ShuffleVectorInst Implementation
1382 //===----------------------------------------------------------------------===//
1384 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1385 const Twine &Name,
1386 Instruction *InsertBefore)
1387 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1388 cast<VectorType>(Mask->getType())->getNumElements()),
1389 ShuffleVector,
1390 OperandTraits<ShuffleVectorInst>::op_begin(this),
1391 OperandTraits<ShuffleVectorInst>::operands(this),
1392 InsertBefore) {
1393 assert(isValidOperands(V1, V2, Mask) &&
1394 "Invalid shuffle vector instruction operands!");
1395 Op<0>() = V1;
1396 Op<1>() = V2;
1397 Op<2>() = Mask;
1398 setName(Name);
1401 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1402 const Twine &Name,
1403 BasicBlock *InsertAtEnd)
1404 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1405 cast<VectorType>(Mask->getType())->getNumElements()),
1406 ShuffleVector,
1407 OperandTraits<ShuffleVectorInst>::op_begin(this),
1408 OperandTraits<ShuffleVectorInst>::operands(this),
1409 InsertAtEnd) {
1410 assert(isValidOperands(V1, V2, Mask) &&
1411 "Invalid shuffle vector instruction operands!");
1413 Op<0>() = V1;
1414 Op<1>() = V2;
1415 Op<2>() = Mask;
1416 setName(Name);
1419 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1420 const Value *Mask) {
1421 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1422 return false;
1424 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1425 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1426 MaskTy->getElementType() != Type::getInt32Ty(V1->getContext()))
1427 return false;
1428 return true;
1431 /// getMaskValue - Return the index from the shuffle mask for the specified
1432 /// output result. This is either -1 if the element is undef or a number less
1433 /// than 2*numelements.
1434 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1435 const Constant *Mask = cast<Constant>(getOperand(2));
1436 if (isa<UndefValue>(Mask)) return -1;
1437 if (isa<ConstantAggregateZero>(Mask)) return 0;
1438 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1439 assert(i < MaskCV->getNumOperands() && "Index out of range");
1441 if (isa<UndefValue>(MaskCV->getOperand(i)))
1442 return -1;
1443 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1446 //===----------------------------------------------------------------------===//
1447 // InsertValueInst Class
1448 //===----------------------------------------------------------------------===//
1450 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1451 unsigned NumIdx, const Twine &Name) {
1452 assert(NumOperands == 2 && "NumOperands not initialized?");
1453 Op<0>() = Agg;
1454 Op<1>() = Val;
1456 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1457 setName(Name);
1460 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1461 const Twine &Name) {
1462 assert(NumOperands == 2 && "NumOperands not initialized?");
1463 Op<0>() = Agg;
1464 Op<1>() = Val;
1466 Indices.push_back(Idx);
1467 setName(Name);
1470 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1471 : Instruction(IVI.getType(), InsertValue,
1472 OperandTraits<InsertValueInst>::op_begin(this), 2),
1473 Indices(IVI.Indices) {
1474 Op<0>() = IVI.getOperand(0);
1475 Op<1>() = IVI.getOperand(1);
1476 SubclassOptionalData = IVI.SubclassOptionalData;
1479 InsertValueInst::InsertValueInst(Value *Agg,
1480 Value *Val,
1481 unsigned Idx,
1482 const Twine &Name,
1483 Instruction *InsertBefore)
1484 : Instruction(Agg->getType(), InsertValue,
1485 OperandTraits<InsertValueInst>::op_begin(this),
1486 2, InsertBefore) {
1487 init(Agg, Val, Idx, Name);
1490 InsertValueInst::InsertValueInst(Value *Agg,
1491 Value *Val,
1492 unsigned Idx,
1493 const Twine &Name,
1494 BasicBlock *InsertAtEnd)
1495 : Instruction(Agg->getType(), InsertValue,
1496 OperandTraits<InsertValueInst>::op_begin(this),
1497 2, InsertAtEnd) {
1498 init(Agg, Val, Idx, Name);
1501 //===----------------------------------------------------------------------===//
1502 // ExtractValueInst Class
1503 //===----------------------------------------------------------------------===//
1505 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1506 const Twine &Name) {
1507 assert(NumOperands == 1 && "NumOperands not initialized?");
1509 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1510 setName(Name);
1513 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1514 assert(NumOperands == 1 && "NumOperands not initialized?");
1516 Indices.push_back(Idx);
1517 setName(Name);
1520 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1521 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1522 Indices(EVI.Indices) {
1523 SubclassOptionalData = EVI.SubclassOptionalData;
1526 // getIndexedType - Returns the type of the element that would be extracted
1527 // with an extractvalue instruction with the specified parameters.
1529 // A null type is returned if the indices are invalid for the specified
1530 // pointer type.
1532 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1533 const unsigned *Idxs,
1534 unsigned NumIdx) {
1535 unsigned CurIdx = 0;
1536 for (; CurIdx != NumIdx; ++CurIdx) {
1537 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1538 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1539 unsigned Index = Idxs[CurIdx];
1540 if (!CT->indexValid(Index)) return 0;
1541 Agg = CT->getTypeAtIndex(Index);
1543 // If the new type forwards to another type, then it is in the middle
1544 // of being refined to another type (and hence, may have dropped all
1545 // references to what it was using before). So, use the new forwarded
1546 // type.
1547 if (const Type *Ty = Agg->getForwardedType())
1548 Agg = Ty;
1550 return CurIdx == NumIdx ? Agg : 0;
1553 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1554 unsigned Idx) {
1555 return getIndexedType(Agg, &Idx, 1);
1558 //===----------------------------------------------------------------------===//
1559 // BinaryOperator Class
1560 //===----------------------------------------------------------------------===//
1562 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1563 /// type is floating-point, to help provide compatibility with an older API.
1565 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1566 const Type *Ty) {
1567 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1568 if (Ty->isFPOrFPVector()) {
1569 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1570 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1571 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1573 return iType;
1576 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1577 const Type *Ty, const Twine &Name,
1578 Instruction *InsertBefore)
1579 : Instruction(Ty, AdjustIType(iType, Ty),
1580 OperandTraits<BinaryOperator>::op_begin(this),
1581 OperandTraits<BinaryOperator>::operands(this),
1582 InsertBefore) {
1583 Op<0>() = S1;
1584 Op<1>() = S2;
1585 init(AdjustIType(iType, Ty));
1586 setName(Name);
1589 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1590 const Type *Ty, const Twine &Name,
1591 BasicBlock *InsertAtEnd)
1592 : Instruction(Ty, AdjustIType(iType, Ty),
1593 OperandTraits<BinaryOperator>::op_begin(this),
1594 OperandTraits<BinaryOperator>::operands(this),
1595 InsertAtEnd) {
1596 Op<0>() = S1;
1597 Op<1>() = S2;
1598 init(AdjustIType(iType, Ty));
1599 setName(Name);
1603 void BinaryOperator::init(BinaryOps iType) {
1604 Value *LHS = getOperand(0), *RHS = getOperand(1);
1605 LHS = LHS; RHS = RHS; // Silence warnings.
1606 assert(LHS->getType() == RHS->getType() &&
1607 "Binary operator operand types must match!");
1608 #ifndef NDEBUG
1609 switch (iType) {
1610 case Add: case Sub:
1611 case Mul:
1612 assert(getType() == LHS->getType() &&
1613 "Arithmetic operation should return same type as operands!");
1614 assert(getType()->isIntOrIntVector() &&
1615 "Tried to create an integer operation on a non-integer type!");
1616 break;
1617 case FAdd: case FSub:
1618 case FMul:
1619 assert(getType() == LHS->getType() &&
1620 "Arithmetic operation should return same type as operands!");
1621 assert(getType()->isFPOrFPVector() &&
1622 "Tried to create a floating-point operation on a "
1623 "non-floating-point type!");
1624 break;
1625 case UDiv:
1626 case SDiv:
1627 assert(getType() == LHS->getType() &&
1628 "Arithmetic operation should return same type as operands!");
1629 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1630 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1631 "Incorrect operand type (not integer) for S/UDIV");
1632 break;
1633 case FDiv:
1634 assert(getType() == LHS->getType() &&
1635 "Arithmetic operation should return same type as operands!");
1636 assert(getType()->isFPOrFPVector() &&
1637 "Incorrect operand type (not floating point) for FDIV");
1638 break;
1639 case URem:
1640 case SRem:
1641 assert(getType() == LHS->getType() &&
1642 "Arithmetic operation should return same type as operands!");
1643 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1644 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1645 "Incorrect operand type (not integer) for S/UREM");
1646 break;
1647 case FRem:
1648 assert(getType() == LHS->getType() &&
1649 "Arithmetic operation should return same type as operands!");
1650 assert(getType()->isFPOrFPVector() &&
1651 "Incorrect operand type (not floating point) for FREM");
1652 break;
1653 case Shl:
1654 case LShr:
1655 case AShr:
1656 assert(getType() == LHS->getType() &&
1657 "Shift operation should return same type as operands!");
1658 assert((getType()->isInteger() ||
1659 (isa<VectorType>(getType()) &&
1660 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1661 "Tried to create a shift operation on a non-integral type!");
1662 break;
1663 case And: case Or:
1664 case Xor:
1665 assert(getType() == LHS->getType() &&
1666 "Logical operation should return same type as operands!");
1667 assert((getType()->isInteger() ||
1668 (isa<VectorType>(getType()) &&
1669 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1670 "Tried to create a logical operation on a non-integral type!");
1671 break;
1672 default:
1673 break;
1675 #endif
1678 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1679 const Twine &Name,
1680 Instruction *InsertBefore) {
1681 assert(S1->getType() == S2->getType() &&
1682 "Cannot create binary operator with two operands of differing type!");
1683 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1686 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1687 const Twine &Name,
1688 BasicBlock *InsertAtEnd) {
1689 BinaryOperator *Res = Create(Op, S1, S2, Name);
1690 InsertAtEnd->getInstList().push_back(Res);
1691 return Res;
1694 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1695 Instruction *InsertBefore) {
1696 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1697 return new BinaryOperator(Instruction::Sub,
1698 zero, Op,
1699 Op->getType(), Name, InsertBefore);
1702 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1703 BasicBlock *InsertAtEnd) {
1704 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1705 return new BinaryOperator(Instruction::Sub,
1706 zero, Op,
1707 Op->getType(), Name, InsertAtEnd);
1710 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1711 Instruction *InsertBefore) {
1712 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1713 return new BinaryOperator(Instruction::FSub,
1714 zero, Op,
1715 Op->getType(), Name, InsertBefore);
1718 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1719 BasicBlock *InsertAtEnd) {
1720 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1721 return new BinaryOperator(Instruction::FSub,
1722 zero, Op,
1723 Op->getType(), Name, InsertAtEnd);
1726 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1727 Instruction *InsertBefore) {
1728 Constant *C;
1729 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1730 C = Constant::getAllOnesValue(PTy->getElementType());
1731 C = ConstantVector::get(
1732 std::vector<Constant*>(PTy->getNumElements(), C));
1733 } else {
1734 C = Constant::getAllOnesValue(Op->getType());
1737 return new BinaryOperator(Instruction::Xor, Op, C,
1738 Op->getType(), Name, InsertBefore);
1741 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1742 BasicBlock *InsertAtEnd) {
1743 Constant *AllOnes;
1744 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1745 // Create a vector of all ones values.
1746 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1747 AllOnes = ConstantVector::get(
1748 std::vector<Constant*>(PTy->getNumElements(), Elt));
1749 } else {
1750 AllOnes = Constant::getAllOnesValue(Op->getType());
1753 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1754 Op->getType(), Name, InsertAtEnd);
1758 // isConstantAllOnes - Helper function for several functions below
1759 static inline bool isConstantAllOnes(const Value *V) {
1760 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1761 return CI->isAllOnesValue();
1762 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1763 return CV->isAllOnesValue();
1764 return false;
1767 bool BinaryOperator::isNeg(const Value *V) {
1768 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1769 if (Bop->getOpcode() == Instruction::Sub)
1770 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1771 return C->isNegativeZeroValue();
1772 return false;
1775 bool BinaryOperator::isFNeg(const Value *V) {
1776 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1777 if (Bop->getOpcode() == Instruction::FSub)
1778 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1779 return C->isNegativeZeroValue();
1780 return false;
1783 bool BinaryOperator::isNot(const Value *V) {
1784 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1785 return (Bop->getOpcode() == Instruction::Xor &&
1786 (isConstantAllOnes(Bop->getOperand(1)) ||
1787 isConstantAllOnes(Bop->getOperand(0))));
1788 return false;
1791 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1792 return cast<BinaryOperator>(BinOp)->getOperand(1);
1795 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1796 return getNegArgument(const_cast<Value*>(BinOp));
1799 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1800 return cast<BinaryOperator>(BinOp)->getOperand(1);
1803 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1804 return getFNegArgument(const_cast<Value*>(BinOp));
1807 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1808 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1809 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1810 Value *Op0 = BO->getOperand(0);
1811 Value *Op1 = BO->getOperand(1);
1812 if (isConstantAllOnes(Op0)) return Op1;
1814 assert(isConstantAllOnes(Op1));
1815 return Op0;
1818 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1819 return getNotArgument(const_cast<Value*>(BinOp));
1823 // swapOperands - Exchange the two operands to this instruction. This
1824 // instruction is safe to use on any binary instruction and does not
1825 // modify the semantics of the instruction. If the instruction is
1826 // order dependent (SetLT f.e.) the opcode is changed.
1828 bool BinaryOperator::swapOperands() {
1829 if (!isCommutative())
1830 return true; // Can't commute operands
1831 Op<0>().swap(Op<1>());
1832 return false;
1835 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1836 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1839 void BinaryOperator::setHasNoSignedWrap(bool b) {
1840 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1843 void BinaryOperator::setIsExact(bool b) {
1844 cast<SDivOperator>(this)->setIsExact(b);
1847 //===----------------------------------------------------------------------===//
1848 // CastInst Class
1849 //===----------------------------------------------------------------------===//
1851 // Just determine if this cast only deals with integral->integral conversion.
1852 bool CastInst::isIntegerCast() const {
1853 switch (getOpcode()) {
1854 default: return false;
1855 case Instruction::ZExt:
1856 case Instruction::SExt:
1857 case Instruction::Trunc:
1858 return true;
1859 case Instruction::BitCast:
1860 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1864 bool CastInst::isLosslessCast() const {
1865 // Only BitCast can be lossless, exit fast if we're not BitCast
1866 if (getOpcode() != Instruction::BitCast)
1867 return false;
1869 // Identity cast is always lossless
1870 const Type* SrcTy = getOperand(0)->getType();
1871 const Type* DstTy = getType();
1872 if (SrcTy == DstTy)
1873 return true;
1875 // Pointer to pointer is always lossless.
1876 if (isa<PointerType>(SrcTy))
1877 return isa<PointerType>(DstTy);
1878 return false; // Other types have no identity values
1881 /// This function determines if the CastInst does not require any bits to be
1882 /// changed in order to effect the cast. Essentially, it identifies cases where
1883 /// no code gen is necessary for the cast, hence the name no-op cast. For
1884 /// example, the following are all no-op casts:
1885 /// # bitcast i32* %x to i8*
1886 /// # bitcast <2 x i32> %x to <4 x i16>
1887 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1888 /// @brief Determine if a cast is a no-op.
1889 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1890 switch (getOpcode()) {
1891 default:
1892 assert(!"Invalid CastOp");
1893 case Instruction::Trunc:
1894 case Instruction::ZExt:
1895 case Instruction::SExt:
1896 case Instruction::FPTrunc:
1897 case Instruction::FPExt:
1898 case Instruction::UIToFP:
1899 case Instruction::SIToFP:
1900 case Instruction::FPToUI:
1901 case Instruction::FPToSI:
1902 return false; // These always modify bits
1903 case Instruction::BitCast:
1904 return true; // BitCast never modifies bits.
1905 case Instruction::PtrToInt:
1906 return IntPtrTy->getScalarSizeInBits() ==
1907 getType()->getScalarSizeInBits();
1908 case Instruction::IntToPtr:
1909 return IntPtrTy->getScalarSizeInBits() ==
1910 getOperand(0)->getType()->getScalarSizeInBits();
1914 /// This function determines if a pair of casts can be eliminated and what
1915 /// opcode should be used in the elimination. This assumes that there are two
1916 /// instructions like this:
1917 /// * %F = firstOpcode SrcTy %x to MidTy
1918 /// * %S = secondOpcode MidTy %F to DstTy
1919 /// The function returns a resultOpcode so these two casts can be replaced with:
1920 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1921 /// If no such cast is permited, the function returns 0.
1922 unsigned CastInst::isEliminableCastPair(
1923 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1924 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1926 // Define the 144 possibilities for these two cast instructions. The values
1927 // in this matrix determine what to do in a given situation and select the
1928 // case in the switch below. The rows correspond to firstOp, the columns
1929 // correspond to secondOp. In looking at the table below, keep in mind
1930 // the following cast properties:
1932 // Size Compare Source Destination
1933 // Operator Src ? Size Type Sign Type Sign
1934 // -------- ------------ ------------------- ---------------------
1935 // TRUNC > Integer Any Integral Any
1936 // ZEXT < Integral Unsigned Integer Any
1937 // SEXT < Integral Signed Integer Any
1938 // FPTOUI n/a FloatPt n/a Integral Unsigned
1939 // FPTOSI n/a FloatPt n/a Integral Signed
1940 // UITOFP n/a Integral Unsigned FloatPt n/a
1941 // SITOFP n/a Integral Signed FloatPt n/a
1942 // FPTRUNC > FloatPt n/a FloatPt n/a
1943 // FPEXT < FloatPt n/a FloatPt n/a
1944 // PTRTOINT n/a Pointer n/a Integral Unsigned
1945 // INTTOPTR n/a Integral Unsigned Pointer n/a
1946 // BITCONVERT = FirstClass n/a FirstClass n/a
1948 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1949 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
1950 // into "fptoui double to i64", but this loses information about the range
1951 // of the produced value (we no longer know the top-part is all zeros).
1952 // Further this conversion is often much more expensive for typical hardware,
1953 // and causes issues when building libgcc. We disallow fptosi+sext for the
1954 // same reason.
1955 const unsigned numCastOps =
1956 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1957 static const uint8_t CastResults[numCastOps][numCastOps] = {
1958 // T F F U S F F P I B -+
1959 // R Z S P P I I T P 2 N T |
1960 // U E E 2 2 2 2 R E I T C +- secondOp
1961 // N X X U S F F N X N 2 V |
1962 // C T T I I P P C T T P T -+
1963 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1964 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1965 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1966 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1967 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1968 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1969 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1970 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1971 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1972 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1973 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1974 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1977 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1978 [secondOp-Instruction::CastOpsBegin];
1979 switch (ElimCase) {
1980 case 0:
1981 // categorically disallowed
1982 return 0;
1983 case 1:
1984 // allowed, use first cast's opcode
1985 return firstOp;
1986 case 2:
1987 // allowed, use second cast's opcode
1988 return secondOp;
1989 case 3:
1990 // no-op cast in second op implies firstOp as long as the DestTy
1991 // is integer
1992 if (DstTy->isInteger())
1993 return firstOp;
1994 return 0;
1995 case 4:
1996 // no-op cast in second op implies firstOp as long as the DestTy
1997 // is floating point
1998 if (DstTy->isFloatingPoint())
1999 return firstOp;
2000 return 0;
2001 case 5:
2002 // no-op cast in first op implies secondOp as long as the SrcTy
2003 // is an integer
2004 if (SrcTy->isInteger())
2005 return secondOp;
2006 return 0;
2007 case 6:
2008 // no-op cast in first op implies secondOp as long as the SrcTy
2009 // is a floating point
2010 if (SrcTy->isFloatingPoint())
2011 return secondOp;
2012 return 0;
2013 case 7: {
2014 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2015 if (!IntPtrTy)
2016 return 0;
2017 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2018 unsigned MidSize = MidTy->getScalarSizeInBits();
2019 if (MidSize >= PtrSize)
2020 return Instruction::BitCast;
2021 return 0;
2023 case 8: {
2024 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2025 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2026 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2027 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2028 unsigned DstSize = DstTy->getScalarSizeInBits();
2029 if (SrcSize == DstSize)
2030 return Instruction::BitCast;
2031 else if (SrcSize < DstSize)
2032 return firstOp;
2033 return secondOp;
2035 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2036 return Instruction::ZExt;
2037 case 10:
2038 // fpext followed by ftrunc is allowed if the bit size returned to is
2039 // the same as the original, in which case its just a bitcast
2040 if (SrcTy == DstTy)
2041 return Instruction::BitCast;
2042 return 0; // If the types are not the same we can't eliminate it.
2043 case 11:
2044 // bitcast followed by ptrtoint is allowed as long as the bitcast
2045 // is a pointer to pointer cast.
2046 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
2047 return secondOp;
2048 return 0;
2049 case 12:
2050 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2051 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
2052 return firstOp;
2053 return 0;
2054 case 13: {
2055 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2056 if (!IntPtrTy)
2057 return 0;
2058 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2059 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2060 unsigned DstSize = DstTy->getScalarSizeInBits();
2061 if (SrcSize <= PtrSize && SrcSize == DstSize)
2062 return Instruction::BitCast;
2063 return 0;
2065 case 99:
2066 // cast combination can't happen (error in input). This is for all cases
2067 // where the MidTy is not the same for the two cast instructions.
2068 assert(!"Invalid Cast Combination");
2069 return 0;
2070 default:
2071 assert(!"Error in CastResults table!!!");
2072 return 0;
2074 return 0;
2077 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2078 const Twine &Name, Instruction *InsertBefore) {
2079 // Construct and return the appropriate CastInst subclass
2080 switch (op) {
2081 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2082 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2083 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2084 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2085 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2086 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2087 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2088 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2089 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2090 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2091 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2092 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2093 default:
2094 assert(!"Invalid opcode provided");
2096 return 0;
2099 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2100 const Twine &Name, BasicBlock *InsertAtEnd) {
2101 // Construct and return the appropriate CastInst subclass
2102 switch (op) {
2103 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2104 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2105 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2106 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2107 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2108 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2109 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2110 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2111 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2112 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2113 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2114 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2115 default:
2116 assert(!"Invalid opcode provided");
2118 return 0;
2121 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2122 const Twine &Name,
2123 Instruction *InsertBefore) {
2124 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2125 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2126 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2129 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2130 const Twine &Name,
2131 BasicBlock *InsertAtEnd) {
2132 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2133 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2134 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2137 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2138 const Twine &Name,
2139 Instruction *InsertBefore) {
2140 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2141 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2142 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2145 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2146 const Twine &Name,
2147 BasicBlock *InsertAtEnd) {
2148 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2149 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2150 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2153 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2154 const Twine &Name,
2155 Instruction *InsertBefore) {
2156 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2157 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2158 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2161 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2162 const Twine &Name,
2163 BasicBlock *InsertAtEnd) {
2164 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2165 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2166 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2169 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2170 const Twine &Name,
2171 BasicBlock *InsertAtEnd) {
2172 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2173 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2174 "Invalid cast");
2176 if (Ty->isInteger())
2177 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2178 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2181 /// @brief Create a BitCast or a PtrToInt cast instruction
2182 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2183 const Twine &Name,
2184 Instruction *InsertBefore) {
2185 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2186 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2187 "Invalid cast");
2189 if (Ty->isInteger())
2190 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2191 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2194 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2195 bool isSigned, const Twine &Name,
2196 Instruction *InsertBefore) {
2197 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2198 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2199 unsigned DstBits = Ty->getScalarSizeInBits();
2200 Instruction::CastOps opcode =
2201 (SrcBits == DstBits ? Instruction::BitCast :
2202 (SrcBits > DstBits ? Instruction::Trunc :
2203 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2204 return Create(opcode, C, Ty, Name, InsertBefore);
2207 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2208 bool isSigned, const Twine &Name,
2209 BasicBlock *InsertAtEnd) {
2210 assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() &&
2211 "Invalid cast");
2212 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2213 unsigned DstBits = Ty->getScalarSizeInBits();
2214 Instruction::CastOps opcode =
2215 (SrcBits == DstBits ? Instruction::BitCast :
2216 (SrcBits > DstBits ? Instruction::Trunc :
2217 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2218 return Create(opcode, C, Ty, Name, InsertAtEnd);
2221 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2222 const Twine &Name,
2223 Instruction *InsertBefore) {
2224 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2225 "Invalid cast");
2226 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2227 unsigned DstBits = Ty->getScalarSizeInBits();
2228 Instruction::CastOps opcode =
2229 (SrcBits == DstBits ? Instruction::BitCast :
2230 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2231 return Create(opcode, C, Ty, Name, InsertBefore);
2234 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2235 const Twine &Name,
2236 BasicBlock *InsertAtEnd) {
2237 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2238 "Invalid cast");
2239 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2240 unsigned DstBits = Ty->getScalarSizeInBits();
2241 Instruction::CastOps opcode =
2242 (SrcBits == DstBits ? Instruction::BitCast :
2243 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2244 return Create(opcode, C, Ty, Name, InsertAtEnd);
2247 // Check whether it is valid to call getCastOpcode for these types.
2248 // This routine must be kept in sync with getCastOpcode.
2249 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2250 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2251 return false;
2253 if (SrcTy == DestTy)
2254 return true;
2256 // Get the bit sizes, we'll need these
2257 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2258 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2260 // Run through the possibilities ...
2261 if (DestTy->isInteger()) { // Casting to integral
2262 if (SrcTy->isInteger()) { // Casting from integral
2263 return true;
2264 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2265 return true;
2266 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2267 // Casting from vector
2268 return DestBits == PTy->getBitWidth();
2269 } else { // Casting from something else
2270 return isa<PointerType>(SrcTy);
2272 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2273 if (SrcTy->isInteger()) { // Casting from integral
2274 return true;
2275 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2276 return true;
2277 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2278 // Casting from vector
2279 return DestBits == PTy->getBitWidth();
2280 } else { // Casting from something else
2281 return false;
2283 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2284 // Casting to vector
2285 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2286 // Casting from vector
2287 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2288 } else { // Casting from something else
2289 return DestPTy->getBitWidth() == SrcBits;
2291 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2292 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2293 return true;
2294 } else if (SrcTy->isInteger()) { // Casting from integral
2295 return true;
2296 } else { // Casting from something else
2297 return false;
2299 } else { // Casting to something else
2300 return false;
2304 // Provide a way to get a "cast" where the cast opcode is inferred from the
2305 // types and size of the operand. This, basically, is a parallel of the
2306 // logic in the castIsValid function below. This axiom should hold:
2307 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2308 // should not assert in castIsValid. In other words, this produces a "correct"
2309 // casting opcode for the arguments passed to it.
2310 // This routine must be kept in sync with isCastable.
2311 Instruction::CastOps
2312 CastInst::getCastOpcode(
2313 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2314 // Get the bit sizes, we'll need these
2315 const Type *SrcTy = Src->getType();
2316 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2317 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2319 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2320 "Only first class types are castable!");
2322 // Run through the possibilities ...
2323 if (DestTy->isInteger()) { // Casting to integral
2324 if (SrcTy->isInteger()) { // Casting from integral
2325 if (DestBits < SrcBits)
2326 return Trunc; // int -> smaller int
2327 else if (DestBits > SrcBits) { // its an extension
2328 if (SrcIsSigned)
2329 return SExt; // signed -> SEXT
2330 else
2331 return ZExt; // unsigned -> ZEXT
2332 } else {
2333 return BitCast; // Same size, No-op cast
2335 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2336 if (DestIsSigned)
2337 return FPToSI; // FP -> sint
2338 else
2339 return FPToUI; // FP -> uint
2340 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2341 assert(DestBits == PTy->getBitWidth() &&
2342 "Casting vector to integer of different width");
2343 PTy = NULL;
2344 return BitCast; // Same size, no-op cast
2345 } else {
2346 assert(isa<PointerType>(SrcTy) &&
2347 "Casting from a value that is not first-class type");
2348 return PtrToInt; // ptr -> int
2350 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2351 if (SrcTy->isInteger()) { // Casting from integral
2352 if (SrcIsSigned)
2353 return SIToFP; // sint -> FP
2354 else
2355 return UIToFP; // uint -> FP
2356 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2357 if (DestBits < SrcBits) {
2358 return FPTrunc; // FP -> smaller FP
2359 } else if (DestBits > SrcBits) {
2360 return FPExt; // FP -> larger FP
2361 } else {
2362 return BitCast; // same size, no-op cast
2364 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2365 assert(DestBits == PTy->getBitWidth() &&
2366 "Casting vector to floating point of different width");
2367 PTy = NULL;
2368 return BitCast; // same size, no-op cast
2369 } else {
2370 llvm_unreachable("Casting pointer or non-first class to float");
2372 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2373 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2374 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2375 "Casting vector to vector of different widths");
2376 SrcPTy = NULL;
2377 return BitCast; // vector -> vector
2378 } else if (DestPTy->getBitWidth() == SrcBits) {
2379 return BitCast; // float/int -> vector
2380 } else {
2381 assert(!"Illegal cast to vector (wrong type or size)");
2383 } else if (isa<PointerType>(DestTy)) {
2384 if (isa<PointerType>(SrcTy)) {
2385 return BitCast; // ptr -> ptr
2386 } else if (SrcTy->isInteger()) {
2387 return IntToPtr; // int -> ptr
2388 } else {
2389 assert(!"Casting pointer to other than pointer or int");
2391 } else {
2392 assert(!"Casting to type that is not first-class");
2395 // If we fall through to here we probably hit an assertion cast above
2396 // and assertions are not turned on. Anything we return is an error, so
2397 // BitCast is as good a choice as any.
2398 return BitCast;
2401 //===----------------------------------------------------------------------===//
2402 // CastInst SubClass Constructors
2403 //===----------------------------------------------------------------------===//
2405 /// Check that the construction parameters for a CastInst are correct. This
2406 /// could be broken out into the separate constructors but it is useful to have
2407 /// it in one place and to eliminate the redundant code for getting the sizes
2408 /// of the types involved.
2409 bool
2410 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2412 // Check for type sanity on the arguments
2413 const Type *SrcTy = S->getType();
2414 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2415 return false;
2417 // Get the size of the types in bits, we'll need this later
2418 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2419 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2421 // Switch on the opcode provided
2422 switch (op) {
2423 default: return false; // This is an input error
2424 case Instruction::Trunc:
2425 return SrcTy->isIntOrIntVector() &&
2426 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2427 case Instruction::ZExt:
2428 return SrcTy->isIntOrIntVector() &&
2429 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2430 case Instruction::SExt:
2431 return SrcTy->isIntOrIntVector() &&
2432 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2433 case Instruction::FPTrunc:
2434 return SrcTy->isFPOrFPVector() &&
2435 DstTy->isFPOrFPVector() &&
2436 SrcBitSize > DstBitSize;
2437 case Instruction::FPExt:
2438 return SrcTy->isFPOrFPVector() &&
2439 DstTy->isFPOrFPVector() &&
2440 SrcBitSize < DstBitSize;
2441 case Instruction::UIToFP:
2442 case Instruction::SIToFP:
2443 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2444 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2445 return SVTy->getElementType()->isIntOrIntVector() &&
2446 DVTy->getElementType()->isFPOrFPVector() &&
2447 SVTy->getNumElements() == DVTy->getNumElements();
2450 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2451 case Instruction::FPToUI:
2452 case Instruction::FPToSI:
2453 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2454 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2455 return SVTy->getElementType()->isFPOrFPVector() &&
2456 DVTy->getElementType()->isIntOrIntVector() &&
2457 SVTy->getNumElements() == DVTy->getNumElements();
2460 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2461 case Instruction::PtrToInt:
2462 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2463 case Instruction::IntToPtr:
2464 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2465 case Instruction::BitCast:
2466 // BitCast implies a no-op cast of type only. No bits change.
2467 // However, you can't cast pointers to anything but pointers.
2468 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2469 return false;
2471 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2472 // these cases, the cast is okay if the source and destination bit widths
2473 // are identical.
2474 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2478 TruncInst::TruncInst(
2479 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2480 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2481 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2484 TruncInst::TruncInst(
2485 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2486 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2487 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2490 ZExtInst::ZExtInst(
2491 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2492 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2493 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2496 ZExtInst::ZExtInst(
2497 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2498 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2499 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2501 SExtInst::SExtInst(
2502 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2503 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2504 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2507 SExtInst::SExtInst(
2508 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2509 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2510 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2513 FPTruncInst::FPTruncInst(
2514 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2515 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2516 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2519 FPTruncInst::FPTruncInst(
2520 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2521 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2522 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2525 FPExtInst::FPExtInst(
2526 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2527 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2528 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2531 FPExtInst::FPExtInst(
2532 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2533 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2534 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2537 UIToFPInst::UIToFPInst(
2538 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2539 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2540 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2543 UIToFPInst::UIToFPInst(
2544 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2545 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2546 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2549 SIToFPInst::SIToFPInst(
2550 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2551 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2552 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2555 SIToFPInst::SIToFPInst(
2556 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2557 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2558 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2561 FPToUIInst::FPToUIInst(
2562 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2563 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2564 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2567 FPToUIInst::FPToUIInst(
2568 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2569 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2570 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2573 FPToSIInst::FPToSIInst(
2574 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2575 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2576 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2579 FPToSIInst::FPToSIInst(
2580 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2581 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2582 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2585 PtrToIntInst::PtrToIntInst(
2586 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2587 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2588 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2591 PtrToIntInst::PtrToIntInst(
2592 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2593 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2594 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2597 IntToPtrInst::IntToPtrInst(
2598 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2599 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2600 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2603 IntToPtrInst::IntToPtrInst(
2604 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2605 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2606 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2609 BitCastInst::BitCastInst(
2610 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2611 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2612 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2615 BitCastInst::BitCastInst(
2616 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2617 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2618 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2621 //===----------------------------------------------------------------------===//
2622 // CmpInst Classes
2623 //===----------------------------------------------------------------------===//
2625 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2626 Value *LHS, Value *RHS, const Twine &Name,
2627 Instruction *InsertBefore)
2628 : Instruction(ty, op,
2629 OperandTraits<CmpInst>::op_begin(this),
2630 OperandTraits<CmpInst>::operands(this),
2631 InsertBefore) {
2632 Op<0>() = LHS;
2633 Op<1>() = RHS;
2634 SubclassData = predicate;
2635 setName(Name);
2638 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2639 Value *LHS, Value *RHS, const Twine &Name,
2640 BasicBlock *InsertAtEnd)
2641 : Instruction(ty, op,
2642 OperandTraits<CmpInst>::op_begin(this),
2643 OperandTraits<CmpInst>::operands(this),
2644 InsertAtEnd) {
2645 Op<0>() = LHS;
2646 Op<1>() = RHS;
2647 SubclassData = predicate;
2648 setName(Name);
2651 CmpInst *
2652 CmpInst::Create(OtherOps Op, unsigned short predicate,
2653 Value *S1, Value *S2,
2654 const Twine &Name, Instruction *InsertBefore) {
2655 if (Op == Instruction::ICmp) {
2656 if (InsertBefore)
2657 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2658 S1, S2, Name);
2659 else
2660 return new ICmpInst(CmpInst::Predicate(predicate),
2661 S1, S2, Name);
2664 if (InsertBefore)
2665 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2666 S1, S2, Name);
2667 else
2668 return new FCmpInst(CmpInst::Predicate(predicate),
2669 S1, S2, Name);
2672 CmpInst *
2673 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2674 const Twine &Name, BasicBlock *InsertAtEnd) {
2675 if (Op == Instruction::ICmp) {
2676 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2677 S1, S2, Name);
2679 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2680 S1, S2, Name);
2683 void CmpInst::swapOperands() {
2684 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2685 IC->swapOperands();
2686 else
2687 cast<FCmpInst>(this)->swapOperands();
2690 bool CmpInst::isCommutative() {
2691 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2692 return IC->isCommutative();
2693 return cast<FCmpInst>(this)->isCommutative();
2696 bool CmpInst::isEquality() {
2697 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2698 return IC->isEquality();
2699 return cast<FCmpInst>(this)->isEquality();
2703 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2704 switch (pred) {
2705 default: assert(!"Unknown cmp predicate!");
2706 case ICMP_EQ: return ICMP_NE;
2707 case ICMP_NE: return ICMP_EQ;
2708 case ICMP_UGT: return ICMP_ULE;
2709 case ICMP_ULT: return ICMP_UGE;
2710 case ICMP_UGE: return ICMP_ULT;
2711 case ICMP_ULE: return ICMP_UGT;
2712 case ICMP_SGT: return ICMP_SLE;
2713 case ICMP_SLT: return ICMP_SGE;
2714 case ICMP_SGE: return ICMP_SLT;
2715 case ICMP_SLE: return ICMP_SGT;
2717 case FCMP_OEQ: return FCMP_UNE;
2718 case FCMP_ONE: return FCMP_UEQ;
2719 case FCMP_OGT: return FCMP_ULE;
2720 case FCMP_OLT: return FCMP_UGE;
2721 case FCMP_OGE: return FCMP_ULT;
2722 case FCMP_OLE: return FCMP_UGT;
2723 case FCMP_UEQ: return FCMP_ONE;
2724 case FCMP_UNE: return FCMP_OEQ;
2725 case FCMP_UGT: return FCMP_OLE;
2726 case FCMP_ULT: return FCMP_OGE;
2727 case FCMP_UGE: return FCMP_OLT;
2728 case FCMP_ULE: return FCMP_OGT;
2729 case FCMP_ORD: return FCMP_UNO;
2730 case FCMP_UNO: return FCMP_ORD;
2731 case FCMP_TRUE: return FCMP_FALSE;
2732 case FCMP_FALSE: return FCMP_TRUE;
2736 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2737 switch (pred) {
2738 default: assert(! "Unknown icmp predicate!");
2739 case ICMP_EQ: case ICMP_NE:
2740 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2741 return pred;
2742 case ICMP_UGT: return ICMP_SGT;
2743 case ICMP_ULT: return ICMP_SLT;
2744 case ICMP_UGE: return ICMP_SGE;
2745 case ICMP_ULE: return ICMP_SLE;
2749 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2750 switch (pred) {
2751 default: assert(! "Unknown icmp predicate!");
2752 case ICMP_EQ: case ICMP_NE:
2753 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2754 return pred;
2755 case ICMP_SGT: return ICMP_UGT;
2756 case ICMP_SLT: return ICMP_ULT;
2757 case ICMP_SGE: return ICMP_UGE;
2758 case ICMP_SLE: return ICMP_ULE;
2762 bool ICmpInst::isSignedPredicate(Predicate pred) {
2763 switch (pred) {
2764 default: assert(! "Unknown icmp predicate!");
2765 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2766 return true;
2767 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2768 case ICMP_UGE: case ICMP_ULE:
2769 return false;
2773 /// Initialize a set of values that all satisfy the condition with C.
2775 ConstantRange
2776 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2777 APInt Lower(C);
2778 APInt Upper(C);
2779 uint32_t BitWidth = C.getBitWidth();
2780 switch (pred) {
2781 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2782 case ICmpInst::ICMP_EQ: Upper++; break;
2783 case ICmpInst::ICMP_NE: Lower++; break;
2784 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2785 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2786 case ICmpInst::ICMP_UGT:
2787 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2788 break;
2789 case ICmpInst::ICMP_SGT:
2790 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2791 break;
2792 case ICmpInst::ICMP_ULE:
2793 Lower = APInt::getMinValue(BitWidth); Upper++;
2794 break;
2795 case ICmpInst::ICMP_SLE:
2796 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2797 break;
2798 case ICmpInst::ICMP_UGE:
2799 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2800 break;
2801 case ICmpInst::ICMP_SGE:
2802 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2803 break;
2805 return ConstantRange(Lower, Upper);
2808 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2809 switch (pred) {
2810 default: assert(!"Unknown cmp predicate!");
2811 case ICMP_EQ: case ICMP_NE:
2812 return pred;
2813 case ICMP_SGT: return ICMP_SLT;
2814 case ICMP_SLT: return ICMP_SGT;
2815 case ICMP_SGE: return ICMP_SLE;
2816 case ICMP_SLE: return ICMP_SGE;
2817 case ICMP_UGT: return ICMP_ULT;
2818 case ICMP_ULT: return ICMP_UGT;
2819 case ICMP_UGE: return ICMP_ULE;
2820 case ICMP_ULE: return ICMP_UGE;
2822 case FCMP_FALSE: case FCMP_TRUE:
2823 case FCMP_OEQ: case FCMP_ONE:
2824 case FCMP_UEQ: case FCMP_UNE:
2825 case FCMP_ORD: case FCMP_UNO:
2826 return pred;
2827 case FCMP_OGT: return FCMP_OLT;
2828 case FCMP_OLT: return FCMP_OGT;
2829 case FCMP_OGE: return FCMP_OLE;
2830 case FCMP_OLE: return FCMP_OGE;
2831 case FCMP_UGT: return FCMP_ULT;
2832 case FCMP_ULT: return FCMP_UGT;
2833 case FCMP_UGE: return FCMP_ULE;
2834 case FCMP_ULE: return FCMP_UGE;
2838 bool CmpInst::isUnsigned(unsigned short predicate) {
2839 switch (predicate) {
2840 default: return false;
2841 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2842 case ICmpInst::ICMP_UGE: return true;
2846 bool CmpInst::isSigned(unsigned short predicate){
2847 switch (predicate) {
2848 default: return false;
2849 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2850 case ICmpInst::ICMP_SGE: return true;
2854 bool CmpInst::isOrdered(unsigned short predicate) {
2855 switch (predicate) {
2856 default: return false;
2857 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2858 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2859 case FCmpInst::FCMP_ORD: return true;
2863 bool CmpInst::isUnordered(unsigned short predicate) {
2864 switch (predicate) {
2865 default: return false;
2866 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2867 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2868 case FCmpInst::FCMP_UNO: return true;
2872 //===----------------------------------------------------------------------===//
2873 // SwitchInst Implementation
2874 //===----------------------------------------------------------------------===//
2876 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2877 assert(Value && Default);
2878 ReservedSpace = 2+NumCases*2;
2879 NumOperands = 2;
2880 OperandList = allocHungoffUses(ReservedSpace);
2882 OperandList[0] = Value;
2883 OperandList[1] = Default;
2886 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2887 /// switch on and a default destination. The number of additional cases can
2888 /// be specified here to make memory allocation more efficient. This
2889 /// constructor can also autoinsert before another instruction.
2890 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2891 Instruction *InsertBefore)
2892 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2893 0, 0, InsertBefore) {
2894 init(Value, Default, NumCases);
2897 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2898 /// switch on and a default destination. The number of additional cases can
2899 /// be specified here to make memory allocation more efficient. This
2900 /// constructor also autoinserts at the end of the specified BasicBlock.
2901 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2902 BasicBlock *InsertAtEnd)
2903 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2904 0, 0, InsertAtEnd) {
2905 init(Value, Default, NumCases);
2908 SwitchInst::SwitchInst(const SwitchInst &SI)
2909 : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch,
2910 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2911 Use *OL = OperandList, *InOL = SI.OperandList;
2912 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2913 OL[i] = InOL[i];
2914 OL[i+1] = InOL[i+1];
2916 SubclassOptionalData = SI.SubclassOptionalData;
2919 SwitchInst::~SwitchInst() {
2920 dropHungoffUses(OperandList);
2924 /// addCase - Add an entry to the switch instruction...
2926 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2927 unsigned OpNo = NumOperands;
2928 if (OpNo+2 > ReservedSpace)
2929 resizeOperands(0); // Get more space!
2930 // Initialize some new operands.
2931 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2932 NumOperands = OpNo+2;
2933 OperandList[OpNo] = OnVal;
2934 OperandList[OpNo+1] = Dest;
2937 /// removeCase - This method removes the specified successor from the switch
2938 /// instruction. Note that this cannot be used to remove the default
2939 /// destination (successor #0).
2941 void SwitchInst::removeCase(unsigned idx) {
2942 assert(idx != 0 && "Cannot remove the default case!");
2943 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2945 unsigned NumOps = getNumOperands();
2946 Use *OL = OperandList;
2948 // Move everything after this operand down.
2950 // FIXME: we could just swap with the end of the list, then erase. However,
2951 // client might not expect this to happen. The code as it is thrashes the
2952 // use/def lists, which is kinda lame.
2953 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2954 OL[i-2] = OL[i];
2955 OL[i-2+1] = OL[i+1];
2958 // Nuke the last value.
2959 OL[NumOps-2].set(0);
2960 OL[NumOps-2+1].set(0);
2961 NumOperands = NumOps-2;
2964 /// resizeOperands - resize operands - This adjusts the length of the operands
2965 /// list according to the following behavior:
2966 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2967 /// of operation. This grows the number of ops by 3 times.
2968 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2969 /// 3. If NumOps == NumOperands, trim the reserved space.
2971 void SwitchInst::resizeOperands(unsigned NumOps) {
2972 unsigned e = getNumOperands();
2973 if (NumOps == 0) {
2974 NumOps = e*3;
2975 } else if (NumOps*2 > NumOperands) {
2976 // No resize needed.
2977 if (ReservedSpace >= NumOps) return;
2978 } else if (NumOps == NumOperands) {
2979 if (ReservedSpace == NumOps) return;
2980 } else {
2981 return;
2984 ReservedSpace = NumOps;
2985 Use *NewOps = allocHungoffUses(NumOps);
2986 Use *OldOps = OperandList;
2987 for (unsigned i = 0; i != e; ++i) {
2988 NewOps[i] = OldOps[i];
2990 OperandList = NewOps;
2991 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2995 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2996 return getSuccessor(idx);
2998 unsigned SwitchInst::getNumSuccessorsV() const {
2999 return getNumSuccessors();
3001 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3002 setSuccessor(idx, B);
3005 // Define these methods here so vtables don't get emitted into every translation
3006 // unit that uses these classes.
3008 GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const {
3009 GetElementPtrInst *New = new(getNumOperands()) GetElementPtrInst(*this);
3010 New->SubclassOptionalData = SubclassOptionalData;
3011 return New;
3014 BinaryOperator *BinaryOperator::clone(LLVMContext&) const {
3015 BinaryOperator *New = Create(getOpcode(), Op<0>(), Op<1>());
3016 New->SubclassOptionalData = SubclassOptionalData;
3017 return New;
3020 FCmpInst* FCmpInst::clone(LLVMContext &Context) const {
3021 FCmpInst *New = new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3022 New->SubclassOptionalData = SubclassOptionalData;
3023 return New;
3025 ICmpInst* ICmpInst::clone(LLVMContext &Context) const {
3026 ICmpInst *New = new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3027 New->SubclassOptionalData = SubclassOptionalData;
3028 return New;
3031 ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const {
3032 ExtractValueInst *New = new ExtractValueInst(*this);
3033 New->SubclassOptionalData = SubclassOptionalData;
3034 return New;
3036 InsertValueInst *InsertValueInst::clone(LLVMContext&) const {
3037 InsertValueInst *New = new InsertValueInst(*this);
3038 New->SubclassOptionalData = SubclassOptionalData;
3039 return New;
3042 MallocInst *MallocInst::clone(LLVMContext&) const {
3043 MallocInst *New = new MallocInst(getAllocatedType(),
3044 (Value*)getOperand(0),
3045 getAlignment());
3046 New->SubclassOptionalData = SubclassOptionalData;
3047 return New;
3050 AllocaInst *AllocaInst::clone(LLVMContext&) const {
3051 AllocaInst *New = new AllocaInst(getAllocatedType(),
3052 (Value*)getOperand(0),
3053 getAlignment());
3054 New->SubclassOptionalData = SubclassOptionalData;
3055 return New;
3058 FreeInst *FreeInst::clone(LLVMContext&) const {
3059 FreeInst *New = new FreeInst(getOperand(0));
3060 New->SubclassOptionalData = SubclassOptionalData;
3061 return New;
3064 LoadInst *LoadInst::clone(LLVMContext&) const {
3065 LoadInst *New = new LoadInst(getOperand(0),
3066 Twine(), isVolatile(),
3067 getAlignment());
3068 New->SubclassOptionalData = SubclassOptionalData;
3069 return New;
3072 StoreInst *StoreInst::clone(LLVMContext&) const {
3073 StoreInst *New = new StoreInst(getOperand(0), getOperand(1),
3074 isVolatile(), getAlignment());
3075 New->SubclassOptionalData = SubclassOptionalData;
3076 return New;
3079 TruncInst *TruncInst::clone(LLVMContext&) const {
3080 TruncInst *New = new TruncInst(getOperand(0), getType());
3081 New->SubclassOptionalData = SubclassOptionalData;
3082 return New;
3085 ZExtInst *ZExtInst::clone(LLVMContext&) const {
3086 ZExtInst *New = new ZExtInst(getOperand(0), getType());
3087 New->SubclassOptionalData = SubclassOptionalData;
3088 return New;
3091 SExtInst *SExtInst::clone(LLVMContext&) const {
3092 SExtInst *New = new SExtInst(getOperand(0), getType());
3093 New->SubclassOptionalData = SubclassOptionalData;
3094 return New;
3097 FPTruncInst *FPTruncInst::clone(LLVMContext&) const {
3098 FPTruncInst *New = new FPTruncInst(getOperand(0), getType());
3099 New->SubclassOptionalData = SubclassOptionalData;
3100 return New;
3103 FPExtInst *FPExtInst::clone(LLVMContext&) const {
3104 FPExtInst *New = new FPExtInst(getOperand(0), getType());
3105 New->SubclassOptionalData = SubclassOptionalData;
3106 return New;
3109 UIToFPInst *UIToFPInst::clone(LLVMContext&) const {
3110 UIToFPInst *New = new UIToFPInst(getOperand(0), getType());
3111 New->SubclassOptionalData = SubclassOptionalData;
3112 return New;
3115 SIToFPInst *SIToFPInst::clone(LLVMContext&) const {
3116 SIToFPInst *New = new SIToFPInst(getOperand(0), getType());
3117 New->SubclassOptionalData = SubclassOptionalData;
3118 return New;
3121 FPToUIInst *FPToUIInst::clone(LLVMContext&) const {
3122 FPToUIInst *New = new FPToUIInst(getOperand(0), getType());
3123 New->SubclassOptionalData = SubclassOptionalData;
3124 return New;
3127 FPToSIInst *FPToSIInst::clone(LLVMContext&) const {
3128 FPToSIInst *New = new FPToSIInst(getOperand(0), getType());
3129 New->SubclassOptionalData = SubclassOptionalData;
3130 return New;
3133 PtrToIntInst *PtrToIntInst::clone(LLVMContext&) const {
3134 PtrToIntInst *New = new PtrToIntInst(getOperand(0), getType());
3135 New->SubclassOptionalData = SubclassOptionalData;
3136 return New;
3139 IntToPtrInst *IntToPtrInst::clone(LLVMContext&) const {
3140 IntToPtrInst *New = new IntToPtrInst(getOperand(0), getType());
3141 New->SubclassOptionalData = SubclassOptionalData;
3142 return New;
3145 BitCastInst *BitCastInst::clone(LLVMContext&) const {
3146 BitCastInst *New = new BitCastInst(getOperand(0), getType());
3147 New->SubclassOptionalData = SubclassOptionalData;
3148 return New;
3151 CallInst *CallInst::clone(LLVMContext&) const {
3152 CallInst *New = new(getNumOperands()) CallInst(*this);
3153 New->SubclassOptionalData = SubclassOptionalData;
3154 return New;
3157 SelectInst *SelectInst::clone(LLVMContext&) const {
3158 SelectInst *New = SelectInst::Create(getOperand(0),
3159 getOperand(1),
3160 getOperand(2));
3161 New->SubclassOptionalData = SubclassOptionalData;
3162 return New;
3165 VAArgInst *VAArgInst::clone(LLVMContext&) const {
3166 VAArgInst *New = new VAArgInst(getOperand(0), getType());
3167 New->SubclassOptionalData = SubclassOptionalData;
3168 return New;
3171 ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const {
3172 ExtractElementInst *New = ExtractElementInst::Create(getOperand(0),
3173 getOperand(1));
3174 New->SubclassOptionalData = SubclassOptionalData;
3175 return New;
3178 InsertElementInst *InsertElementInst::clone(LLVMContext&) const {
3179 InsertElementInst *New = InsertElementInst::Create(getOperand(0),
3180 getOperand(1),
3181 getOperand(2));
3182 New->SubclassOptionalData = SubclassOptionalData;
3183 return New;
3186 ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const {
3187 ShuffleVectorInst *New = new ShuffleVectorInst(getOperand(0),
3188 getOperand(1),
3189 getOperand(2));
3190 New->SubclassOptionalData = SubclassOptionalData;
3191 return New;
3194 PHINode *PHINode::clone(LLVMContext&) const {
3195 PHINode *New = new PHINode(*this);
3196 New->SubclassOptionalData = SubclassOptionalData;
3197 return New;
3200 ReturnInst *ReturnInst::clone(LLVMContext&) const {
3201 ReturnInst *New = new(getNumOperands()) ReturnInst(*this);
3202 New->SubclassOptionalData = SubclassOptionalData;
3203 return New;
3206 BranchInst *BranchInst::clone(LLVMContext&) const {
3207 unsigned Ops(getNumOperands());
3208 BranchInst *New = new(Ops, Ops == 1) BranchInst(*this);
3209 New->SubclassOptionalData = SubclassOptionalData;
3210 return New;
3213 SwitchInst *SwitchInst::clone(LLVMContext&) const {
3214 SwitchInst *New = new SwitchInst(*this);
3215 New->SubclassOptionalData = SubclassOptionalData;
3216 return New;
3219 InvokeInst *InvokeInst::clone(LLVMContext&) const {
3220 InvokeInst *New = new(getNumOperands()) InvokeInst(*this);
3221 New->SubclassOptionalData = SubclassOptionalData;
3222 return New;
3225 UnwindInst *UnwindInst::clone(LLVMContext &C) const {
3226 UnwindInst *New = new UnwindInst(C);
3227 New->SubclassOptionalData = SubclassOptionalData;
3228 return New;
3231 UnreachableInst *UnreachableInst::clone(LLVMContext &C) const {
3232 UnreachableInst *New = new UnreachableInst(C);
3233 New->SubclassOptionalData = SubclassOptionalData;
3234 return New;