There is only one register coalescer. Merge it into the base class and
[llvm/stm8.git] / lib / VMCore / Instructions.cpp
blob0eddd5ada7ae9c71e39efb70ef090d25bb699c04
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 "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/MathExtras.h"
26 using namespace llvm;
28 //===----------------------------------------------------------------------===//
29 // CallSite Class
30 //===----------------------------------------------------------------------===//
32 User::op_iterator CallSite::getCallee() const {
33 Instruction *II(getInstruction());
34 return isCall()
35 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
36 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
39 //===----------------------------------------------------------------------===//
40 // TerminatorInst Class
41 //===----------------------------------------------------------------------===//
43 // Out of line virtual method, so the vtable, etc has a home.
44 TerminatorInst::~TerminatorInst() {
47 //===----------------------------------------------------------------------===//
48 // UnaryInstruction Class
49 //===----------------------------------------------------------------------===//
51 // Out of line virtual method, so the vtable, etc has a home.
52 UnaryInstruction::~UnaryInstruction() {
55 //===----------------------------------------------------------------------===//
56 // SelectInst Class
57 //===----------------------------------------------------------------------===//
59 /// areInvalidOperands - Return a string if the specified operands are invalid
60 /// for a select operation, otherwise return null.
61 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
62 if (Op1->getType() != Op2->getType())
63 return "both values to select must have same type";
65 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
66 // Vector select.
67 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
68 return "vector select condition element type must be i1";
69 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
70 if (ET == 0)
71 return "selected values for vector select must be vectors";
72 if (ET->getNumElements() != VT->getNumElements())
73 return "vector select requires selected vectors to have "
74 "the same vector length as select condition";
75 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
76 return "select condition must be i1 or <n x i1>";
78 return 0;
82 //===----------------------------------------------------------------------===//
83 // PHINode Class
84 //===----------------------------------------------------------------------===//
86 PHINode::PHINode(const PHINode &PN)
87 : Instruction(PN.getType(), Instruction::PHI,
88 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
89 ReservedSpace(PN.getNumOperands()) {
90 std::copy(PN.op_begin(), PN.op_end(), op_begin());
91 std::copy(PN.block_begin(), PN.block_end(), block_begin());
92 SubclassOptionalData = PN.SubclassOptionalData;
95 PHINode::~PHINode() {
96 dropHungoffUses();
99 Use *PHINode::allocHungoffUses(unsigned N) const {
100 // Allocate the array of Uses of the incoming values, followed by a pointer
101 // (with bottom bit set) to the User, followed by the array of pointers to
102 // the incoming basic blocks.
103 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
104 + N * sizeof(BasicBlock*);
105 Use *Begin = static_cast<Use*>(::operator new(size));
106 Use *End = Begin + N;
107 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
108 return Use::initTags(Begin, End);
111 // removeIncomingValue - Remove an incoming value. This is useful if a
112 // predecessor basic block is deleted.
113 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
114 Value *Removed = getIncomingValue(Idx);
116 // Move everything after this operand down.
118 // FIXME: we could just swap with the end of the list, then erase. However,
119 // clients might not expect this to happen. The code as it is thrashes the
120 // use/def lists, which is kinda lame.
121 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
122 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
124 // Nuke the last value.
125 Op<-1>().set(0);
126 --NumOperands;
128 // If the PHI node is dead, because it has zero entries, nuke it now.
129 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
130 // If anyone is using this PHI, make them use a dummy value instead...
131 replaceAllUsesWith(UndefValue::get(getType()));
132 eraseFromParent();
134 return Removed;
137 /// growOperands - grow operands - This grows the operand list in response
138 /// to a push_back style of operation. This grows the number of ops by 1.5
139 /// times.
141 void PHINode::growOperands() {
142 unsigned e = getNumOperands();
143 unsigned NumOps = e + e / 2;
144 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
146 Use *OldOps = op_begin();
147 BasicBlock **OldBlocks = block_begin();
149 ReservedSpace = NumOps;
150 OperandList = allocHungoffUses(ReservedSpace);
152 std::copy(OldOps, OldOps + e, op_begin());
153 std::copy(OldBlocks, OldBlocks + e, block_begin());
155 Use::zap(OldOps, OldOps + e, true);
158 /// hasConstantValue - If the specified PHI node always merges together the same
159 /// value, return the value, otherwise return null.
160 Value *PHINode::hasConstantValue() const {
161 // Exploit the fact that phi nodes always have at least one entry.
162 Value *ConstantValue = getIncomingValue(0);
163 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
164 if (getIncomingValue(i) != ConstantValue)
165 return 0; // Incoming values not all the same.
166 return ConstantValue;
170 //===----------------------------------------------------------------------===//
171 // CallInst Implementation
172 //===----------------------------------------------------------------------===//
174 CallInst::~CallInst() {
177 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
178 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
179 Op<-1>() = Func;
181 const FunctionType *FTy =
182 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
183 (void)FTy; // silence warning.
185 assert((NumParams == FTy->getNumParams() ||
186 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
187 "Calling a function with bad signature!");
188 for (unsigned i = 0; i != NumParams; ++i) {
189 assert((i >= FTy->getNumParams() ||
190 FTy->getParamType(i) == Params[i]->getType()) &&
191 "Calling a function with a bad signature!");
192 OperandList[i] = Params[i];
196 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
197 assert(NumOperands == 3 && "NumOperands not set up?");
198 Op<-1>() = Func;
199 Op<0>() = Actual1;
200 Op<1>() = Actual2;
202 const FunctionType *FTy =
203 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
204 (void)FTy; // silence warning.
206 assert((FTy->getNumParams() == 2 ||
207 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
208 "Calling a function with bad signature");
209 assert((0 >= FTy->getNumParams() ||
210 FTy->getParamType(0) == Actual1->getType()) &&
211 "Calling a function with a bad signature!");
212 assert((1 >= FTy->getNumParams() ||
213 FTy->getParamType(1) == Actual2->getType()) &&
214 "Calling a function with a bad signature!");
217 void CallInst::init(Value *Func, Value *Actual) {
218 assert(NumOperands == 2 && "NumOperands not set up?");
219 Op<-1>() = Func;
220 Op<0>() = Actual;
222 const FunctionType *FTy =
223 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
224 (void)FTy; // silence warning.
226 assert((FTy->getNumParams() == 1 ||
227 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
228 "Calling a function with bad signature");
229 assert((0 == FTy->getNumParams() ||
230 FTy->getParamType(0) == Actual->getType()) &&
231 "Calling a function with a bad signature!");
234 void CallInst::init(Value *Func) {
235 assert(NumOperands == 1 && "NumOperands not set up?");
236 Op<-1>() = Func;
238 const FunctionType *FTy =
239 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
240 (void)FTy; // silence warning.
242 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
245 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
246 Instruction *InsertBefore)
247 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
248 ->getElementType())->getReturnType(),
249 Instruction::Call,
250 OperandTraits<CallInst>::op_end(this) - 2,
251 2, InsertBefore) {
252 init(Func, Actual);
253 setName(Name);
256 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
257 BasicBlock *InsertAtEnd)
258 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
259 ->getElementType())->getReturnType(),
260 Instruction::Call,
261 OperandTraits<CallInst>::op_end(this) - 2,
262 2, InsertAtEnd) {
263 init(Func, Actual);
264 setName(Name);
266 CallInst::CallInst(Value *Func, const Twine &Name,
267 Instruction *InsertBefore)
268 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
269 ->getElementType())->getReturnType(),
270 Instruction::Call,
271 OperandTraits<CallInst>::op_end(this) - 1,
272 1, InsertBefore) {
273 init(Func);
274 setName(Name);
277 CallInst::CallInst(Value *Func, const Twine &Name,
278 BasicBlock *InsertAtEnd)
279 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
280 ->getElementType())->getReturnType(),
281 Instruction::Call,
282 OperandTraits<CallInst>::op_end(this) - 1,
283 1, InsertAtEnd) {
284 init(Func);
285 setName(Name);
288 CallInst::CallInst(const CallInst &CI)
289 : Instruction(CI.getType(), Instruction::Call,
290 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
291 CI.getNumOperands()) {
292 setAttributes(CI.getAttributes());
293 setTailCall(CI.isTailCall());
294 setCallingConv(CI.getCallingConv());
296 Use *OL = OperandList;
297 Use *InOL = CI.OperandList;
298 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
299 OL[i] = InOL[i];
300 SubclassOptionalData = CI.SubclassOptionalData;
303 void CallInst::addAttribute(unsigned i, Attributes attr) {
304 AttrListPtr PAL = getAttributes();
305 PAL = PAL.addAttr(i, attr);
306 setAttributes(PAL);
309 void CallInst::removeAttribute(unsigned i, Attributes attr) {
310 AttrListPtr PAL = getAttributes();
311 PAL = PAL.removeAttr(i, attr);
312 setAttributes(PAL);
315 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
316 if (AttributeList.paramHasAttr(i, attr))
317 return true;
318 if (const Function *F = getCalledFunction())
319 return F->paramHasAttr(i, attr);
320 return false;
323 /// IsConstantOne - Return true only if val is constant int 1
324 static bool IsConstantOne(Value *val) {
325 assert(val && "IsConstantOne does not work with NULL val");
326 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
329 static Instruction *createMalloc(Instruction *InsertBefore,
330 BasicBlock *InsertAtEnd, const Type *IntPtrTy,
331 const Type *AllocTy, Value *AllocSize,
332 Value *ArraySize, Function *MallocF,
333 const Twine &Name) {
334 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
335 "createMalloc needs either InsertBefore or InsertAtEnd");
337 // malloc(type) becomes:
338 // bitcast (i8* malloc(typeSize)) to type*
339 // malloc(type, arraySize) becomes:
340 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
341 if (!ArraySize)
342 ArraySize = ConstantInt::get(IntPtrTy, 1);
343 else if (ArraySize->getType() != IntPtrTy) {
344 if (InsertBefore)
345 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
346 "", InsertBefore);
347 else
348 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
349 "", InsertAtEnd);
352 if (!IsConstantOne(ArraySize)) {
353 if (IsConstantOne(AllocSize)) {
354 AllocSize = ArraySize; // Operand * 1 = Operand
355 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
356 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
357 false /*ZExt*/);
358 // Malloc arg is constant product of type size and array size
359 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
360 } else {
361 // Multiply type size by the array size...
362 if (InsertBefore)
363 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
364 "mallocsize", InsertBefore);
365 else
366 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
367 "mallocsize", InsertAtEnd);
371 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
372 // Create the call to Malloc.
373 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
374 Module* M = BB->getParent()->getParent();
375 const Type *BPTy = Type::getInt8PtrTy(BB->getContext());
376 Value *MallocFunc = MallocF;
377 if (!MallocFunc)
378 // prototype malloc as "void *malloc(size_t)"
379 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
380 const PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
381 CallInst *MCall = NULL;
382 Instruction *Result = NULL;
383 if (InsertBefore) {
384 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
385 Result = MCall;
386 if (Result->getType() != AllocPtrType)
387 // Create a cast instruction to convert to the right type...
388 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
389 } else {
390 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
391 Result = MCall;
392 if (Result->getType() != AllocPtrType) {
393 InsertAtEnd->getInstList().push_back(MCall);
394 // Create a cast instruction to convert to the right type...
395 Result = new BitCastInst(MCall, AllocPtrType, Name);
398 MCall->setTailCall();
399 if (Function *F = dyn_cast<Function>(MallocFunc)) {
400 MCall->setCallingConv(F->getCallingConv());
401 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
403 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
405 return Result;
408 /// CreateMalloc - Generate the IR for a call to malloc:
409 /// 1. Compute the malloc call's argument as the specified type's size,
410 /// possibly multiplied by the array size if the array size is not
411 /// constant 1.
412 /// 2. Call malloc with that argument.
413 /// 3. Bitcast the result of the malloc call to the specified type.
414 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
415 const Type *IntPtrTy, const Type *AllocTy,
416 Value *AllocSize, Value *ArraySize,
417 Function * MallocF,
418 const Twine &Name) {
419 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
420 ArraySize, MallocF, Name);
423 /// CreateMalloc - Generate the IR for a call to malloc:
424 /// 1. Compute the malloc call's argument as the specified type's size,
425 /// possibly multiplied by the array size if the array size is not
426 /// constant 1.
427 /// 2. Call malloc with that argument.
428 /// 3. Bitcast the result of the malloc call to the specified type.
429 /// Note: This function does not add the bitcast to the basic block, that is the
430 /// responsibility of the caller.
431 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
432 const Type *IntPtrTy, const Type *AllocTy,
433 Value *AllocSize, Value *ArraySize,
434 Function *MallocF, const Twine &Name) {
435 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
436 ArraySize, MallocF, Name);
439 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
440 BasicBlock *InsertAtEnd) {
441 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
442 "createFree needs either InsertBefore or InsertAtEnd");
443 assert(Source->getType()->isPointerTy() &&
444 "Can not free something of nonpointer type!");
446 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
447 Module* M = BB->getParent()->getParent();
449 const Type *VoidTy = Type::getVoidTy(M->getContext());
450 const Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
451 // prototype free as "void free(void*)"
452 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
453 CallInst* Result = NULL;
454 Value *PtrCast = Source;
455 if (InsertBefore) {
456 if (Source->getType() != IntPtrTy)
457 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
458 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
459 } else {
460 if (Source->getType() != IntPtrTy)
461 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
462 Result = CallInst::Create(FreeFunc, PtrCast, "");
464 Result->setTailCall();
465 if (Function *F = dyn_cast<Function>(FreeFunc))
466 Result->setCallingConv(F->getCallingConv());
468 return Result;
471 /// CreateFree - Generate the IR for a call to the builtin free function.
472 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
473 return createFree(Source, InsertBefore, NULL);
476 /// CreateFree - Generate the IR for a call to the builtin free function.
477 /// Note: This function does not add the call to the basic block, that is the
478 /// responsibility of the caller.
479 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
480 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
481 assert(FreeCall && "CreateFree did not create a CallInst");
482 return FreeCall;
485 //===----------------------------------------------------------------------===//
486 // InvokeInst Implementation
487 //===----------------------------------------------------------------------===//
489 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
490 Value* const *Args, unsigned NumArgs) {
491 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
492 Op<-3>() = Fn;
493 Op<-2>() = IfNormal;
494 Op<-1>() = IfException;
495 const FunctionType *FTy =
496 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
497 (void)FTy; // silence warning.
499 assert(((NumArgs == FTy->getNumParams()) ||
500 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
501 "Invoking a function with bad signature");
503 Use *OL = OperandList;
504 for (unsigned i = 0, e = NumArgs; i != e; i++) {
505 assert((i >= FTy->getNumParams() ||
506 FTy->getParamType(i) == Args[i]->getType()) &&
507 "Invoking a function with a bad signature!");
509 OL[i] = Args[i];
513 InvokeInst::InvokeInst(const InvokeInst &II)
514 : TerminatorInst(II.getType(), Instruction::Invoke,
515 OperandTraits<InvokeInst>::op_end(this)
516 - II.getNumOperands(),
517 II.getNumOperands()) {
518 setAttributes(II.getAttributes());
519 setCallingConv(II.getCallingConv());
520 Use *OL = OperandList, *InOL = II.OperandList;
521 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
522 OL[i] = InOL[i];
523 SubclassOptionalData = II.SubclassOptionalData;
526 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
527 return getSuccessor(idx);
529 unsigned InvokeInst::getNumSuccessorsV() const {
530 return getNumSuccessors();
532 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
533 return setSuccessor(idx, B);
536 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
537 if (AttributeList.paramHasAttr(i, attr))
538 return true;
539 if (const Function *F = getCalledFunction())
540 return F->paramHasAttr(i, attr);
541 return false;
544 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
545 AttrListPtr PAL = getAttributes();
546 PAL = PAL.addAttr(i, attr);
547 setAttributes(PAL);
550 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
551 AttrListPtr PAL = getAttributes();
552 PAL = PAL.removeAttr(i, attr);
553 setAttributes(PAL);
557 //===----------------------------------------------------------------------===//
558 // ReturnInst Implementation
559 //===----------------------------------------------------------------------===//
561 ReturnInst::ReturnInst(const ReturnInst &RI)
562 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
563 OperandTraits<ReturnInst>::op_end(this) -
564 RI.getNumOperands(),
565 RI.getNumOperands()) {
566 if (RI.getNumOperands())
567 Op<0>() = RI.Op<0>();
568 SubclassOptionalData = RI.SubclassOptionalData;
571 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
572 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
573 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
574 InsertBefore) {
575 if (retVal)
576 Op<0>() = retVal;
578 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
579 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
580 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
581 InsertAtEnd) {
582 if (retVal)
583 Op<0>() = retVal;
585 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
586 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
587 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
590 unsigned ReturnInst::getNumSuccessorsV() const {
591 return getNumSuccessors();
594 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
595 /// emit the vtable for the class in this translation unit.
596 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
597 llvm_unreachable("ReturnInst has no successors!");
600 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
601 llvm_unreachable("ReturnInst has no successors!");
602 return 0;
605 ReturnInst::~ReturnInst() {
608 //===----------------------------------------------------------------------===//
609 // UnwindInst Implementation
610 //===----------------------------------------------------------------------===//
612 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
613 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
614 0, 0, InsertBefore) {
616 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
617 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
618 0, 0, InsertAtEnd) {
622 unsigned UnwindInst::getNumSuccessorsV() const {
623 return getNumSuccessors();
626 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
627 llvm_unreachable("UnwindInst has no successors!");
630 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
631 llvm_unreachable("UnwindInst has no successors!");
632 return 0;
635 //===----------------------------------------------------------------------===//
636 // UnreachableInst Implementation
637 //===----------------------------------------------------------------------===//
639 UnreachableInst::UnreachableInst(LLVMContext &Context,
640 Instruction *InsertBefore)
641 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
642 0, 0, InsertBefore) {
644 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
645 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
646 0, 0, InsertAtEnd) {
649 unsigned UnreachableInst::getNumSuccessorsV() const {
650 return getNumSuccessors();
653 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
654 llvm_unreachable("UnwindInst has no successors!");
657 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
658 llvm_unreachable("UnwindInst has no successors!");
659 return 0;
662 //===----------------------------------------------------------------------===//
663 // BranchInst Implementation
664 //===----------------------------------------------------------------------===//
666 void BranchInst::AssertOK() {
667 if (isConditional())
668 assert(getCondition()->getType()->isIntegerTy(1) &&
669 "May only branch on boolean predicates!");
672 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
673 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
674 OperandTraits<BranchInst>::op_end(this) - 1,
675 1, InsertBefore) {
676 assert(IfTrue != 0 && "Branch destination may not be null!");
677 Op<-1>() = IfTrue;
679 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
680 Instruction *InsertBefore)
681 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
682 OperandTraits<BranchInst>::op_end(this) - 3,
683 3, InsertBefore) {
684 Op<-1>() = IfTrue;
685 Op<-2>() = IfFalse;
686 Op<-3>() = Cond;
687 #ifndef NDEBUG
688 AssertOK();
689 #endif
692 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
693 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
694 OperandTraits<BranchInst>::op_end(this) - 1,
695 1, InsertAtEnd) {
696 assert(IfTrue != 0 && "Branch destination may not be null!");
697 Op<-1>() = IfTrue;
700 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
701 BasicBlock *InsertAtEnd)
702 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
703 OperandTraits<BranchInst>::op_end(this) - 3,
704 3, InsertAtEnd) {
705 Op<-1>() = IfTrue;
706 Op<-2>() = IfFalse;
707 Op<-3>() = Cond;
708 #ifndef NDEBUG
709 AssertOK();
710 #endif
714 BranchInst::BranchInst(const BranchInst &BI) :
715 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
716 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
717 BI.getNumOperands()) {
718 Op<-1>() = BI.Op<-1>();
719 if (BI.getNumOperands() != 1) {
720 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
721 Op<-3>() = BI.Op<-3>();
722 Op<-2>() = BI.Op<-2>();
724 SubclassOptionalData = BI.SubclassOptionalData;
727 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
728 return getSuccessor(idx);
730 unsigned BranchInst::getNumSuccessorsV() const {
731 return getNumSuccessors();
733 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
734 setSuccessor(idx, B);
738 //===----------------------------------------------------------------------===//
739 // AllocaInst Implementation
740 //===----------------------------------------------------------------------===//
742 static Value *getAISize(LLVMContext &Context, Value *Amt) {
743 if (!Amt)
744 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
745 else {
746 assert(!isa<BasicBlock>(Amt) &&
747 "Passed basic block into allocation size parameter! Use other ctor");
748 assert(Amt->getType()->isIntegerTy() &&
749 "Allocation array size is not an integer!");
751 return Amt;
754 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
755 const Twine &Name, Instruction *InsertBefore)
756 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
757 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
758 setAlignment(0);
759 assert(!Ty->isVoidTy() && "Cannot allocate void!");
760 setName(Name);
763 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize,
764 const Twine &Name, BasicBlock *InsertAtEnd)
765 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
766 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
767 setAlignment(0);
768 assert(!Ty->isVoidTy() && "Cannot allocate void!");
769 setName(Name);
772 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
773 Instruction *InsertBefore)
774 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
775 getAISize(Ty->getContext(), 0), InsertBefore) {
776 setAlignment(0);
777 assert(!Ty->isVoidTy() && "Cannot allocate void!");
778 setName(Name);
781 AllocaInst::AllocaInst(const Type *Ty, const Twine &Name,
782 BasicBlock *InsertAtEnd)
783 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
784 getAISize(Ty->getContext(), 0), InsertAtEnd) {
785 setAlignment(0);
786 assert(!Ty->isVoidTy() && "Cannot allocate void!");
787 setName(Name);
790 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
791 const Twine &Name, Instruction *InsertBefore)
792 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
793 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
794 setAlignment(Align);
795 assert(!Ty->isVoidTy() && "Cannot allocate void!");
796 setName(Name);
799 AllocaInst::AllocaInst(const Type *Ty, Value *ArraySize, unsigned Align,
800 const Twine &Name, BasicBlock *InsertAtEnd)
801 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
802 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
803 setAlignment(Align);
804 assert(!Ty->isVoidTy() && "Cannot allocate void!");
805 setName(Name);
808 // Out of line virtual method, so the vtable, etc has a home.
809 AllocaInst::~AllocaInst() {
812 void AllocaInst::setAlignment(unsigned Align) {
813 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
814 assert(Align <= MaximumAlignment &&
815 "Alignment is greater than MaximumAlignment!");
816 setInstructionSubclassData(Log2_32(Align) + 1);
817 assert(getAlignment() == Align && "Alignment representation error!");
820 bool AllocaInst::isArrayAllocation() const {
821 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
822 return !CI->isOne();
823 return true;
826 const Type *AllocaInst::getAllocatedType() const {
827 return getType()->getElementType();
830 /// isStaticAlloca - Return true if this alloca is in the entry block of the
831 /// function and is a constant size. If so, the code generator will fold it
832 /// into the prolog/epilog code, so it is basically free.
833 bool AllocaInst::isStaticAlloca() const {
834 // Must be constant size.
835 if (!isa<ConstantInt>(getArraySize())) return false;
837 // Must be in the entry block.
838 const BasicBlock *Parent = getParent();
839 return Parent == &Parent->getParent()->front();
842 //===----------------------------------------------------------------------===//
843 // LoadInst Implementation
844 //===----------------------------------------------------------------------===//
846 void LoadInst::AssertOK() {
847 assert(getOperand(0)->getType()->isPointerTy() &&
848 "Ptr must have pointer type.");
851 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
852 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
853 Load, Ptr, InsertBef) {
854 setVolatile(false);
855 setAlignment(0);
856 AssertOK();
857 setName(Name);
860 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
861 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
862 Load, Ptr, InsertAE) {
863 setVolatile(false);
864 setAlignment(0);
865 AssertOK();
866 setName(Name);
869 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
870 Instruction *InsertBef)
871 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
872 Load, Ptr, InsertBef) {
873 setVolatile(isVolatile);
874 setAlignment(0);
875 AssertOK();
876 setName(Name);
879 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
880 unsigned Align, Instruction *InsertBef)
881 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
882 Load, Ptr, InsertBef) {
883 setVolatile(isVolatile);
884 setAlignment(Align);
885 AssertOK();
886 setName(Name);
889 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
890 unsigned Align, BasicBlock *InsertAE)
891 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
892 Load, Ptr, InsertAE) {
893 setVolatile(isVolatile);
894 setAlignment(Align);
895 AssertOK();
896 setName(Name);
899 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
900 BasicBlock *InsertAE)
901 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
902 Load, Ptr, InsertAE) {
903 setVolatile(isVolatile);
904 setAlignment(0);
905 AssertOK();
906 setName(Name);
911 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
912 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
913 Load, Ptr, InsertBef) {
914 setVolatile(false);
915 setAlignment(0);
916 AssertOK();
917 if (Name && Name[0]) setName(Name);
920 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
921 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
922 Load, Ptr, InsertAE) {
923 setVolatile(false);
924 setAlignment(0);
925 AssertOK();
926 if (Name && Name[0]) setName(Name);
929 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
930 Instruction *InsertBef)
931 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
932 Load, Ptr, InsertBef) {
933 setVolatile(isVolatile);
934 setAlignment(0);
935 AssertOK();
936 if (Name && Name[0]) setName(Name);
939 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
940 BasicBlock *InsertAE)
941 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
942 Load, Ptr, InsertAE) {
943 setVolatile(isVolatile);
944 setAlignment(0);
945 AssertOK();
946 if (Name && Name[0]) setName(Name);
949 void LoadInst::setAlignment(unsigned Align) {
950 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
951 assert(Align <= MaximumAlignment &&
952 "Alignment is greater than MaximumAlignment!");
953 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
954 ((Log2_32(Align)+1)<<1));
955 assert(getAlignment() == Align && "Alignment representation error!");
958 //===----------------------------------------------------------------------===//
959 // StoreInst Implementation
960 //===----------------------------------------------------------------------===//
962 void StoreInst::AssertOK() {
963 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
964 assert(getOperand(1)->getType()->isPointerTy() &&
965 "Ptr must have pointer type!");
966 assert(getOperand(0)->getType() ==
967 cast<PointerType>(getOperand(1)->getType())->getElementType()
968 && "Ptr must be a pointer to Val type!");
972 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
973 : Instruction(Type::getVoidTy(val->getContext()), Store,
974 OperandTraits<StoreInst>::op_begin(this),
975 OperandTraits<StoreInst>::operands(this),
976 InsertBefore) {
977 Op<0>() = val;
978 Op<1>() = addr;
979 setVolatile(false);
980 setAlignment(0);
981 AssertOK();
984 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
985 : Instruction(Type::getVoidTy(val->getContext()), Store,
986 OperandTraits<StoreInst>::op_begin(this),
987 OperandTraits<StoreInst>::operands(this),
988 InsertAtEnd) {
989 Op<0>() = val;
990 Op<1>() = addr;
991 setVolatile(false);
992 setAlignment(0);
993 AssertOK();
996 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
997 Instruction *InsertBefore)
998 : Instruction(Type::getVoidTy(val->getContext()), Store,
999 OperandTraits<StoreInst>::op_begin(this),
1000 OperandTraits<StoreInst>::operands(this),
1001 InsertBefore) {
1002 Op<0>() = val;
1003 Op<1>() = addr;
1004 setVolatile(isVolatile);
1005 setAlignment(0);
1006 AssertOK();
1009 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1010 unsigned Align, Instruction *InsertBefore)
1011 : Instruction(Type::getVoidTy(val->getContext()), Store,
1012 OperandTraits<StoreInst>::op_begin(this),
1013 OperandTraits<StoreInst>::operands(this),
1014 InsertBefore) {
1015 Op<0>() = val;
1016 Op<1>() = addr;
1017 setVolatile(isVolatile);
1018 setAlignment(Align);
1019 AssertOK();
1022 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1023 unsigned Align, BasicBlock *InsertAtEnd)
1024 : Instruction(Type::getVoidTy(val->getContext()), Store,
1025 OperandTraits<StoreInst>::op_begin(this),
1026 OperandTraits<StoreInst>::operands(this),
1027 InsertAtEnd) {
1028 Op<0>() = val;
1029 Op<1>() = addr;
1030 setVolatile(isVolatile);
1031 setAlignment(Align);
1032 AssertOK();
1035 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1036 BasicBlock *InsertAtEnd)
1037 : Instruction(Type::getVoidTy(val->getContext()), Store,
1038 OperandTraits<StoreInst>::op_begin(this),
1039 OperandTraits<StoreInst>::operands(this),
1040 InsertAtEnd) {
1041 Op<0>() = val;
1042 Op<1>() = addr;
1043 setVolatile(isVolatile);
1044 setAlignment(0);
1045 AssertOK();
1048 void StoreInst::setAlignment(unsigned Align) {
1049 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1050 assert(Align <= MaximumAlignment &&
1051 "Alignment is greater than MaximumAlignment!");
1052 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1053 ((Log2_32(Align)+1) << 1));
1054 assert(getAlignment() == Align && "Alignment representation error!");
1057 //===----------------------------------------------------------------------===//
1058 // GetElementPtrInst Implementation
1059 //===----------------------------------------------------------------------===//
1061 static unsigned retrieveAddrSpace(const Value *Val) {
1062 return cast<PointerType>(Val->getType())->getAddressSpace();
1065 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1066 const Twine &Name) {
1067 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1068 Use *OL = OperandList;
1069 OL[0] = Ptr;
1071 for (unsigned i = 0; i != NumIdx; ++i)
1072 OL[i+1] = Idx[i];
1074 setName(Name);
1077 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1078 assert(NumOperands == 2 && "NumOperands not initialized?");
1079 Use *OL = OperandList;
1080 OL[0] = Ptr;
1081 OL[1] = Idx;
1083 setName(Name);
1086 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1087 : Instruction(GEPI.getType(), GetElementPtr,
1088 OperandTraits<GetElementPtrInst>::op_end(this)
1089 - GEPI.getNumOperands(),
1090 GEPI.getNumOperands()) {
1091 Use *OL = OperandList;
1092 Use *GEPIOL = GEPI.OperandList;
1093 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1094 OL[i] = GEPIOL[i];
1095 SubclassOptionalData = GEPI.SubclassOptionalData;
1098 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1099 const Twine &Name, Instruction *InBe)
1100 : Instruction(PointerType::get(
1101 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1102 GetElementPtr,
1103 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1104 2, InBe) {
1105 init(Ptr, Idx, Name);
1108 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1109 const Twine &Name, BasicBlock *IAE)
1110 : Instruction(PointerType::get(
1111 checkType(getIndexedType(Ptr->getType(),Idx)),
1112 retrieveAddrSpace(Ptr)),
1113 GetElementPtr,
1114 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1115 2, IAE) {
1116 init(Ptr, Idx, Name);
1119 /// getIndexedType - Returns the type of the element that would be accessed with
1120 /// a gep instruction with the specified parameters.
1122 /// The Idxs pointer should point to a continuous piece of memory containing the
1123 /// indices, either as Value* or uint64_t.
1125 /// A null type is returned if the indices are invalid for the specified
1126 /// pointer type.
1128 template <typename IndexTy>
1129 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1130 unsigned NumIdx) {
1131 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1132 if (!PTy) return 0; // Type isn't a pointer type!
1133 const Type *Agg = PTy->getElementType();
1135 // Handle the special case of the empty set index set, which is always valid.
1136 if (NumIdx == 0)
1137 return Agg;
1139 // If there is at least one index, the top level type must be sized, otherwise
1140 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1141 // that contain opaque types) under the assumption that it will be resolved to
1142 // a sane type later.
1143 if (!Agg->isSized() && !Agg->isAbstract())
1144 return 0;
1146 unsigned CurIdx = 1;
1147 for (; CurIdx != NumIdx; ++CurIdx) {
1148 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1149 if (!CT || CT->isPointerTy()) return 0;
1150 IndexTy Index = Idxs[CurIdx];
1151 if (!CT->indexValid(Index)) return 0;
1152 Agg = CT->getTypeAtIndex(Index);
1154 // If the new type forwards to another type, then it is in the middle
1155 // of being refined to another type (and hence, may have dropped all
1156 // references to what it was using before). So, use the new forwarded
1157 // type.
1158 if (const Type *Ty = Agg->getForwardedType())
1159 Agg = Ty;
1161 return CurIdx == NumIdx ? Agg : 0;
1164 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1165 Value* const *Idxs,
1166 unsigned NumIdx) {
1167 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1170 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1171 Constant* const *Idxs,
1172 unsigned NumIdx) {
1173 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1176 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1177 uint64_t const *Idxs,
1178 unsigned NumIdx) {
1179 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1182 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1183 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1184 if (!PTy) return 0; // Type isn't a pointer type!
1186 // Check the pointer index.
1187 if (!PTy->indexValid(Idx)) return 0;
1189 return PTy->getElementType();
1193 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1194 /// zeros. If so, the result pointer and the first operand have the same
1195 /// value, just potentially different types.
1196 bool GetElementPtrInst::hasAllZeroIndices() const {
1197 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1198 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1199 if (!CI->isZero()) return false;
1200 } else {
1201 return false;
1204 return true;
1207 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1208 /// constant integers. If so, the result pointer and the first operand have
1209 /// a constant offset between them.
1210 bool GetElementPtrInst::hasAllConstantIndices() const {
1211 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1212 if (!isa<ConstantInt>(getOperand(i)))
1213 return false;
1215 return true;
1218 void GetElementPtrInst::setIsInBounds(bool B) {
1219 cast<GEPOperator>(this)->setIsInBounds(B);
1222 bool GetElementPtrInst::isInBounds() const {
1223 return cast<GEPOperator>(this)->isInBounds();
1226 //===----------------------------------------------------------------------===//
1227 // ExtractElementInst Implementation
1228 //===----------------------------------------------------------------------===//
1230 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1231 const Twine &Name,
1232 Instruction *InsertBef)
1233 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1234 ExtractElement,
1235 OperandTraits<ExtractElementInst>::op_begin(this),
1236 2, InsertBef) {
1237 assert(isValidOperands(Val, Index) &&
1238 "Invalid extractelement instruction operands!");
1239 Op<0>() = Val;
1240 Op<1>() = Index;
1241 setName(Name);
1244 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1245 const Twine &Name,
1246 BasicBlock *InsertAE)
1247 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1248 ExtractElement,
1249 OperandTraits<ExtractElementInst>::op_begin(this),
1250 2, InsertAE) {
1251 assert(isValidOperands(Val, Index) &&
1252 "Invalid extractelement instruction operands!");
1254 Op<0>() = Val;
1255 Op<1>() = Index;
1256 setName(Name);
1260 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1261 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1262 return false;
1263 return true;
1267 //===----------------------------------------------------------------------===//
1268 // InsertElementInst Implementation
1269 //===----------------------------------------------------------------------===//
1271 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1272 const Twine &Name,
1273 Instruction *InsertBef)
1274 : Instruction(Vec->getType(), InsertElement,
1275 OperandTraits<InsertElementInst>::op_begin(this),
1276 3, InsertBef) {
1277 assert(isValidOperands(Vec, Elt, Index) &&
1278 "Invalid insertelement instruction operands!");
1279 Op<0>() = Vec;
1280 Op<1>() = Elt;
1281 Op<2>() = Index;
1282 setName(Name);
1285 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1286 const Twine &Name,
1287 BasicBlock *InsertAE)
1288 : Instruction(Vec->getType(), InsertElement,
1289 OperandTraits<InsertElementInst>::op_begin(this),
1290 3, InsertAE) {
1291 assert(isValidOperands(Vec, Elt, Index) &&
1292 "Invalid insertelement instruction operands!");
1294 Op<0>() = Vec;
1295 Op<1>() = Elt;
1296 Op<2>() = Index;
1297 setName(Name);
1300 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1301 const Value *Index) {
1302 if (!Vec->getType()->isVectorTy())
1303 return false; // First operand of insertelement must be vector type.
1305 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1306 return false;// Second operand of insertelement must be vector element type.
1308 if (!Index->getType()->isIntegerTy(32))
1309 return false; // Third operand of insertelement must be i32.
1310 return true;
1314 //===----------------------------------------------------------------------===//
1315 // ShuffleVectorInst Implementation
1316 //===----------------------------------------------------------------------===//
1318 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1319 const Twine &Name,
1320 Instruction *InsertBefore)
1321 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1322 cast<VectorType>(Mask->getType())->getNumElements()),
1323 ShuffleVector,
1324 OperandTraits<ShuffleVectorInst>::op_begin(this),
1325 OperandTraits<ShuffleVectorInst>::operands(this),
1326 InsertBefore) {
1327 assert(isValidOperands(V1, V2, Mask) &&
1328 "Invalid shuffle vector instruction operands!");
1329 Op<0>() = V1;
1330 Op<1>() = V2;
1331 Op<2>() = Mask;
1332 setName(Name);
1335 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1336 const Twine &Name,
1337 BasicBlock *InsertAtEnd)
1338 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1339 cast<VectorType>(Mask->getType())->getNumElements()),
1340 ShuffleVector,
1341 OperandTraits<ShuffleVectorInst>::op_begin(this),
1342 OperandTraits<ShuffleVectorInst>::operands(this),
1343 InsertAtEnd) {
1344 assert(isValidOperands(V1, V2, Mask) &&
1345 "Invalid shuffle vector instruction operands!");
1347 Op<0>() = V1;
1348 Op<1>() = V2;
1349 Op<2>() = Mask;
1350 setName(Name);
1353 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1354 const Value *Mask) {
1355 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1356 return false;
1358 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1359 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1360 return false;
1362 // Check to see if Mask is valid.
1363 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1364 const VectorType *VTy = cast<VectorType>(V1->getType());
1365 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1366 if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1367 if (CI->uge(VTy->getNumElements()*2))
1368 return false;
1369 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1370 return false;
1374 else if (!isa<UndefValue>(Mask) && !isa<ConstantAggregateZero>(Mask))
1375 return false;
1377 return true;
1380 /// getMaskValue - Return the index from the shuffle mask for the specified
1381 /// output result. This is either -1 if the element is undef or a number less
1382 /// than 2*numelements.
1383 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1384 const Constant *Mask = cast<Constant>(getOperand(2));
1385 if (isa<UndefValue>(Mask)) return -1;
1386 if (isa<ConstantAggregateZero>(Mask)) return 0;
1387 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1388 assert(i < MaskCV->getNumOperands() && "Index out of range");
1390 if (isa<UndefValue>(MaskCV->getOperand(i)))
1391 return -1;
1392 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1395 //===----------------------------------------------------------------------===//
1396 // InsertValueInst Class
1397 //===----------------------------------------------------------------------===//
1399 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1400 unsigned NumIdx, const Twine &Name) {
1401 assert(NumOperands == 2 && "NumOperands not initialized?");
1402 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idx, Idx + NumIdx) ==
1403 Val->getType() && "Inserted value must match indexed type!");
1404 Op<0>() = Agg;
1405 Op<1>() = Val;
1407 Indices.append(Idx, Idx + NumIdx);
1408 setName(Name);
1411 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1412 const Twine &Name) {
1413 assert(NumOperands == 2 && "NumOperands not initialized?");
1414 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idx) == Val->getType()
1415 && "Inserted value must match indexed type!");
1416 Op<0>() = Agg;
1417 Op<1>() = Val;
1419 Indices.push_back(Idx);
1420 setName(Name);
1423 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1424 : Instruction(IVI.getType(), InsertValue,
1425 OperandTraits<InsertValueInst>::op_begin(this), 2),
1426 Indices(IVI.Indices) {
1427 Op<0>() = IVI.getOperand(0);
1428 Op<1>() = IVI.getOperand(1);
1429 SubclassOptionalData = IVI.SubclassOptionalData;
1432 InsertValueInst::InsertValueInst(Value *Agg,
1433 Value *Val,
1434 unsigned Idx,
1435 const Twine &Name,
1436 Instruction *InsertBefore)
1437 : Instruction(Agg->getType(), InsertValue,
1438 OperandTraits<InsertValueInst>::op_begin(this),
1439 2, InsertBefore) {
1440 init(Agg, Val, Idx, Name);
1443 InsertValueInst::InsertValueInst(Value *Agg,
1444 Value *Val,
1445 unsigned Idx,
1446 const Twine &Name,
1447 BasicBlock *InsertAtEnd)
1448 : Instruction(Agg->getType(), InsertValue,
1449 OperandTraits<InsertValueInst>::op_begin(this),
1450 2, InsertAtEnd) {
1451 init(Agg, Val, Idx, Name);
1454 //===----------------------------------------------------------------------===//
1455 // ExtractValueInst Class
1456 //===----------------------------------------------------------------------===//
1458 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1459 const Twine &Name) {
1460 assert(NumOperands == 1 && "NumOperands not initialized?");
1462 Indices.append(Idx, Idx + NumIdx);
1463 setName(Name);
1466 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1467 assert(NumOperands == 1 && "NumOperands not initialized?");
1469 Indices.push_back(Idx);
1470 setName(Name);
1473 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1474 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1475 Indices(EVI.Indices) {
1476 SubclassOptionalData = EVI.SubclassOptionalData;
1479 // getIndexedType - Returns the type of the element that would be extracted
1480 // with an extractvalue instruction with the specified parameters.
1482 // A null type is returned if the indices are invalid for the specified
1483 // pointer type.
1485 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1486 const unsigned *Idxs,
1487 unsigned NumIdx) {
1488 for (unsigned CurIdx = 0; CurIdx != NumIdx; ++CurIdx) {
1489 unsigned Index = Idxs[CurIdx];
1490 // We can't use CompositeType::indexValid(Index) here.
1491 // indexValid() always returns true for arrays because getelementptr allows
1492 // out-of-bounds indices. Since we don't allow those for extractvalue and
1493 // insertvalue we need to check array indexing manually.
1494 // Since the only other types we can index into are struct types it's just
1495 // as easy to check those manually as well.
1496 if (const ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1497 if (Index >= AT->getNumElements())
1498 return 0;
1499 } else if (const StructType *ST = dyn_cast<StructType>(Agg)) {
1500 if (Index >= ST->getNumElements())
1501 return 0;
1502 } else {
1503 // Not a valid type to index into.
1504 return 0;
1507 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1509 // If the new type forwards to another type, then it is in the middle
1510 // of being refined to another type (and hence, may have dropped all
1511 // references to what it was using before). So, use the new forwarded
1512 // type.
1513 if (const Type *Ty = Agg->getForwardedType())
1514 Agg = Ty;
1516 return Agg;
1519 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1520 unsigned Idx) {
1521 return getIndexedType(Agg, &Idx, 1);
1524 //===----------------------------------------------------------------------===//
1525 // BinaryOperator Class
1526 //===----------------------------------------------------------------------===//
1528 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1529 const Type *Ty, const Twine &Name,
1530 Instruction *InsertBefore)
1531 : Instruction(Ty, iType,
1532 OperandTraits<BinaryOperator>::op_begin(this),
1533 OperandTraits<BinaryOperator>::operands(this),
1534 InsertBefore) {
1535 Op<0>() = S1;
1536 Op<1>() = S2;
1537 init(iType);
1538 setName(Name);
1541 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1542 const Type *Ty, const Twine &Name,
1543 BasicBlock *InsertAtEnd)
1544 : Instruction(Ty, iType,
1545 OperandTraits<BinaryOperator>::op_begin(this),
1546 OperandTraits<BinaryOperator>::operands(this),
1547 InsertAtEnd) {
1548 Op<0>() = S1;
1549 Op<1>() = S2;
1550 init(iType);
1551 setName(Name);
1555 void BinaryOperator::init(BinaryOps iType) {
1556 Value *LHS = getOperand(0), *RHS = getOperand(1);
1557 (void)LHS; (void)RHS; // Silence warnings.
1558 assert(LHS->getType() == RHS->getType() &&
1559 "Binary operator operand types must match!");
1560 #ifndef NDEBUG
1561 switch (iType) {
1562 case Add: case Sub:
1563 case Mul:
1564 assert(getType() == LHS->getType() &&
1565 "Arithmetic operation should return same type as operands!");
1566 assert(getType()->isIntOrIntVectorTy() &&
1567 "Tried to create an integer operation on a non-integer type!");
1568 break;
1569 case FAdd: case FSub:
1570 case FMul:
1571 assert(getType() == LHS->getType() &&
1572 "Arithmetic operation should return same type as operands!");
1573 assert(getType()->isFPOrFPVectorTy() &&
1574 "Tried to create a floating-point operation on a "
1575 "non-floating-point type!");
1576 break;
1577 case UDiv:
1578 case SDiv:
1579 assert(getType() == LHS->getType() &&
1580 "Arithmetic operation should return same type as operands!");
1581 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1582 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1583 "Incorrect operand type (not integer) for S/UDIV");
1584 break;
1585 case FDiv:
1586 assert(getType() == LHS->getType() &&
1587 "Arithmetic operation should return same type as operands!");
1588 assert(getType()->isFPOrFPVectorTy() &&
1589 "Incorrect operand type (not floating point) for FDIV");
1590 break;
1591 case URem:
1592 case SRem:
1593 assert(getType() == LHS->getType() &&
1594 "Arithmetic operation should return same type as operands!");
1595 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1596 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1597 "Incorrect operand type (not integer) for S/UREM");
1598 break;
1599 case FRem:
1600 assert(getType() == LHS->getType() &&
1601 "Arithmetic operation should return same type as operands!");
1602 assert(getType()->isFPOrFPVectorTy() &&
1603 "Incorrect operand type (not floating point) for FREM");
1604 break;
1605 case Shl:
1606 case LShr:
1607 case AShr:
1608 assert(getType() == LHS->getType() &&
1609 "Shift operation should return same type as operands!");
1610 assert((getType()->isIntegerTy() ||
1611 (getType()->isVectorTy() &&
1612 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1613 "Tried to create a shift operation on a non-integral type!");
1614 break;
1615 case And: case Or:
1616 case Xor:
1617 assert(getType() == LHS->getType() &&
1618 "Logical operation should return same type as operands!");
1619 assert((getType()->isIntegerTy() ||
1620 (getType()->isVectorTy() &&
1621 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1622 "Tried to create a logical operation on a non-integral type!");
1623 break;
1624 default:
1625 break;
1627 #endif
1630 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1631 const Twine &Name,
1632 Instruction *InsertBefore) {
1633 assert(S1->getType() == S2->getType() &&
1634 "Cannot create binary operator with two operands of differing type!");
1635 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1638 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1639 const Twine &Name,
1640 BasicBlock *InsertAtEnd) {
1641 BinaryOperator *Res = Create(Op, S1, S2, Name);
1642 InsertAtEnd->getInstList().push_back(Res);
1643 return Res;
1646 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1647 Instruction *InsertBefore) {
1648 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1649 return new BinaryOperator(Instruction::Sub,
1650 zero, Op,
1651 Op->getType(), Name, InsertBefore);
1654 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1655 BasicBlock *InsertAtEnd) {
1656 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1657 return new BinaryOperator(Instruction::Sub,
1658 zero, Op,
1659 Op->getType(), Name, InsertAtEnd);
1662 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1663 Instruction *InsertBefore) {
1664 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1665 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1668 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1669 BasicBlock *InsertAtEnd) {
1670 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1671 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1674 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1675 Instruction *InsertBefore) {
1676 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1677 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1680 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1681 BasicBlock *InsertAtEnd) {
1682 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1683 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1686 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1687 Instruction *InsertBefore) {
1688 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1689 return new BinaryOperator(Instruction::FSub,
1690 zero, Op,
1691 Op->getType(), Name, InsertBefore);
1694 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1695 BasicBlock *InsertAtEnd) {
1696 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1697 return new BinaryOperator(Instruction::FSub,
1698 zero, Op,
1699 Op->getType(), Name, InsertAtEnd);
1702 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1703 Instruction *InsertBefore) {
1704 Constant *C;
1705 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1706 C = Constant::getAllOnesValue(PTy->getElementType());
1707 C = ConstantVector::get(
1708 std::vector<Constant*>(PTy->getNumElements(), C));
1709 } else {
1710 C = Constant::getAllOnesValue(Op->getType());
1713 return new BinaryOperator(Instruction::Xor, Op, C,
1714 Op->getType(), Name, InsertBefore);
1717 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1718 BasicBlock *InsertAtEnd) {
1719 Constant *AllOnes;
1720 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1721 // Create a vector of all ones values.
1722 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1723 AllOnes = ConstantVector::get(
1724 std::vector<Constant*>(PTy->getNumElements(), Elt));
1725 } else {
1726 AllOnes = Constant::getAllOnesValue(Op->getType());
1729 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1730 Op->getType(), Name, InsertAtEnd);
1734 // isConstantAllOnes - Helper function for several functions below
1735 static inline bool isConstantAllOnes(const Value *V) {
1736 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1737 return CI->isAllOnesValue();
1738 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1739 return CV->isAllOnesValue();
1740 return false;
1743 bool BinaryOperator::isNeg(const Value *V) {
1744 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1745 if (Bop->getOpcode() == Instruction::Sub)
1746 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1747 return C->isNegativeZeroValue();
1748 return false;
1751 bool BinaryOperator::isFNeg(const Value *V) {
1752 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1753 if (Bop->getOpcode() == Instruction::FSub)
1754 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1755 return C->isNegativeZeroValue();
1756 return false;
1759 bool BinaryOperator::isNot(const Value *V) {
1760 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1761 return (Bop->getOpcode() == Instruction::Xor &&
1762 (isConstantAllOnes(Bop->getOperand(1)) ||
1763 isConstantAllOnes(Bop->getOperand(0))));
1764 return false;
1767 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1768 return cast<BinaryOperator>(BinOp)->getOperand(1);
1771 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1772 return getNegArgument(const_cast<Value*>(BinOp));
1775 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1776 return cast<BinaryOperator>(BinOp)->getOperand(1);
1779 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1780 return getFNegArgument(const_cast<Value*>(BinOp));
1783 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1784 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1785 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1786 Value *Op0 = BO->getOperand(0);
1787 Value *Op1 = BO->getOperand(1);
1788 if (isConstantAllOnes(Op0)) return Op1;
1790 assert(isConstantAllOnes(Op1));
1791 return Op0;
1794 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1795 return getNotArgument(const_cast<Value*>(BinOp));
1799 // swapOperands - Exchange the two operands to this instruction. This
1800 // instruction is safe to use on any binary instruction and does not
1801 // modify the semantics of the instruction. If the instruction is
1802 // order dependent (SetLT f.e.) the opcode is changed.
1804 bool BinaryOperator::swapOperands() {
1805 if (!isCommutative())
1806 return true; // Can't commute operands
1807 Op<0>().swap(Op<1>());
1808 return false;
1811 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1812 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1815 void BinaryOperator::setHasNoSignedWrap(bool b) {
1816 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1819 void BinaryOperator::setIsExact(bool b) {
1820 cast<PossiblyExactOperator>(this)->setIsExact(b);
1823 bool BinaryOperator::hasNoUnsignedWrap() const {
1824 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1827 bool BinaryOperator::hasNoSignedWrap() const {
1828 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1831 bool BinaryOperator::isExact() const {
1832 return cast<PossiblyExactOperator>(this)->isExact();
1835 //===----------------------------------------------------------------------===//
1836 // CastInst Class
1837 //===----------------------------------------------------------------------===//
1839 // Just determine if this cast only deals with integral->integral conversion.
1840 bool CastInst::isIntegerCast() const {
1841 switch (getOpcode()) {
1842 default: return false;
1843 case Instruction::ZExt:
1844 case Instruction::SExt:
1845 case Instruction::Trunc:
1846 return true;
1847 case Instruction::BitCast:
1848 return getOperand(0)->getType()->isIntegerTy() &&
1849 getType()->isIntegerTy();
1853 bool CastInst::isLosslessCast() const {
1854 // Only BitCast can be lossless, exit fast if we're not BitCast
1855 if (getOpcode() != Instruction::BitCast)
1856 return false;
1858 // Identity cast is always lossless
1859 const Type* SrcTy = getOperand(0)->getType();
1860 const Type* DstTy = getType();
1861 if (SrcTy == DstTy)
1862 return true;
1864 // Pointer to pointer is always lossless.
1865 if (SrcTy->isPointerTy())
1866 return DstTy->isPointerTy();
1867 return false; // Other types have no identity values
1870 /// This function determines if the CastInst does not require any bits to be
1871 /// changed in order to effect the cast. Essentially, it identifies cases where
1872 /// no code gen is necessary for the cast, hence the name no-op cast. For
1873 /// example, the following are all no-op casts:
1874 /// # bitcast i32* %x to i8*
1875 /// # bitcast <2 x i32> %x to <4 x i16>
1876 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1877 /// @brief Determine if the described cast is a no-op.
1878 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
1879 const Type *SrcTy,
1880 const Type *DestTy,
1881 const Type *IntPtrTy) {
1882 switch (Opcode) {
1883 default:
1884 assert(!"Invalid CastOp");
1885 case Instruction::Trunc:
1886 case Instruction::ZExt:
1887 case Instruction::SExt:
1888 case Instruction::FPTrunc:
1889 case Instruction::FPExt:
1890 case Instruction::UIToFP:
1891 case Instruction::SIToFP:
1892 case Instruction::FPToUI:
1893 case Instruction::FPToSI:
1894 return false; // These always modify bits
1895 case Instruction::BitCast:
1896 return true; // BitCast never modifies bits.
1897 case Instruction::PtrToInt:
1898 return IntPtrTy->getScalarSizeInBits() ==
1899 DestTy->getScalarSizeInBits();
1900 case Instruction::IntToPtr:
1901 return IntPtrTy->getScalarSizeInBits() ==
1902 SrcTy->getScalarSizeInBits();
1906 /// @brief Determine if a cast is a no-op.
1907 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1908 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
1911 /// This function determines if a pair of casts can be eliminated and what
1912 /// opcode should be used in the elimination. This assumes that there are two
1913 /// instructions like this:
1914 /// * %F = firstOpcode SrcTy %x to MidTy
1915 /// * %S = secondOpcode MidTy %F to DstTy
1916 /// The function returns a resultOpcode so these two casts can be replaced with:
1917 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1918 /// If no such cast is permited, the function returns 0.
1919 unsigned CastInst::isEliminableCastPair(
1920 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1921 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1923 // Define the 144 possibilities for these two cast instructions. The values
1924 // in this matrix determine what to do in a given situation and select the
1925 // case in the switch below. The rows correspond to firstOp, the columns
1926 // correspond to secondOp. In looking at the table below, keep in mind
1927 // the following cast properties:
1929 // Size Compare Source Destination
1930 // Operator Src ? Size Type Sign Type Sign
1931 // -------- ------------ ------------------- ---------------------
1932 // TRUNC > Integer Any Integral Any
1933 // ZEXT < Integral Unsigned Integer Any
1934 // SEXT < Integral Signed Integer Any
1935 // FPTOUI n/a FloatPt n/a Integral Unsigned
1936 // FPTOSI n/a FloatPt n/a Integral Signed
1937 // UITOFP n/a Integral Unsigned FloatPt n/a
1938 // SITOFP n/a Integral Signed FloatPt n/a
1939 // FPTRUNC > FloatPt n/a FloatPt n/a
1940 // FPEXT < FloatPt n/a FloatPt n/a
1941 // PTRTOINT n/a Pointer n/a Integral Unsigned
1942 // INTTOPTR n/a Integral Unsigned Pointer n/a
1943 // BITCAST = FirstClass n/a FirstClass n/a
1945 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1946 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
1947 // into "fptoui double to i64", but this loses information about the range
1948 // of the produced value (we no longer know the top-part is all zeros).
1949 // Further this conversion is often much more expensive for typical hardware,
1950 // and causes issues when building libgcc. We disallow fptosi+sext for the
1951 // same reason.
1952 const unsigned numCastOps =
1953 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1954 static const uint8_t CastResults[numCastOps][numCastOps] = {
1955 // T F F U S F F P I B -+
1956 // R Z S P P I I T P 2 N T |
1957 // U E E 2 2 2 2 R E I T C +- secondOp
1958 // N X X U S F F N X N 2 V |
1959 // C T T I I P P C T T P T -+
1960 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1961 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1962 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1963 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1964 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1965 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1966 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1967 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1968 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1969 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1970 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1971 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1974 // If either of the casts are a bitcast from scalar to vector, disallow the
1975 // merging.
1976 if ((firstOp == Instruction::BitCast &&
1977 isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
1978 (secondOp == Instruction::BitCast &&
1979 isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
1980 return 0; // Disallowed
1982 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1983 [secondOp-Instruction::CastOpsBegin];
1984 switch (ElimCase) {
1985 case 0:
1986 // categorically disallowed
1987 return 0;
1988 case 1:
1989 // allowed, use first cast's opcode
1990 return firstOp;
1991 case 2:
1992 // allowed, use second cast's opcode
1993 return secondOp;
1994 case 3:
1995 // no-op cast in second op implies firstOp as long as the DestTy
1996 // is integer and we are not converting between a vector and a
1997 // non vector type.
1998 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
1999 return firstOp;
2000 return 0;
2001 case 4:
2002 // no-op cast in second op implies firstOp as long as the DestTy
2003 // is floating point.
2004 if (DstTy->isFloatingPointTy())
2005 return firstOp;
2006 return 0;
2007 case 5:
2008 // no-op cast in first op implies secondOp as long as the SrcTy
2009 // is an integer.
2010 if (SrcTy->isIntegerTy())
2011 return secondOp;
2012 return 0;
2013 case 6:
2014 // no-op cast in first op implies secondOp as long as the SrcTy
2015 // is a floating point.
2016 if (SrcTy->isFloatingPointTy())
2017 return secondOp;
2018 return 0;
2019 case 7: {
2020 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2021 if (!IntPtrTy)
2022 return 0;
2023 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2024 unsigned MidSize = MidTy->getScalarSizeInBits();
2025 if (MidSize >= PtrSize)
2026 return Instruction::BitCast;
2027 return 0;
2029 case 8: {
2030 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2031 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2032 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2033 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2034 unsigned DstSize = DstTy->getScalarSizeInBits();
2035 if (SrcSize == DstSize)
2036 return Instruction::BitCast;
2037 else if (SrcSize < DstSize)
2038 return firstOp;
2039 return secondOp;
2041 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2042 return Instruction::ZExt;
2043 case 10:
2044 // fpext followed by ftrunc is allowed if the bit size returned to is
2045 // the same as the original, in which case its just a bitcast
2046 if (SrcTy == DstTy)
2047 return Instruction::BitCast;
2048 return 0; // If the types are not the same we can't eliminate it.
2049 case 11:
2050 // bitcast followed by ptrtoint is allowed as long as the bitcast
2051 // is a pointer to pointer cast.
2052 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2053 return secondOp;
2054 return 0;
2055 case 12:
2056 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2057 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2058 return firstOp;
2059 return 0;
2060 case 13: {
2061 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2062 if (!IntPtrTy)
2063 return 0;
2064 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2065 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2066 unsigned DstSize = DstTy->getScalarSizeInBits();
2067 if (SrcSize <= PtrSize && SrcSize == DstSize)
2068 return Instruction::BitCast;
2069 return 0;
2071 case 99:
2072 // cast combination can't happen (error in input). This is for all cases
2073 // where the MidTy is not the same for the two cast instructions.
2074 assert(!"Invalid Cast Combination");
2075 return 0;
2076 default:
2077 assert(!"Error in CastResults table!!!");
2078 return 0;
2080 return 0;
2083 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2084 const Twine &Name, Instruction *InsertBefore) {
2085 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2086 // Construct and return the appropriate CastInst subclass
2087 switch (op) {
2088 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2089 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2090 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2091 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2092 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2093 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2094 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2095 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2096 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2097 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2098 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2099 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2100 default:
2101 assert(!"Invalid opcode provided");
2103 return 0;
2106 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2107 const Twine &Name, BasicBlock *InsertAtEnd) {
2108 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2109 // Construct and return the appropriate CastInst subclass
2110 switch (op) {
2111 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2112 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2113 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2114 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2115 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2116 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2117 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2118 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2119 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2120 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2121 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2122 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2123 default:
2124 assert(!"Invalid opcode provided");
2126 return 0;
2129 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2130 const Twine &Name,
2131 Instruction *InsertBefore) {
2132 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2133 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2134 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2137 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2138 const Twine &Name,
2139 BasicBlock *InsertAtEnd) {
2140 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2141 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2142 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2145 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2146 const Twine &Name,
2147 Instruction *InsertBefore) {
2148 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2149 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2150 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2153 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2154 const Twine &Name,
2155 BasicBlock *InsertAtEnd) {
2156 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2157 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2158 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2161 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2162 const Twine &Name,
2163 Instruction *InsertBefore) {
2164 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2165 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2166 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2169 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2170 const Twine &Name,
2171 BasicBlock *InsertAtEnd) {
2172 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2173 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2174 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2177 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2178 const Twine &Name,
2179 BasicBlock *InsertAtEnd) {
2180 assert(S->getType()->isPointerTy() && "Invalid cast");
2181 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2182 "Invalid cast");
2184 if (Ty->isIntegerTy())
2185 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2186 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2189 /// @brief Create a BitCast or a PtrToInt cast instruction
2190 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2191 const Twine &Name,
2192 Instruction *InsertBefore) {
2193 assert(S->getType()->isPointerTy() && "Invalid cast");
2194 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2195 "Invalid cast");
2197 if (Ty->isIntegerTy())
2198 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2199 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2202 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2203 bool isSigned, const Twine &Name,
2204 Instruction *InsertBefore) {
2205 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2206 "Invalid integer cast");
2207 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2208 unsigned DstBits = Ty->getScalarSizeInBits();
2209 Instruction::CastOps opcode =
2210 (SrcBits == DstBits ? Instruction::BitCast :
2211 (SrcBits > DstBits ? Instruction::Trunc :
2212 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2213 return Create(opcode, C, Ty, Name, InsertBefore);
2216 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2217 bool isSigned, const Twine &Name,
2218 BasicBlock *InsertAtEnd) {
2219 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2220 "Invalid cast");
2221 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2222 unsigned DstBits = Ty->getScalarSizeInBits();
2223 Instruction::CastOps opcode =
2224 (SrcBits == DstBits ? Instruction::BitCast :
2225 (SrcBits > DstBits ? Instruction::Trunc :
2226 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2227 return Create(opcode, C, Ty, Name, InsertAtEnd);
2230 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2231 const Twine &Name,
2232 Instruction *InsertBefore) {
2233 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2234 "Invalid cast");
2235 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2236 unsigned DstBits = Ty->getScalarSizeInBits();
2237 Instruction::CastOps opcode =
2238 (SrcBits == DstBits ? Instruction::BitCast :
2239 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2240 return Create(opcode, C, Ty, Name, InsertBefore);
2243 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2244 const Twine &Name,
2245 BasicBlock *InsertAtEnd) {
2246 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2247 "Invalid cast");
2248 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2249 unsigned DstBits = Ty->getScalarSizeInBits();
2250 Instruction::CastOps opcode =
2251 (SrcBits == DstBits ? Instruction::BitCast :
2252 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2253 return Create(opcode, C, Ty, Name, InsertAtEnd);
2256 // Check whether it is valid to call getCastOpcode for these types.
2257 // This routine must be kept in sync with getCastOpcode.
2258 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2259 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2260 return false;
2262 if (SrcTy == DestTy)
2263 return true;
2265 if (const VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2266 if (const VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2267 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2268 // An element by element cast. Valid if casting the elements is valid.
2269 SrcTy = SrcVecTy->getElementType();
2270 DestTy = DestVecTy->getElementType();
2273 // Get the bit sizes, we'll need these
2274 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2275 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2277 // Run through the possibilities ...
2278 if (DestTy->isIntegerTy()) { // Casting to integral
2279 if (SrcTy->isIntegerTy()) { // Casting from integral
2280 return true;
2281 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2282 return true;
2283 } else if (SrcTy->isVectorTy()) { // Casting from vector
2284 return DestBits == SrcBits;
2285 } else { // Casting from something else
2286 return SrcTy->isPointerTy();
2288 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2289 if (SrcTy->isIntegerTy()) { // Casting from integral
2290 return true;
2291 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2292 return true;
2293 } else if (SrcTy->isVectorTy()) { // Casting from vector
2294 return DestBits == SrcBits;
2295 } else { // Casting from something else
2296 return false;
2298 } else if (DestTy->isVectorTy()) { // Casting to vector
2299 return DestBits == SrcBits;
2300 } else if (DestTy->isPointerTy()) { // Casting to pointer
2301 if (SrcTy->isPointerTy()) { // Casting from pointer
2302 return true;
2303 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2304 return true;
2305 } else { // Casting from something else
2306 return false;
2308 } else if (DestTy->isX86_MMXTy()) {
2309 if (SrcTy->isVectorTy()) {
2310 return DestBits == SrcBits; // 64-bit vector to MMX
2311 } else {
2312 return false;
2314 } else { // Casting to something else
2315 return false;
2319 // Provide a way to get a "cast" where the cast opcode is inferred from the
2320 // types and size of the operand. This, basically, is a parallel of the
2321 // logic in the castIsValid function below. This axiom should hold:
2322 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2323 // should not assert in castIsValid. In other words, this produces a "correct"
2324 // casting opcode for the arguments passed to it.
2325 // This routine must be kept in sync with isCastable.
2326 Instruction::CastOps
2327 CastInst::getCastOpcode(
2328 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2329 const Type *SrcTy = Src->getType();
2331 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2332 "Only first class types are castable!");
2334 if (SrcTy == DestTy)
2335 return BitCast;
2337 if (const VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2338 if (const VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2339 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2340 // An element by element cast. Find the appropriate opcode based on the
2341 // element types.
2342 SrcTy = SrcVecTy->getElementType();
2343 DestTy = DestVecTy->getElementType();
2346 // Get the bit sizes, we'll need these
2347 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2348 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2350 // Run through the possibilities ...
2351 if (DestTy->isIntegerTy()) { // Casting to integral
2352 if (SrcTy->isIntegerTy()) { // Casting from integral
2353 if (DestBits < SrcBits)
2354 return Trunc; // int -> smaller int
2355 else if (DestBits > SrcBits) { // its an extension
2356 if (SrcIsSigned)
2357 return SExt; // signed -> SEXT
2358 else
2359 return ZExt; // unsigned -> ZEXT
2360 } else {
2361 return BitCast; // Same size, No-op cast
2363 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2364 if (DestIsSigned)
2365 return FPToSI; // FP -> sint
2366 else
2367 return FPToUI; // FP -> uint
2368 } else if (SrcTy->isVectorTy()) {
2369 assert(DestBits == SrcBits &&
2370 "Casting vector to integer of different width");
2371 return BitCast; // Same size, no-op cast
2372 } else {
2373 assert(SrcTy->isPointerTy() &&
2374 "Casting from a value that is not first-class type");
2375 return PtrToInt; // ptr -> int
2377 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2378 if (SrcTy->isIntegerTy()) { // Casting from integral
2379 if (SrcIsSigned)
2380 return SIToFP; // sint -> FP
2381 else
2382 return UIToFP; // uint -> FP
2383 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2384 if (DestBits < SrcBits) {
2385 return FPTrunc; // FP -> smaller FP
2386 } else if (DestBits > SrcBits) {
2387 return FPExt; // FP -> larger FP
2388 } else {
2389 return BitCast; // same size, no-op cast
2391 } else if (SrcTy->isVectorTy()) {
2392 assert(DestBits == SrcBits &&
2393 "Casting vector to floating point of different width");
2394 return BitCast; // same size, no-op cast
2395 } else {
2396 llvm_unreachable("Casting pointer or non-first class to float");
2398 } else if (DestTy->isVectorTy()) {
2399 assert(DestBits == SrcBits &&
2400 "Illegal cast to vector (wrong type or size)");
2401 return BitCast;
2402 } else if (DestTy->isPointerTy()) {
2403 if (SrcTy->isPointerTy()) {
2404 return BitCast; // ptr -> ptr
2405 } else if (SrcTy->isIntegerTy()) {
2406 return IntToPtr; // int -> ptr
2407 } else {
2408 assert(!"Casting pointer to other than pointer or int");
2410 } else if (DestTy->isX86_MMXTy()) {
2411 if (SrcTy->isVectorTy()) {
2412 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2413 return BitCast; // 64-bit vector to MMX
2414 } else {
2415 assert(!"Illegal cast to X86_MMX");
2417 } else {
2418 assert(!"Casting to type that is not first-class");
2421 // If we fall through to here we probably hit an assertion cast above
2422 // and assertions are not turned on. Anything we return is an error, so
2423 // BitCast is as good a choice as any.
2424 return BitCast;
2427 //===----------------------------------------------------------------------===//
2428 // CastInst SubClass Constructors
2429 //===----------------------------------------------------------------------===//
2431 /// Check that the construction parameters for a CastInst are correct. This
2432 /// could be broken out into the separate constructors but it is useful to have
2433 /// it in one place and to eliminate the redundant code for getting the sizes
2434 /// of the types involved.
2435 bool
2436 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2438 // Check for type sanity on the arguments
2439 const Type *SrcTy = S->getType();
2440 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2441 SrcTy->isAggregateType() || DstTy->isAggregateType())
2442 return false;
2444 // Get the size of the types in bits, we'll need this later
2445 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2446 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2448 // If these are vector types, get the lengths of the vectors (using zero for
2449 // scalar types means that checking that vector lengths match also checks that
2450 // scalars are not being converted to vectors or vectors to scalars).
2451 unsigned SrcLength = SrcTy->isVectorTy() ?
2452 cast<VectorType>(SrcTy)->getNumElements() : 0;
2453 unsigned DstLength = DstTy->isVectorTy() ?
2454 cast<VectorType>(DstTy)->getNumElements() : 0;
2456 // Switch on the opcode provided
2457 switch (op) {
2458 default: return false; // This is an input error
2459 case Instruction::Trunc:
2460 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2461 SrcLength == DstLength && SrcBitSize > DstBitSize;
2462 case Instruction::ZExt:
2463 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2464 SrcLength == DstLength && SrcBitSize < DstBitSize;
2465 case Instruction::SExt:
2466 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2467 SrcLength == DstLength && SrcBitSize < DstBitSize;
2468 case Instruction::FPTrunc:
2469 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2470 SrcLength == DstLength && SrcBitSize > DstBitSize;
2471 case Instruction::FPExt:
2472 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2473 SrcLength == DstLength && SrcBitSize < DstBitSize;
2474 case Instruction::UIToFP:
2475 case Instruction::SIToFP:
2476 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2477 SrcLength == DstLength;
2478 case Instruction::FPToUI:
2479 case Instruction::FPToSI:
2480 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2481 SrcLength == DstLength;
2482 case Instruction::PtrToInt:
2483 return SrcTy->isPointerTy() && DstTy->isIntegerTy();
2484 case Instruction::IntToPtr:
2485 return SrcTy->isIntegerTy() && DstTy->isPointerTy();
2486 case Instruction::BitCast:
2487 // BitCast implies a no-op cast of type only. No bits change.
2488 // However, you can't cast pointers to anything but pointers.
2489 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2490 return false;
2492 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2493 // these cases, the cast is okay if the source and destination bit widths
2494 // are identical.
2495 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2499 TruncInst::TruncInst(
2500 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2501 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2502 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2505 TruncInst::TruncInst(
2506 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2507 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2508 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2511 ZExtInst::ZExtInst(
2512 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2513 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2514 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2517 ZExtInst::ZExtInst(
2518 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2519 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2520 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2522 SExtInst::SExtInst(
2523 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2524 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2525 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2528 SExtInst::SExtInst(
2529 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2530 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2531 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2534 FPTruncInst::FPTruncInst(
2535 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2536 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2537 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2540 FPTruncInst::FPTruncInst(
2541 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2542 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2543 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2546 FPExtInst::FPExtInst(
2547 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2548 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2549 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2552 FPExtInst::FPExtInst(
2553 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2554 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2555 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2558 UIToFPInst::UIToFPInst(
2559 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2560 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2561 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2564 UIToFPInst::UIToFPInst(
2565 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2566 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2567 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2570 SIToFPInst::SIToFPInst(
2571 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2572 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2573 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2576 SIToFPInst::SIToFPInst(
2577 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2578 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2579 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2582 FPToUIInst::FPToUIInst(
2583 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2584 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2585 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2588 FPToUIInst::FPToUIInst(
2589 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2590 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2591 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2594 FPToSIInst::FPToSIInst(
2595 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2596 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2597 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2600 FPToSIInst::FPToSIInst(
2601 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2602 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2603 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2606 PtrToIntInst::PtrToIntInst(
2607 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2608 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2609 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2612 PtrToIntInst::PtrToIntInst(
2613 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2614 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2615 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2618 IntToPtrInst::IntToPtrInst(
2619 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2620 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2621 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2624 IntToPtrInst::IntToPtrInst(
2625 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2626 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2627 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2630 BitCastInst::BitCastInst(
2631 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2632 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2633 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2636 BitCastInst::BitCastInst(
2637 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2638 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2639 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2642 //===----------------------------------------------------------------------===//
2643 // CmpInst Classes
2644 //===----------------------------------------------------------------------===//
2646 void CmpInst::Anchor() const {}
2648 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2649 Value *LHS, Value *RHS, const Twine &Name,
2650 Instruction *InsertBefore)
2651 : Instruction(ty, op,
2652 OperandTraits<CmpInst>::op_begin(this),
2653 OperandTraits<CmpInst>::operands(this),
2654 InsertBefore) {
2655 Op<0>() = LHS;
2656 Op<1>() = RHS;
2657 setPredicate((Predicate)predicate);
2658 setName(Name);
2661 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2662 Value *LHS, Value *RHS, const Twine &Name,
2663 BasicBlock *InsertAtEnd)
2664 : Instruction(ty, op,
2665 OperandTraits<CmpInst>::op_begin(this),
2666 OperandTraits<CmpInst>::operands(this),
2667 InsertAtEnd) {
2668 Op<0>() = LHS;
2669 Op<1>() = RHS;
2670 setPredicate((Predicate)predicate);
2671 setName(Name);
2674 CmpInst *
2675 CmpInst::Create(OtherOps Op, unsigned short predicate,
2676 Value *S1, Value *S2,
2677 const Twine &Name, Instruction *InsertBefore) {
2678 if (Op == Instruction::ICmp) {
2679 if (InsertBefore)
2680 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2681 S1, S2, Name);
2682 else
2683 return new ICmpInst(CmpInst::Predicate(predicate),
2684 S1, S2, Name);
2687 if (InsertBefore)
2688 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2689 S1, S2, Name);
2690 else
2691 return new FCmpInst(CmpInst::Predicate(predicate),
2692 S1, S2, Name);
2695 CmpInst *
2696 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2697 const Twine &Name, BasicBlock *InsertAtEnd) {
2698 if (Op == Instruction::ICmp) {
2699 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2700 S1, S2, Name);
2702 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2703 S1, S2, Name);
2706 void CmpInst::swapOperands() {
2707 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2708 IC->swapOperands();
2709 else
2710 cast<FCmpInst>(this)->swapOperands();
2713 bool CmpInst::isCommutative() const {
2714 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2715 return IC->isCommutative();
2716 return cast<FCmpInst>(this)->isCommutative();
2719 bool CmpInst::isEquality() const {
2720 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2721 return IC->isEquality();
2722 return cast<FCmpInst>(this)->isEquality();
2726 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2727 switch (pred) {
2728 default: assert(!"Unknown cmp predicate!");
2729 case ICMP_EQ: return ICMP_NE;
2730 case ICMP_NE: return ICMP_EQ;
2731 case ICMP_UGT: return ICMP_ULE;
2732 case ICMP_ULT: return ICMP_UGE;
2733 case ICMP_UGE: return ICMP_ULT;
2734 case ICMP_ULE: return ICMP_UGT;
2735 case ICMP_SGT: return ICMP_SLE;
2736 case ICMP_SLT: return ICMP_SGE;
2737 case ICMP_SGE: return ICMP_SLT;
2738 case ICMP_SLE: return ICMP_SGT;
2740 case FCMP_OEQ: return FCMP_UNE;
2741 case FCMP_ONE: return FCMP_UEQ;
2742 case FCMP_OGT: return FCMP_ULE;
2743 case FCMP_OLT: return FCMP_UGE;
2744 case FCMP_OGE: return FCMP_ULT;
2745 case FCMP_OLE: return FCMP_UGT;
2746 case FCMP_UEQ: return FCMP_ONE;
2747 case FCMP_UNE: return FCMP_OEQ;
2748 case FCMP_UGT: return FCMP_OLE;
2749 case FCMP_ULT: return FCMP_OGE;
2750 case FCMP_UGE: return FCMP_OLT;
2751 case FCMP_ULE: return FCMP_OGT;
2752 case FCMP_ORD: return FCMP_UNO;
2753 case FCMP_UNO: return FCMP_ORD;
2754 case FCMP_TRUE: return FCMP_FALSE;
2755 case FCMP_FALSE: return FCMP_TRUE;
2759 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2760 switch (pred) {
2761 default: assert(! "Unknown icmp predicate!");
2762 case ICMP_EQ: case ICMP_NE:
2763 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2764 return pred;
2765 case ICMP_UGT: return ICMP_SGT;
2766 case ICMP_ULT: return ICMP_SLT;
2767 case ICMP_UGE: return ICMP_SGE;
2768 case ICMP_ULE: return ICMP_SLE;
2772 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2773 switch (pred) {
2774 default: assert(! "Unknown icmp predicate!");
2775 case ICMP_EQ: case ICMP_NE:
2776 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2777 return pred;
2778 case ICMP_SGT: return ICMP_UGT;
2779 case ICMP_SLT: return ICMP_ULT;
2780 case ICMP_SGE: return ICMP_UGE;
2781 case ICMP_SLE: return ICMP_ULE;
2785 /// Initialize a set of values that all satisfy the condition with C.
2787 ConstantRange
2788 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2789 APInt Lower(C);
2790 APInt Upper(C);
2791 uint32_t BitWidth = C.getBitWidth();
2792 switch (pred) {
2793 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2794 case ICmpInst::ICMP_EQ: Upper++; break;
2795 case ICmpInst::ICMP_NE: Lower++; break;
2796 case ICmpInst::ICMP_ULT:
2797 Lower = APInt::getMinValue(BitWidth);
2798 // Check for an empty-set condition.
2799 if (Lower == Upper)
2800 return ConstantRange(BitWidth, /*isFullSet=*/false);
2801 break;
2802 case ICmpInst::ICMP_SLT:
2803 Lower = APInt::getSignedMinValue(BitWidth);
2804 // Check for an empty-set condition.
2805 if (Lower == Upper)
2806 return ConstantRange(BitWidth, /*isFullSet=*/false);
2807 break;
2808 case ICmpInst::ICMP_UGT:
2809 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2810 // Check for an empty-set condition.
2811 if (Lower == Upper)
2812 return ConstantRange(BitWidth, /*isFullSet=*/false);
2813 break;
2814 case ICmpInst::ICMP_SGT:
2815 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2816 // Check for an empty-set condition.
2817 if (Lower == Upper)
2818 return ConstantRange(BitWidth, /*isFullSet=*/false);
2819 break;
2820 case ICmpInst::ICMP_ULE:
2821 Lower = APInt::getMinValue(BitWidth); Upper++;
2822 // Check for a full-set condition.
2823 if (Lower == Upper)
2824 return ConstantRange(BitWidth, /*isFullSet=*/true);
2825 break;
2826 case ICmpInst::ICMP_SLE:
2827 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2828 // Check for a full-set condition.
2829 if (Lower == Upper)
2830 return ConstantRange(BitWidth, /*isFullSet=*/true);
2831 break;
2832 case ICmpInst::ICMP_UGE:
2833 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2834 // Check for a full-set condition.
2835 if (Lower == Upper)
2836 return ConstantRange(BitWidth, /*isFullSet=*/true);
2837 break;
2838 case ICmpInst::ICMP_SGE:
2839 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2840 // Check for a full-set condition.
2841 if (Lower == Upper)
2842 return ConstantRange(BitWidth, /*isFullSet=*/true);
2843 break;
2845 return ConstantRange(Lower, Upper);
2848 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2849 switch (pred) {
2850 default: assert(!"Unknown cmp predicate!");
2851 case ICMP_EQ: case ICMP_NE:
2852 return pred;
2853 case ICMP_SGT: return ICMP_SLT;
2854 case ICMP_SLT: return ICMP_SGT;
2855 case ICMP_SGE: return ICMP_SLE;
2856 case ICMP_SLE: return ICMP_SGE;
2857 case ICMP_UGT: return ICMP_ULT;
2858 case ICMP_ULT: return ICMP_UGT;
2859 case ICMP_UGE: return ICMP_ULE;
2860 case ICMP_ULE: return ICMP_UGE;
2862 case FCMP_FALSE: case FCMP_TRUE:
2863 case FCMP_OEQ: case FCMP_ONE:
2864 case FCMP_UEQ: case FCMP_UNE:
2865 case FCMP_ORD: case FCMP_UNO:
2866 return pred;
2867 case FCMP_OGT: return FCMP_OLT;
2868 case FCMP_OLT: return FCMP_OGT;
2869 case FCMP_OGE: return FCMP_OLE;
2870 case FCMP_OLE: return FCMP_OGE;
2871 case FCMP_UGT: return FCMP_ULT;
2872 case FCMP_ULT: return FCMP_UGT;
2873 case FCMP_UGE: return FCMP_ULE;
2874 case FCMP_ULE: return FCMP_UGE;
2878 bool CmpInst::isUnsigned(unsigned short predicate) {
2879 switch (predicate) {
2880 default: return false;
2881 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2882 case ICmpInst::ICMP_UGE: return true;
2886 bool CmpInst::isSigned(unsigned short predicate) {
2887 switch (predicate) {
2888 default: return false;
2889 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2890 case ICmpInst::ICMP_SGE: return true;
2894 bool CmpInst::isOrdered(unsigned short predicate) {
2895 switch (predicate) {
2896 default: return false;
2897 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2898 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2899 case FCmpInst::FCMP_ORD: return true;
2903 bool CmpInst::isUnordered(unsigned short predicate) {
2904 switch (predicate) {
2905 default: return false;
2906 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2907 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2908 case FCmpInst::FCMP_UNO: return true;
2912 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
2913 switch(predicate) {
2914 default: return false;
2915 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
2916 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
2920 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
2921 switch(predicate) {
2922 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
2923 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
2924 default: return false;
2929 //===----------------------------------------------------------------------===//
2930 // SwitchInst Implementation
2931 //===----------------------------------------------------------------------===//
2933 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
2934 assert(Value && Default && NumReserved);
2935 ReservedSpace = NumReserved;
2936 NumOperands = 2;
2937 OperandList = allocHungoffUses(ReservedSpace);
2939 OperandList[0] = Value;
2940 OperandList[1] = Default;
2943 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2944 /// switch on and a default destination. The number of additional cases can
2945 /// be specified here to make memory allocation more efficient. This
2946 /// constructor can also autoinsert before another instruction.
2947 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2948 Instruction *InsertBefore)
2949 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2950 0, 0, InsertBefore) {
2951 init(Value, Default, 2+NumCases*2);
2954 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2955 /// switch on and a default destination. The number of additional cases can
2956 /// be specified here to make memory allocation more efficient. This
2957 /// constructor also autoinserts at the end of the specified BasicBlock.
2958 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2959 BasicBlock *InsertAtEnd)
2960 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2961 0, 0, InsertAtEnd) {
2962 init(Value, Default, 2+NumCases*2);
2965 SwitchInst::SwitchInst(const SwitchInst &SI)
2966 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
2967 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
2968 NumOperands = SI.getNumOperands();
2969 Use *OL = OperandList, *InOL = SI.OperandList;
2970 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
2971 OL[i] = InOL[i];
2972 OL[i+1] = InOL[i+1];
2974 SubclassOptionalData = SI.SubclassOptionalData;
2977 SwitchInst::~SwitchInst() {
2978 dropHungoffUses();
2982 /// addCase - Add an entry to the switch instruction...
2984 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2985 unsigned OpNo = NumOperands;
2986 if (OpNo+2 > ReservedSpace)
2987 growOperands(); // Get more space!
2988 // Initialize some new operands.
2989 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2990 NumOperands = OpNo+2;
2991 OperandList[OpNo] = OnVal;
2992 OperandList[OpNo+1] = Dest;
2995 /// removeCase - This method removes the specified successor from the switch
2996 /// instruction. Note that this cannot be used to remove the default
2997 /// destination (successor #0).
2999 void SwitchInst::removeCase(unsigned idx) {
3000 assert(idx != 0 && "Cannot remove the default case!");
3001 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3003 unsigned NumOps = getNumOperands();
3004 Use *OL = OperandList;
3006 // Overwrite this case with the end of the list.
3007 if ((idx + 1) * 2 != NumOps) {
3008 OL[idx * 2] = OL[NumOps - 2];
3009 OL[idx * 2 + 1] = OL[NumOps - 1];
3012 // Nuke the last value.
3013 OL[NumOps-2].set(0);
3014 OL[NumOps-2+1].set(0);
3015 NumOperands = NumOps-2;
3018 /// growOperands - grow operands - This grows the operand list in response
3019 /// to a push_back style of operation. This grows the number of ops by 3 times.
3021 void SwitchInst::growOperands() {
3022 unsigned e = getNumOperands();
3023 unsigned NumOps = e*3;
3025 ReservedSpace = NumOps;
3026 Use *NewOps = allocHungoffUses(NumOps);
3027 Use *OldOps = OperandList;
3028 for (unsigned i = 0; i != e; ++i) {
3029 NewOps[i] = OldOps[i];
3031 OperandList = NewOps;
3032 Use::zap(OldOps, OldOps + e, true);
3036 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3037 return getSuccessor(idx);
3039 unsigned SwitchInst::getNumSuccessorsV() const {
3040 return getNumSuccessors();
3042 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3043 setSuccessor(idx, B);
3046 //===----------------------------------------------------------------------===//
3047 // IndirectBrInst Implementation
3048 //===----------------------------------------------------------------------===//
3050 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3051 assert(Address && Address->getType()->isPointerTy() &&
3052 "Address of indirectbr must be a pointer");
3053 ReservedSpace = 1+NumDests;
3054 NumOperands = 1;
3055 OperandList = allocHungoffUses(ReservedSpace);
3057 OperandList[0] = Address;
3061 /// growOperands - grow operands - This grows the operand list in response
3062 /// to a push_back style of operation. This grows the number of ops by 2 times.
3064 void IndirectBrInst::growOperands() {
3065 unsigned e = getNumOperands();
3066 unsigned NumOps = e*2;
3068 ReservedSpace = NumOps;
3069 Use *NewOps = allocHungoffUses(NumOps);
3070 Use *OldOps = OperandList;
3071 for (unsigned i = 0; i != e; ++i)
3072 NewOps[i] = OldOps[i];
3073 OperandList = NewOps;
3074 Use::zap(OldOps, OldOps + e, true);
3077 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3078 Instruction *InsertBefore)
3079 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3080 0, 0, InsertBefore) {
3081 init(Address, NumCases);
3084 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3085 BasicBlock *InsertAtEnd)
3086 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3087 0, 0, InsertAtEnd) {
3088 init(Address, NumCases);
3091 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3092 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3093 allocHungoffUses(IBI.getNumOperands()),
3094 IBI.getNumOperands()) {
3095 Use *OL = OperandList, *InOL = IBI.OperandList;
3096 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3097 OL[i] = InOL[i];
3098 SubclassOptionalData = IBI.SubclassOptionalData;
3101 IndirectBrInst::~IndirectBrInst() {
3102 dropHungoffUses();
3105 /// addDestination - Add a destination.
3107 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3108 unsigned OpNo = NumOperands;
3109 if (OpNo+1 > ReservedSpace)
3110 growOperands(); // Get more space!
3111 // Initialize some new operands.
3112 assert(OpNo < ReservedSpace && "Growing didn't work!");
3113 NumOperands = OpNo+1;
3114 OperandList[OpNo] = DestBB;
3117 /// removeDestination - This method removes the specified successor from the
3118 /// indirectbr instruction.
3119 void IndirectBrInst::removeDestination(unsigned idx) {
3120 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3122 unsigned NumOps = getNumOperands();
3123 Use *OL = OperandList;
3125 // Replace this value with the last one.
3126 OL[idx+1] = OL[NumOps-1];
3128 // Nuke the last value.
3129 OL[NumOps-1].set(0);
3130 NumOperands = NumOps-1;
3133 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3134 return getSuccessor(idx);
3136 unsigned IndirectBrInst::getNumSuccessorsV() const {
3137 return getNumSuccessors();
3139 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3140 setSuccessor(idx, B);
3143 //===----------------------------------------------------------------------===//
3144 // clone_impl() implementations
3145 //===----------------------------------------------------------------------===//
3147 // Define these methods here so vtables don't get emitted into every translation
3148 // unit that uses these classes.
3150 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3151 return new (getNumOperands()) GetElementPtrInst(*this);
3154 BinaryOperator *BinaryOperator::clone_impl() const {
3155 return Create(getOpcode(), Op<0>(), Op<1>());
3158 FCmpInst* FCmpInst::clone_impl() const {
3159 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3162 ICmpInst* ICmpInst::clone_impl() const {
3163 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3166 ExtractValueInst *ExtractValueInst::clone_impl() const {
3167 return new ExtractValueInst(*this);
3170 InsertValueInst *InsertValueInst::clone_impl() const {
3171 return new InsertValueInst(*this);
3174 AllocaInst *AllocaInst::clone_impl() const {
3175 return new AllocaInst(getAllocatedType(),
3176 (Value*)getOperand(0),
3177 getAlignment());
3180 LoadInst *LoadInst::clone_impl() const {
3181 return new LoadInst(getOperand(0),
3182 Twine(), isVolatile(),
3183 getAlignment());
3186 StoreInst *StoreInst::clone_impl() const {
3187 return new StoreInst(getOperand(0), getOperand(1),
3188 isVolatile(), getAlignment());
3191 TruncInst *TruncInst::clone_impl() const {
3192 return new TruncInst(getOperand(0), getType());
3195 ZExtInst *ZExtInst::clone_impl() const {
3196 return new ZExtInst(getOperand(0), getType());
3199 SExtInst *SExtInst::clone_impl() const {
3200 return new SExtInst(getOperand(0), getType());
3203 FPTruncInst *FPTruncInst::clone_impl() const {
3204 return new FPTruncInst(getOperand(0), getType());
3207 FPExtInst *FPExtInst::clone_impl() const {
3208 return new FPExtInst(getOperand(0), getType());
3211 UIToFPInst *UIToFPInst::clone_impl() const {
3212 return new UIToFPInst(getOperand(0), getType());
3215 SIToFPInst *SIToFPInst::clone_impl() const {
3216 return new SIToFPInst(getOperand(0), getType());
3219 FPToUIInst *FPToUIInst::clone_impl() const {
3220 return new FPToUIInst(getOperand(0), getType());
3223 FPToSIInst *FPToSIInst::clone_impl() const {
3224 return new FPToSIInst(getOperand(0), getType());
3227 PtrToIntInst *PtrToIntInst::clone_impl() const {
3228 return new PtrToIntInst(getOperand(0), getType());
3231 IntToPtrInst *IntToPtrInst::clone_impl() const {
3232 return new IntToPtrInst(getOperand(0), getType());
3235 BitCastInst *BitCastInst::clone_impl() const {
3236 return new BitCastInst(getOperand(0), getType());
3239 CallInst *CallInst::clone_impl() const {
3240 return new(getNumOperands()) CallInst(*this);
3243 SelectInst *SelectInst::clone_impl() const {
3244 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3247 VAArgInst *VAArgInst::clone_impl() const {
3248 return new VAArgInst(getOperand(0), getType());
3251 ExtractElementInst *ExtractElementInst::clone_impl() const {
3252 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3255 InsertElementInst *InsertElementInst::clone_impl() const {
3256 return InsertElementInst::Create(getOperand(0),
3257 getOperand(1),
3258 getOperand(2));
3261 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3262 return new ShuffleVectorInst(getOperand(0),
3263 getOperand(1),
3264 getOperand(2));
3267 PHINode *PHINode::clone_impl() const {
3268 return new PHINode(*this);
3271 ReturnInst *ReturnInst::clone_impl() const {
3272 return new(getNumOperands()) ReturnInst(*this);
3275 BranchInst *BranchInst::clone_impl() const {
3276 return new(getNumOperands()) BranchInst(*this);
3279 SwitchInst *SwitchInst::clone_impl() const {
3280 return new SwitchInst(*this);
3283 IndirectBrInst *IndirectBrInst::clone_impl() const {
3284 return new IndirectBrInst(*this);
3288 InvokeInst *InvokeInst::clone_impl() const {
3289 return new(getNumOperands()) InvokeInst(*this);
3292 UnwindInst *UnwindInst::clone_impl() const {
3293 LLVMContext &Context = getContext();
3294 return new UnwindInst(Context);
3297 UnreachableInst *UnreachableInst::clone_impl() const {
3298 LLVMContext &Context = getContext();
3299 return new UnreachableInst(Context);