1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Support/CallSite.h"
23 unsigned CallSite::getCallingConv() const {
24 if (CallInst *CI = dyn_cast<CallInst>(I))
25 return CI->getCallingConv();
27 return cast<InvokeInst>(I)->getCallingConv();
29 void CallSite::setCallingConv(unsigned CC) {
30 if (CallInst *CI = dyn_cast<CallInst>(I))
31 CI->setCallingConv(CC);
33 cast<InvokeInst>(I)->setCallingConv(CC);
39 //===----------------------------------------------------------------------===//
40 // TerminatorInst Class
41 //===----------------------------------------------------------------------===//
43 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
44 Use *Ops, unsigned NumOps, Instruction *IB)
45 : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IB) {
48 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
49 Use *Ops, unsigned NumOps, BasicBlock *IAE)
50 : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IAE) {
53 // Out of line virtual method, so the vtable, etc has a home.
54 TerminatorInst::~TerminatorInst() {
57 // Out of line virtual method, so the vtable, etc has a home.
58 UnaryInstruction::~UnaryInstruction() {
62 //===----------------------------------------------------------------------===//
64 //===----------------------------------------------------------------------===//
66 PHINode::PHINode(const PHINode &PN)
67 : Instruction(PN.getType(), Instruction::PHI,
68 new Use[PN.getNumOperands()], PN.getNumOperands()),
69 ReservedSpace(PN.getNumOperands()) {
70 Use *OL = OperandList;
71 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
72 OL[i].init(PN.getOperand(i), this);
73 OL[i+1].init(PN.getOperand(i+1), this);
78 delete [] OperandList;
81 // removeIncomingValue - Remove an incoming value. This is useful if a
82 // predecessor basic block is deleted.
83 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
84 unsigned NumOps = getNumOperands();
85 Use *OL = OperandList;
86 assert(Idx*2 < NumOps && "BB not in PHI node!");
87 Value *Removed = OL[Idx*2];
89 // Move everything after this operand down.
91 // FIXME: we could just swap with the end of the list, then erase. However,
92 // client might not expect this to happen. The code as it is thrashes the
93 // use/def lists, which is kinda lame.
94 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
99 // Nuke the last value.
101 OL[NumOps-2+1].set(0);
102 NumOperands = NumOps-2;
104 // If the PHI node is dead, because it has zero entries, nuke it now.
105 if (NumOps == 2 && DeletePHIIfEmpty) {
106 // If anyone is using this PHI, make them use a dummy value instead...
107 replaceAllUsesWith(UndefValue::get(getType()));
113 /// resizeOperands - resize operands - This adjusts the length of the operands
114 /// list according to the following behavior:
115 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
116 /// of operation. This grows the number of ops by 1.5 times.
117 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
118 /// 3. If NumOps == NumOperands, trim the reserved space.
120 void PHINode::resizeOperands(unsigned NumOps) {
122 NumOps = (getNumOperands())*3/2;
123 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
124 } else if (NumOps*2 > NumOperands) {
126 if (ReservedSpace >= NumOps) return;
127 } else if (NumOps == NumOperands) {
128 if (ReservedSpace == NumOps) return;
133 ReservedSpace = NumOps;
134 Use *NewOps = new Use[NumOps];
135 Use *OldOps = OperandList;
136 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
137 NewOps[i].init(OldOps[i], this);
141 OperandList = NewOps;
144 /// hasConstantValue - If the specified PHI node always merges together the same
145 /// value, return the value, otherwise return null.
147 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
148 // If the PHI node only has one incoming value, eliminate the PHI node...
149 if (getNumIncomingValues() == 1)
150 if (getIncomingValue(0) != this) // not X = phi X
151 return getIncomingValue(0);
153 return UndefValue::get(getType()); // Self cycle is dead.
155 // Otherwise if all of the incoming values are the same for the PHI, replace
156 // the PHI node with the incoming value.
159 bool HasUndefInput = false;
160 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
161 if (isa<UndefValue>(getIncomingValue(i)))
162 HasUndefInput = true;
163 else if (getIncomingValue(i) != this) // Not the PHI node itself...
164 if (InVal && getIncomingValue(i) != InVal)
165 return 0; // Not the same, bail out.
167 InVal = getIncomingValue(i);
169 // The only case that could cause InVal to be null is if we have a PHI node
170 // that only has entries for itself. In this case, there is no entry into the
171 // loop, so kill the PHI.
173 if (InVal == 0) InVal = UndefValue::get(getType());
175 // If we have a PHI node like phi(X, undef, X), where X is defined by some
176 // instruction, we cannot always return X as the result of the PHI node. Only
177 // do this if X is not an instruction (thus it must dominate the PHI block),
178 // or if the client is prepared to deal with this possibility.
179 if (HasUndefInput && !AllowNonDominatingInstruction)
180 if (Instruction *IV = dyn_cast<Instruction>(InVal))
181 // If it's in the entry block, it dominates everything.
182 if (IV->getParent() != &IV->getParent()->getParent()->front() ||
184 return 0; // Cannot guarantee that InVal dominates this PHINode.
186 // All of the incoming values are the same, return the value now.
191 //===----------------------------------------------------------------------===//
192 // CallInst Implementation
193 //===----------------------------------------------------------------------===//
195 CallInst::~CallInst() {
196 delete [] OperandList;
199 void CallInst::init(Value *Func, const std::vector<Value*> &Params) {
200 NumOperands = Params.size()+1;
201 Use *OL = OperandList = new Use[Params.size()+1];
202 OL[0].init(Func, this);
204 const FunctionType *FTy =
205 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
206 FTy = FTy; // silence warning.
208 assert((Params.size() == FTy->getNumParams() ||
209 (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
210 "Calling a function with bad signature!");
211 for (unsigned i = 0, e = Params.size(); i != e; ++i) {
212 assert((i >= FTy->getNumParams() ||
213 FTy->getParamType(i) == Params[i]->getType()) &&
214 "Calling a function with a bad signature!");
215 OL[i+1].init(Params[i], this);
219 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
221 Use *OL = OperandList = new Use[3];
222 OL[0].init(Func, this);
223 OL[1].init(Actual1, this);
224 OL[2].init(Actual2, this);
226 const FunctionType *FTy =
227 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
228 FTy = FTy; // silence warning.
230 assert((FTy->getNumParams() == 2 ||
231 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
232 "Calling a function with bad signature");
233 assert((0 >= FTy->getNumParams() ||
234 FTy->getParamType(0) == Actual1->getType()) &&
235 "Calling a function with a bad signature!");
236 assert((1 >= FTy->getNumParams() ||
237 FTy->getParamType(1) == Actual2->getType()) &&
238 "Calling a function with a bad signature!");
241 void CallInst::init(Value *Func, Value *Actual) {
243 Use *OL = OperandList = new Use[2];
244 OL[0].init(Func, this);
245 OL[1].init(Actual, this);
247 const FunctionType *FTy =
248 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
249 FTy = FTy; // silence warning.
251 assert((FTy->getNumParams() == 1 ||
252 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
253 "Calling a function with bad signature");
254 assert((0 == FTy->getNumParams() ||
255 FTy->getParamType(0) == Actual->getType()) &&
256 "Calling a function with a bad signature!");
259 void CallInst::init(Value *Func) {
261 Use *OL = OperandList = new Use[1];
262 OL[0].init(Func, this);
264 const FunctionType *FTy =
265 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
266 FTy = FTy; // silence warning.
268 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
271 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
272 const std::string &Name, Instruction *InsertBefore)
273 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
274 ->getElementType())->getReturnType(),
275 Instruction::Call, 0, 0, Name, InsertBefore) {
279 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
280 const std::string &Name, BasicBlock *InsertAtEnd)
281 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
282 ->getElementType())->getReturnType(),
283 Instruction::Call, 0, 0, Name, InsertAtEnd) {
287 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
288 const std::string &Name, Instruction *InsertBefore)
289 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
290 ->getElementType())->getReturnType(),
291 Instruction::Call, 0, 0, Name, InsertBefore) {
292 init(Func, Actual1, Actual2);
295 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
296 const std::string &Name, BasicBlock *InsertAtEnd)
297 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
298 ->getElementType())->getReturnType(),
299 Instruction::Call, 0, 0, Name, InsertAtEnd) {
300 init(Func, Actual1, Actual2);
303 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
304 Instruction *InsertBefore)
305 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
306 ->getElementType())->getReturnType(),
307 Instruction::Call, 0, 0, Name, InsertBefore) {
311 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
312 BasicBlock *InsertAtEnd)
313 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
314 ->getElementType())->getReturnType(),
315 Instruction::Call, 0, 0, Name, InsertAtEnd) {
319 CallInst::CallInst(Value *Func, const std::string &Name,
320 Instruction *InsertBefore)
321 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
322 ->getElementType())->getReturnType(),
323 Instruction::Call, 0, 0, Name, InsertBefore) {
327 CallInst::CallInst(Value *Func, const std::string &Name,
328 BasicBlock *InsertAtEnd)
329 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
330 ->getElementType())->getReturnType(),
331 Instruction::Call, 0, 0, Name, InsertAtEnd) {
335 CallInst::CallInst(const CallInst &CI)
336 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
337 CI.getNumOperands()) {
338 SubclassData = CI.SubclassData;
339 Use *OL = OperandList;
340 Use *InOL = CI.OperandList;
341 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
342 OL[i].init(InOL[i], this);
346 //===----------------------------------------------------------------------===//
347 // InvokeInst Implementation
348 //===----------------------------------------------------------------------===//
350 InvokeInst::~InvokeInst() {
351 delete [] OperandList;
354 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
355 const std::vector<Value*> &Params) {
356 NumOperands = 3+Params.size();
357 Use *OL = OperandList = new Use[3+Params.size()];
358 OL[0].init(Fn, this);
359 OL[1].init(IfNormal, this);
360 OL[2].init(IfException, this);
361 const FunctionType *FTy =
362 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
363 FTy = FTy; // silence warning.
365 assert((Params.size() == FTy->getNumParams()) ||
366 (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
367 "Calling a function with bad signature");
369 for (unsigned i = 0, e = Params.size(); i != e; i++) {
370 assert((i >= FTy->getNumParams() ||
371 FTy->getParamType(i) == Params[i]->getType()) &&
372 "Invoking a function with a bad signature!");
374 OL[i+3].init(Params[i], this);
378 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
379 BasicBlock *IfException,
380 const std::vector<Value*> &Params,
381 const std::string &Name, Instruction *InsertBefore)
382 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
383 ->getElementType())->getReturnType(),
384 Instruction::Invoke, 0, 0, Name, InsertBefore) {
385 init(Fn, IfNormal, IfException, Params);
388 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
389 BasicBlock *IfException,
390 const std::vector<Value*> &Params,
391 const std::string &Name, BasicBlock *InsertAtEnd)
392 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
393 ->getElementType())->getReturnType(),
394 Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
395 init(Fn, IfNormal, IfException, Params);
398 InvokeInst::InvokeInst(const InvokeInst &II)
399 : TerminatorInst(II.getType(), Instruction::Invoke,
400 new Use[II.getNumOperands()], II.getNumOperands()) {
401 SubclassData = II.SubclassData;
402 Use *OL = OperandList, *InOL = II.OperandList;
403 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
404 OL[i].init(InOL[i], this);
407 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
408 return getSuccessor(idx);
410 unsigned InvokeInst::getNumSuccessorsV() const {
411 return getNumSuccessors();
413 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
414 return setSuccessor(idx, B);
418 //===----------------------------------------------------------------------===//
419 // ReturnInst Implementation
420 //===----------------------------------------------------------------------===//
422 void ReturnInst::init(Value *retVal) {
423 if (retVal && retVal->getType() != Type::VoidTy) {
424 assert(!isa<BasicBlock>(retVal) &&
425 "Cannot return basic block. Probably using the incorrect ctor");
427 RetVal.init(retVal, this);
431 unsigned ReturnInst::getNumSuccessorsV() const {
432 return getNumSuccessors();
435 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
436 // emit the vtable for the class in this translation unit.
437 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
438 assert(0 && "ReturnInst has no successors!");
441 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
442 assert(0 && "ReturnInst has no successors!");
448 //===----------------------------------------------------------------------===//
449 // UnwindInst Implementation
450 //===----------------------------------------------------------------------===//
452 unsigned UnwindInst::getNumSuccessorsV() const {
453 return getNumSuccessors();
456 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
457 assert(0 && "UnwindInst has no successors!");
460 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
461 assert(0 && "UnwindInst has no successors!");
466 //===----------------------------------------------------------------------===//
467 // UnreachableInst Implementation
468 //===----------------------------------------------------------------------===//
470 unsigned UnreachableInst::getNumSuccessorsV() const {
471 return getNumSuccessors();
474 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
475 assert(0 && "UnwindInst has no successors!");
478 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
479 assert(0 && "UnwindInst has no successors!");
484 //===----------------------------------------------------------------------===//
485 // BranchInst Implementation
486 //===----------------------------------------------------------------------===//
488 void BranchInst::AssertOK() {
490 assert(getCondition()->getType() == Type::Int1Ty &&
491 "May only branch on boolean predicates!");
494 BranchInst::BranchInst(const BranchInst &BI) :
495 TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
496 OperandList[0].init(BI.getOperand(0), this);
497 if (BI.getNumOperands() != 1) {
498 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
499 OperandList[1].init(BI.getOperand(1), this);
500 OperandList[2].init(BI.getOperand(2), this);
504 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
505 return getSuccessor(idx);
507 unsigned BranchInst::getNumSuccessorsV() const {
508 return getNumSuccessors();
510 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
511 setSuccessor(idx, B);
515 //===----------------------------------------------------------------------===//
516 // AllocationInst Implementation
517 //===----------------------------------------------------------------------===//
519 static Value *getAISize(Value *Amt) {
521 Amt = ConstantInt::get(Type::Int32Ty, 1);
523 assert(!isa<BasicBlock>(Amt) &&
524 "Passed basic block into allocation size parameter! Ue other ctor");
525 assert(Amt->getType() == Type::Int32Ty &&
526 "Malloc/Allocation array size is not a 32-bit integer!");
531 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
532 unsigned Align, const std::string &Name,
533 Instruction *InsertBefore)
534 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
535 Name, InsertBefore), Alignment(Align) {
536 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
537 assert(Ty != Type::VoidTy && "Cannot allocate void!");
540 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
541 unsigned Align, const std::string &Name,
542 BasicBlock *InsertAtEnd)
543 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
544 Name, InsertAtEnd), Alignment(Align) {
545 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
546 assert(Ty != Type::VoidTy && "Cannot allocate void!");
549 // Out of line virtual method, so the vtable, etc has a home.
550 AllocationInst::~AllocationInst() {
553 bool AllocationInst::isArrayAllocation() const {
554 if (ConstantInt *CUI = dyn_cast<ConstantInt>(getOperand(0)))
555 return CUI->getZExtValue() != 1;
559 const Type *AllocationInst::getAllocatedType() const {
560 return getType()->getElementType();
563 AllocaInst::AllocaInst(const AllocaInst &AI)
564 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
565 Instruction::Alloca, AI.getAlignment()) {
568 MallocInst::MallocInst(const MallocInst &MI)
569 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
570 Instruction::Malloc, MI.getAlignment()) {
573 //===----------------------------------------------------------------------===//
574 // FreeInst Implementation
575 //===----------------------------------------------------------------------===//
577 void FreeInst::AssertOK() {
578 assert(isa<PointerType>(getOperand(0)->getType()) &&
579 "Can not free something of nonpointer type!");
582 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
583 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
587 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
588 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
593 //===----------------------------------------------------------------------===//
594 // LoadInst Implementation
595 //===----------------------------------------------------------------------===//
597 void LoadInst::AssertOK() {
598 assert(isa<PointerType>(getOperand(0)->getType()) &&
599 "Ptr must have pointer type.");
602 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
603 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
604 Load, Ptr, Name, InsertBef) {
609 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
610 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
611 Load, Ptr, Name, InsertAE) {
616 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
617 Instruction *InsertBef)
618 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
619 Load, Ptr, Name, InsertBef) {
620 setVolatile(isVolatile);
624 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
625 BasicBlock *InsertAE)
626 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
627 Load, Ptr, Name, InsertAE) {
628 setVolatile(isVolatile);
633 //===----------------------------------------------------------------------===//
634 // StoreInst Implementation
635 //===----------------------------------------------------------------------===//
637 void StoreInst::AssertOK() {
638 assert(isa<PointerType>(getOperand(1)->getType()) &&
639 "Ptr must have pointer type!");
640 assert(getOperand(0)->getType() ==
641 cast<PointerType>(getOperand(1)->getType())->getElementType()
642 && "Ptr must be a pointer to Val type!");
646 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
647 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
648 Ops[0].init(val, this);
649 Ops[1].init(addr, this);
654 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
655 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
656 Ops[0].init(val, this);
657 Ops[1].init(addr, this);
662 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
663 Instruction *InsertBefore)
664 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
665 Ops[0].init(val, this);
666 Ops[1].init(addr, this);
667 setVolatile(isVolatile);
671 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
672 BasicBlock *InsertAtEnd)
673 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
674 Ops[0].init(val, this);
675 Ops[1].init(addr, this);
676 setVolatile(isVolatile);
680 //===----------------------------------------------------------------------===//
681 // GetElementPtrInst Implementation
682 //===----------------------------------------------------------------------===//
684 // checkType - Simple wrapper function to give a better assertion failure
685 // message on bad indexes for a gep instruction.
687 static inline const Type *checkType(const Type *Ty) {
688 assert(Ty && "Invalid GetElementPtrInst indices for type!");
692 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
693 NumOperands = 1+NumIdx;
694 Use *OL = OperandList = new Use[NumOperands];
695 OL[0].init(Ptr, this);
697 for (unsigned i = 0; i != NumIdx; ++i)
698 OL[i+1].init(Idx[i], this);
701 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
703 Use *OL = OperandList = new Use[3];
704 OL[0].init(Ptr, this);
705 OL[1].init(Idx0, this);
706 OL[2].init(Idx1, this);
709 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
711 Use *OL = OperandList = new Use[2];
712 OL[0].init(Ptr, this);
713 OL[1].init(Idx, this);
716 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
717 const std::string &Name, Instruction *InBe)
718 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
721 GetElementPtr, 0, 0, Name, InBe) {
722 init(Ptr, &Idx[0], Idx.size());
725 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
726 const std::string &Name, BasicBlock *IAE)
727 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
730 GetElementPtr, 0, 0, Name, IAE) {
731 init(Ptr, &Idx[0], Idx.size());
734 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
736 const std::string &Name, Instruction *InBe)
737 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
738 Idx, NumIdx, true))),
739 GetElementPtr, 0, 0, Name, InBe) {
740 init(Ptr, Idx, NumIdx);
743 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value* const *Idx,
745 const std::string &Name, BasicBlock *IAE)
746 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
747 Idx, NumIdx, true))),
748 GetElementPtr, 0, 0, Name, IAE) {
749 init(Ptr, Idx, NumIdx);
752 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
753 const std::string &Name, Instruction *InBe)
754 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
756 GetElementPtr, 0, 0, Name, InBe) {
760 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
761 const std::string &Name, BasicBlock *IAE)
762 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
764 GetElementPtr, 0, 0, Name, IAE) {
768 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
769 const std::string &Name, Instruction *InBe)
770 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
772 GetElementPtr, 0, 0, Name, InBe) {
773 init(Ptr, Idx0, Idx1);
776 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
777 const std::string &Name, BasicBlock *IAE)
778 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
780 GetElementPtr, 0, 0, Name, IAE) {
781 init(Ptr, Idx0, Idx1);
784 GetElementPtrInst::~GetElementPtrInst() {
785 delete[] OperandList;
788 // getIndexedType - Returns the type of the element that would be loaded with
789 // a load instruction with the specified parameters.
791 // A null type is returned if the indices are invalid for the specified
794 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
797 bool AllowCompositeLeaf) {
798 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
800 // Handle the special case of the empty set index set...
802 if (AllowCompositeLeaf ||
803 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
804 return cast<PointerType>(Ptr)->getElementType();
809 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
810 if (NumIdx == CurIdx) {
811 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
812 return 0; // Can't load a whole structure or array!?!?
815 Value *Index = Idxs[CurIdx++];
816 if (isa<PointerType>(CT) && CurIdx != 1)
817 return 0; // Can only index into pointer types at the first index!
818 if (!CT->indexValid(Index)) return 0;
819 Ptr = CT->getTypeAtIndex(Index);
821 // If the new type forwards to another type, then it is in the middle
822 // of being refined to another type (and hence, may have dropped all
823 // references to what it was using before). So, use the new forwarded
825 if (const Type * Ty = Ptr->getForwardedType()) {
829 return CurIdx == NumIdx ? Ptr : 0;
832 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
833 Value *Idx0, Value *Idx1,
834 bool AllowCompositeLeaf) {
835 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
836 if (!PTy) return 0; // Type isn't a pointer type!
838 // Check the pointer index.
839 if (!PTy->indexValid(Idx0)) return 0;
841 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
842 if (!CT || !CT->indexValid(Idx1)) return 0;
844 const Type *ElTy = CT->getTypeAtIndex(Idx1);
845 if (AllowCompositeLeaf || ElTy->isFirstClassType())
850 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
851 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
852 if (!PTy) return 0; // Type isn't a pointer type!
854 // Check the pointer index.
855 if (!PTy->indexValid(Idx)) return 0;
857 return PTy->getElementType();
860 //===----------------------------------------------------------------------===//
861 // ExtractElementInst Implementation
862 //===----------------------------------------------------------------------===//
864 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
865 const std::string &Name,
866 Instruction *InsertBef)
867 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
868 ExtractElement, Ops, 2, Name, InsertBef) {
869 assert(isValidOperands(Val, Index) &&
870 "Invalid extractelement instruction operands!");
871 Ops[0].init(Val, this);
872 Ops[1].init(Index, this);
875 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
876 const std::string &Name,
877 Instruction *InsertBef)
878 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
879 ExtractElement, Ops, 2, Name, InsertBef) {
880 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
881 assert(isValidOperands(Val, Index) &&
882 "Invalid extractelement instruction operands!");
883 Ops[0].init(Val, this);
884 Ops[1].init(Index, this);
888 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
889 const std::string &Name,
890 BasicBlock *InsertAE)
891 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
892 ExtractElement, Ops, 2, Name, InsertAE) {
893 assert(isValidOperands(Val, Index) &&
894 "Invalid extractelement instruction operands!");
896 Ops[0].init(Val, this);
897 Ops[1].init(Index, this);
900 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
901 const std::string &Name,
902 BasicBlock *InsertAE)
903 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
904 ExtractElement, Ops, 2, Name, InsertAE) {
905 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
906 assert(isValidOperands(Val, Index) &&
907 "Invalid extractelement instruction operands!");
909 Ops[0].init(Val, this);
910 Ops[1].init(Index, this);
914 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
915 if (!isa<PackedType>(Val->getType()) || Index->getType() != Type::Int32Ty)
921 //===----------------------------------------------------------------------===//
922 // InsertElementInst Implementation
923 //===----------------------------------------------------------------------===//
925 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
926 : Instruction(IE.getType(), InsertElement, Ops, 3) {
927 Ops[0].init(IE.Ops[0], this);
928 Ops[1].init(IE.Ops[1], this);
929 Ops[2].init(IE.Ops[2], this);
931 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
932 const std::string &Name,
933 Instruction *InsertBef)
934 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
935 assert(isValidOperands(Vec, Elt, Index) &&
936 "Invalid insertelement instruction operands!");
937 Ops[0].init(Vec, this);
938 Ops[1].init(Elt, this);
939 Ops[2].init(Index, this);
942 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
943 const std::string &Name,
944 Instruction *InsertBef)
945 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
946 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
947 assert(isValidOperands(Vec, Elt, Index) &&
948 "Invalid insertelement instruction operands!");
949 Ops[0].init(Vec, this);
950 Ops[1].init(Elt, this);
951 Ops[2].init(Index, this);
955 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
956 const std::string &Name,
957 BasicBlock *InsertAE)
958 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
959 assert(isValidOperands(Vec, Elt, Index) &&
960 "Invalid insertelement instruction operands!");
962 Ops[0].init(Vec, this);
963 Ops[1].init(Elt, this);
964 Ops[2].init(Index, this);
967 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
968 const std::string &Name,
969 BasicBlock *InsertAE)
970 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
971 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
972 assert(isValidOperands(Vec, Elt, Index) &&
973 "Invalid insertelement instruction operands!");
975 Ops[0].init(Vec, this);
976 Ops[1].init(Elt, this);
977 Ops[2].init(Index, this);
980 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
981 const Value *Index) {
982 if (!isa<PackedType>(Vec->getType()))
983 return false; // First operand of insertelement must be packed type.
985 if (Elt->getType() != cast<PackedType>(Vec->getType())->getElementType())
986 return false;// Second operand of insertelement must be packed element type.
988 if (Index->getType() != Type::Int32Ty)
989 return false; // Third operand of insertelement must be uint.
994 //===----------------------------------------------------------------------===//
995 // ShuffleVectorInst Implementation
996 //===----------------------------------------------------------------------===//
998 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
999 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1000 Ops[0].init(SV.Ops[0], this);
1001 Ops[1].init(SV.Ops[1], this);
1002 Ops[2].init(SV.Ops[2], this);
1005 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1006 const std::string &Name,
1007 Instruction *InsertBefore)
1008 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertBefore) {
1009 assert(isValidOperands(V1, V2, Mask) &&
1010 "Invalid shuffle vector instruction operands!");
1011 Ops[0].init(V1, this);
1012 Ops[1].init(V2, this);
1013 Ops[2].init(Mask, this);
1016 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1017 const std::string &Name,
1018 BasicBlock *InsertAtEnd)
1019 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertAtEnd) {
1020 assert(isValidOperands(V1, V2, Mask) &&
1021 "Invalid shuffle vector instruction operands!");
1023 Ops[0].init(V1, this);
1024 Ops[1].init(V2, this);
1025 Ops[2].init(Mask, this);
1028 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1029 const Value *Mask) {
1030 if (!isa<PackedType>(V1->getType())) return false;
1031 if (V1->getType() != V2->getType()) return false;
1032 if (!isa<PackedType>(Mask->getType()) ||
1033 cast<PackedType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1034 cast<PackedType>(Mask->getType())->getNumElements() !=
1035 cast<PackedType>(V1->getType())->getNumElements())
1041 //===----------------------------------------------------------------------===//
1042 // BinaryOperator Class
1043 //===----------------------------------------------------------------------===//
1045 void BinaryOperator::init(BinaryOps iType)
1047 Value *LHS = getOperand(0), *RHS = getOperand(1);
1048 LHS = LHS; RHS = RHS; // Silence warnings.
1049 assert(LHS->getType() == RHS->getType() &&
1050 "Binary operator operand types must match!");
1055 assert(getType() == LHS->getType() &&
1056 "Arithmetic operation should return same type as operands!");
1057 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1058 isa<PackedType>(getType())) &&
1059 "Tried to create an arithmetic operation on a non-arithmetic type!");
1063 assert(getType() == LHS->getType() &&
1064 "Arithmetic operation should return same type as operands!");
1065 assert((getType()->isInteger() || (isa<PackedType>(getType()) &&
1066 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1067 "Incorrect operand type (not integer) for S/UDIV");
1070 assert(getType() == LHS->getType() &&
1071 "Arithmetic operation should return same type as operands!");
1072 assert((getType()->isFloatingPoint() || (isa<PackedType>(getType()) &&
1073 cast<PackedType>(getType())->getElementType()->isFloatingPoint()))
1074 && "Incorrect operand type (not floating point) for FDIV");
1078 assert(getType() == LHS->getType() &&
1079 "Arithmetic operation should return same type as operands!");
1080 assert((getType()->isInteger() || (isa<PackedType>(getType()) &&
1081 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1082 "Incorrect operand type (not integer) for S/UREM");
1085 assert(getType() == LHS->getType() &&
1086 "Arithmetic operation should return same type as operands!");
1087 assert((getType()->isFloatingPoint() || (isa<PackedType>(getType()) &&
1088 cast<PackedType>(getType())->getElementType()->isFloatingPoint()))
1089 && "Incorrect operand type (not floating point) for FREM");
1093 assert(getType() == LHS->getType() &&
1094 "Logical operation should return same type as operands!");
1095 assert((getType()->isInteger() ||
1096 (isa<PackedType>(getType()) &&
1097 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1098 "Tried to create a logical operation on a non-integral type!");
1106 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1107 const std::string &Name,
1108 Instruction *InsertBefore) {
1109 assert(S1->getType() == S2->getType() &&
1110 "Cannot create binary operator with two operands of differing type!");
1111 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1114 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1115 const std::string &Name,
1116 BasicBlock *InsertAtEnd) {
1117 BinaryOperator *Res = create(Op, S1, S2, Name);
1118 InsertAtEnd->getInstList().push_back(Res);
1122 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1123 Instruction *InsertBefore) {
1124 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1125 return new BinaryOperator(Instruction::Sub,
1127 Op->getType(), Name, InsertBefore);
1130 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1131 BasicBlock *InsertAtEnd) {
1132 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1133 return new BinaryOperator(Instruction::Sub,
1135 Op->getType(), Name, InsertAtEnd);
1138 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1139 Instruction *InsertBefore) {
1141 if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
1142 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1143 C = ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), C));
1145 C = ConstantInt::getAllOnesValue(Op->getType());
1148 return new BinaryOperator(Instruction::Xor, Op, C,
1149 Op->getType(), Name, InsertBefore);
1152 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1153 BasicBlock *InsertAtEnd) {
1155 if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
1156 // Create a vector of all ones values.
1157 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1159 ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1161 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1164 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1165 Op->getType(), Name, InsertAtEnd);
1169 // isConstantAllOnes - Helper function for several functions below
1170 static inline bool isConstantAllOnes(const Value *V) {
1171 return isa<ConstantInt>(V) &&cast<ConstantInt>(V)->isAllOnesValue();
1174 bool BinaryOperator::isNeg(const Value *V) {
1175 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1176 if (Bop->getOpcode() == Instruction::Sub)
1177 return Bop->getOperand(0) ==
1178 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1182 bool BinaryOperator::isNot(const Value *V) {
1183 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1184 return (Bop->getOpcode() == Instruction::Xor &&
1185 (isConstantAllOnes(Bop->getOperand(1)) ||
1186 isConstantAllOnes(Bop->getOperand(0))));
1190 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1191 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1192 return cast<BinaryOperator>(BinOp)->getOperand(1);
1195 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1196 return getNegArgument(const_cast<Value*>(BinOp));
1199 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1200 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1201 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1202 Value *Op0 = BO->getOperand(0);
1203 Value *Op1 = BO->getOperand(1);
1204 if (isConstantAllOnes(Op0)) return Op1;
1206 assert(isConstantAllOnes(Op1));
1210 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1211 return getNotArgument(const_cast<Value*>(BinOp));
1215 // swapOperands - Exchange the two operands to this instruction. This
1216 // instruction is safe to use on any binary instruction and does not
1217 // modify the semantics of the instruction. If the instruction is
1218 // order dependent (SetLT f.e.) the opcode is changed.
1220 bool BinaryOperator::swapOperands() {
1221 if (!isCommutative())
1222 return true; // Can't commute operands
1223 std::swap(Ops[0], Ops[1]);
1227 //===----------------------------------------------------------------------===//
1229 //===----------------------------------------------------------------------===//
1231 // Just determine if this cast only deals with integral->integral conversion.
1232 bool CastInst::isIntegerCast() const {
1233 switch (getOpcode()) {
1234 default: return false;
1235 case Instruction::ZExt:
1236 case Instruction::SExt:
1237 case Instruction::Trunc:
1239 case Instruction::BitCast:
1240 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1244 bool CastInst::isLosslessCast() const {
1245 // Only BitCast can be lossless, exit fast if we're not BitCast
1246 if (getOpcode() != Instruction::BitCast)
1249 // Identity cast is always lossless
1250 const Type* SrcTy = getOperand(0)->getType();
1251 const Type* DstTy = getType();
1255 // Pointer to pointer is always lossless.
1256 if (isa<PointerType>(SrcTy))
1257 return isa<PointerType>(DstTy);
1258 return false; // Other types have no identity values
1261 /// This function determines if the CastInst does not require any bits to be
1262 /// changed in order to effect the cast. Essentially, it identifies cases where
1263 /// no code gen is necessary for the cast, hence the name no-op cast. For
1264 /// example, the following are all no-op casts:
1265 /// # bitcast uint %X, int
1266 /// # bitcast uint* %x, sbyte*
1267 /// # bitcast packed< 2 x int > %x, packed< 4 x short>
1268 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1269 /// @brief Determine if a cast is a no-op.
1270 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1271 switch (getOpcode()) {
1273 assert(!"Invalid CastOp");
1274 case Instruction::Trunc:
1275 case Instruction::ZExt:
1276 case Instruction::SExt:
1277 case Instruction::FPTrunc:
1278 case Instruction::FPExt:
1279 case Instruction::UIToFP:
1280 case Instruction::SIToFP:
1281 case Instruction::FPToUI:
1282 case Instruction::FPToSI:
1283 return false; // These always modify bits
1284 case Instruction::BitCast:
1285 return true; // BitCast never modifies bits.
1286 case Instruction::PtrToInt:
1287 return IntPtrTy->getPrimitiveSizeInBits() ==
1288 getType()->getPrimitiveSizeInBits();
1289 case Instruction::IntToPtr:
1290 return IntPtrTy->getPrimitiveSizeInBits() ==
1291 getOperand(0)->getType()->getPrimitiveSizeInBits();
1295 /// This function determines if a pair of casts can be eliminated and what
1296 /// opcode should be used in the elimination. This assumes that there are two
1297 /// instructions like this:
1298 /// * %F = firstOpcode SrcTy %x to MidTy
1299 /// * %S = secondOpcode MidTy %F to DstTy
1300 /// The function returns a resultOpcode so these two casts can be replaced with:
1301 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1302 /// If no such cast is permited, the function returns 0.
1303 unsigned CastInst::isEliminableCastPair(
1304 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1305 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1307 // Define the 144 possibilities for these two cast instructions. The values
1308 // in this matrix determine what to do in a given situation and select the
1309 // case in the switch below. The rows correspond to firstOp, the columns
1310 // correspond to secondOp. In looking at the table below, keep in mind
1311 // the following cast properties:
1313 // Size Compare Source Destination
1314 // Operator Src ? Size Type Sign Type Sign
1315 // -------- ------------ ------------------- ---------------------
1316 // TRUNC > Integer Any Integral Any
1317 // ZEXT < Integral Unsigned Integer Any
1318 // SEXT < Integral Signed Integer Any
1319 // FPTOUI n/a FloatPt n/a Integral Unsigned
1320 // FPTOSI n/a FloatPt n/a Integral Signed
1321 // UITOFP n/a Integral Unsigned FloatPt n/a
1322 // SITOFP n/a Integral Signed FloatPt n/a
1323 // FPTRUNC > FloatPt n/a FloatPt n/a
1324 // FPEXT < FloatPt n/a FloatPt n/a
1325 // PTRTOINT n/a Pointer n/a Integral Unsigned
1326 // INTTOPTR n/a Integral Unsigned Pointer n/a
1327 // BITCONVERT = FirstClass n/a FirstClass n/a
1329 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1330 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1331 // into "fptoui double to ulong", but this loses information about the range
1332 // of the produced value (we no longer know the top-part is all zeros).
1333 // Further this conversion is often much more expensive for typical hardware,
1334 // and causes issues when building libgcc. We disallow fptosi+sext for the
1336 const unsigned numCastOps =
1337 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1338 static const uint8_t CastResults[numCastOps][numCastOps] = {
1339 // T F F U S F F P I B -+
1340 // R Z S P P I I T P 2 N T |
1341 // U E E 2 2 2 2 R E I T C +- secondOp
1342 // N X X U S F F N X N 2 V |
1343 // C T T I I P P C T T P T -+
1344 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1345 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1346 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1347 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1348 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1349 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1350 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1351 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1352 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1353 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1354 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1355 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1358 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1359 [secondOp-Instruction::CastOpsBegin];
1362 // categorically disallowed
1365 // allowed, use first cast's opcode
1368 // allowed, use second cast's opcode
1371 // no-op cast in second op implies firstOp as long as the DestTy
1373 if (DstTy->isInteger())
1377 // no-op cast in second op implies firstOp as long as the DestTy
1378 // is floating point
1379 if (DstTy->isFloatingPoint())
1383 // no-op cast in first op implies secondOp as long as the SrcTy
1385 if (SrcTy->isInteger())
1389 // no-op cast in first op implies secondOp as long as the SrcTy
1390 // is a floating point
1391 if (SrcTy->isFloatingPoint())
1395 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1396 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1397 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1398 if (MidSize >= PtrSize)
1399 return Instruction::BitCast;
1403 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1404 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1405 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1406 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1407 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1408 if (SrcSize == DstSize)
1409 return Instruction::BitCast;
1410 else if (SrcSize < DstSize)
1414 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1415 return Instruction::ZExt;
1417 // fpext followed by ftrunc is allowed if the bit size returned to is
1418 // the same as the original, in which case its just a bitcast
1420 return Instruction::BitCast;
1421 return 0; // If the types are not the same we can't eliminate it.
1423 // bitcast followed by ptrtoint is allowed as long as the bitcast
1424 // is a pointer to pointer cast.
1425 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1429 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1430 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1434 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1435 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1436 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1437 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1438 if (SrcSize <= PtrSize && SrcSize == DstSize)
1439 return Instruction::BitCast;
1443 // cast combination can't happen (error in input). This is for all cases
1444 // where the MidTy is not the same for the two cast instructions.
1445 assert(!"Invalid Cast Combination");
1448 assert(!"Error in CastResults table!!!");
1454 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1455 const std::string &Name, Instruction *InsertBefore) {
1456 // Construct and return the appropriate CastInst subclass
1458 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1459 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1460 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1461 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1462 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1463 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1464 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1465 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1466 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1467 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1468 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1469 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1471 assert(!"Invalid opcode provided");
1476 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1477 const std::string &Name, BasicBlock *InsertAtEnd) {
1478 // Construct and return the appropriate CastInst subclass
1480 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1481 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1482 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1483 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1484 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1485 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1486 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1487 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1488 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1489 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1490 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1491 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1493 assert(!"Invalid opcode provided");
1498 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1499 const std::string &Name,
1500 Instruction *InsertBefore) {
1501 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1502 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1503 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1506 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1507 const std::string &Name,
1508 BasicBlock *InsertAtEnd) {
1509 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1510 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1511 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1514 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1515 const std::string &Name,
1516 Instruction *InsertBefore) {
1517 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1518 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1519 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1522 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1523 const std::string &Name,
1524 BasicBlock *InsertAtEnd) {
1525 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1526 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1527 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1530 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1531 const std::string &Name,
1532 Instruction *InsertBefore) {
1533 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1534 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1535 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1538 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1539 const std::string &Name,
1540 BasicBlock *InsertAtEnd) {
1541 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1542 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1543 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1546 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1547 const std::string &Name,
1548 BasicBlock *InsertAtEnd) {
1549 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1550 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1553 if (Ty->isInteger())
1554 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1555 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1558 /// @brief Create a BitCast or a PtrToInt cast instruction
1559 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1560 const std::string &Name,
1561 Instruction *InsertBefore) {
1562 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1563 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1566 if (Ty->isInteger())
1567 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1568 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1571 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1572 bool isSigned, const std::string &Name,
1573 Instruction *InsertBefore) {
1574 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1575 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1576 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1577 Instruction::CastOps opcode =
1578 (SrcBits == DstBits ? Instruction::BitCast :
1579 (SrcBits > DstBits ? Instruction::Trunc :
1580 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1581 return create(opcode, C, Ty, Name, InsertBefore);
1584 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1585 bool isSigned, const std::string &Name,
1586 BasicBlock *InsertAtEnd) {
1587 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1588 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1589 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1590 Instruction::CastOps opcode =
1591 (SrcBits == DstBits ? Instruction::BitCast :
1592 (SrcBits > DstBits ? Instruction::Trunc :
1593 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1594 return create(opcode, C, Ty, Name, InsertAtEnd);
1597 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1598 const std::string &Name,
1599 Instruction *InsertBefore) {
1600 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1602 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1603 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1604 Instruction::CastOps opcode =
1605 (SrcBits == DstBits ? Instruction::BitCast :
1606 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1607 return create(opcode, C, Ty, Name, InsertBefore);
1610 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1611 const std::string &Name,
1612 BasicBlock *InsertAtEnd) {
1613 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1615 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1616 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1617 Instruction::CastOps opcode =
1618 (SrcBits == DstBits ? Instruction::BitCast :
1619 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1620 return create(opcode, C, Ty, Name, InsertAtEnd);
1623 // Provide a way to get a "cast" where the cast opcode is inferred from the
1624 // types and size of the operand. This, basically, is a parallel of the
1625 // logic in the castIsValid function below. This axiom should hold:
1626 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1627 // should not assert in castIsValid. In other words, this produces a "correct"
1628 // casting opcode for the arguments passed to it.
1629 Instruction::CastOps
1630 CastInst::getCastOpcode(
1631 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1632 // Get the bit sizes, we'll need these
1633 const Type *SrcTy = Src->getType();
1634 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1635 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1637 // Run through the possibilities ...
1638 if (DestTy->isInteger()) { // Casting to integral
1639 if (SrcTy->isInteger()) { // Casting from integral
1640 if (DestBits < SrcBits)
1641 return Trunc; // int -> smaller int
1642 else if (DestBits > SrcBits) { // its an extension
1644 return SExt; // signed -> SEXT
1646 return ZExt; // unsigned -> ZEXT
1648 return BitCast; // Same size, No-op cast
1650 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1652 return FPToSI; // FP -> sint
1654 return FPToUI; // FP -> uint
1655 } else if (const PackedType *PTy = dyn_cast<PackedType>(SrcTy)) {
1656 assert(DestBits == PTy->getBitWidth() &&
1657 "Casting packed to integer of different width");
1658 return BitCast; // Same size, no-op cast
1660 assert(isa<PointerType>(SrcTy) &&
1661 "Casting from a value that is not first-class type");
1662 return PtrToInt; // ptr -> int
1664 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1665 if (SrcTy->isInteger()) { // Casting from integral
1667 return SIToFP; // sint -> FP
1669 return UIToFP; // uint -> FP
1670 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1671 if (DestBits < SrcBits) {
1672 return FPTrunc; // FP -> smaller FP
1673 } else if (DestBits > SrcBits) {
1674 return FPExt; // FP -> larger FP
1676 return BitCast; // same size, no-op cast
1678 } else if (const PackedType *PTy = dyn_cast<PackedType>(SrcTy)) {
1679 assert(DestBits == PTy->getBitWidth() &&
1680 "Casting packed to floating point of different width");
1681 return BitCast; // same size, no-op cast
1683 assert(0 && "Casting pointer or non-first class to float");
1685 } else if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
1686 if (const PackedType *SrcPTy = dyn_cast<PackedType>(SrcTy)) {
1687 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1688 "Casting packed to packed of different widths");
1689 return BitCast; // packed -> packed
1690 } else if (DestPTy->getBitWidth() == SrcBits) {
1691 return BitCast; // float/int -> packed
1693 assert(!"Illegal cast to packed (wrong type or size)");
1695 } else if (isa<PointerType>(DestTy)) {
1696 if (isa<PointerType>(SrcTy)) {
1697 return BitCast; // ptr -> ptr
1698 } else if (SrcTy->isInteger()) {
1699 return IntToPtr; // int -> ptr
1701 assert(!"Casting pointer to other than pointer or int");
1704 assert(!"Casting to type that is not first-class");
1707 // If we fall through to here we probably hit an assertion cast above
1708 // and assertions are not turned on. Anything we return is an error, so
1709 // BitCast is as good a choice as any.
1713 //===----------------------------------------------------------------------===//
1714 // CastInst SubClass Constructors
1715 //===----------------------------------------------------------------------===//
1717 /// Check that the construction parameters for a CastInst are correct. This
1718 /// could be broken out into the separate constructors but it is useful to have
1719 /// it in one place and to eliminate the redundant code for getting the sizes
1720 /// of the types involved.
1722 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1724 // Check for type sanity on the arguments
1725 const Type *SrcTy = S->getType();
1726 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1729 // Get the size of the types in bits, we'll need this later
1730 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1731 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1733 // Switch on the opcode provided
1735 default: return false; // This is an input error
1736 case Instruction::Trunc:
1737 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1738 case Instruction::ZExt:
1739 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1740 case Instruction::SExt:
1741 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1742 case Instruction::FPTrunc:
1743 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1744 SrcBitSize > DstBitSize;
1745 case Instruction::FPExt:
1746 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1747 SrcBitSize < DstBitSize;
1748 case Instruction::UIToFP:
1749 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1750 case Instruction::SIToFP:
1751 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1752 case Instruction::FPToUI:
1753 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1754 case Instruction::FPToSI:
1755 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1756 case Instruction::PtrToInt:
1757 return isa<PointerType>(SrcTy) && DstTy->isInteger();
1758 case Instruction::IntToPtr:
1759 return SrcTy->isInteger() && isa<PointerType>(DstTy);
1760 case Instruction::BitCast:
1761 // BitCast implies a no-op cast of type only. No bits change.
1762 // However, you can't cast pointers to anything but pointers.
1763 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
1766 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
1767 // these cases, the cast is okay if the source and destination bit widths
1769 return SrcBitSize == DstBitSize;
1773 TruncInst::TruncInst(
1774 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1775 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
1776 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1779 TruncInst::TruncInst(
1780 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1781 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
1782 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1786 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1787 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
1788 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1792 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1793 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
1794 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1797 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1798 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
1799 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
1803 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1804 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
1805 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
1808 FPTruncInst::FPTruncInst(
1809 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1810 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
1811 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
1814 FPTruncInst::FPTruncInst(
1815 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1816 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
1817 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
1820 FPExtInst::FPExtInst(
1821 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1822 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
1823 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
1826 FPExtInst::FPExtInst(
1827 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1828 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
1829 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
1832 UIToFPInst::UIToFPInst(
1833 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1834 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
1835 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
1838 UIToFPInst::UIToFPInst(
1839 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1840 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
1841 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
1844 SIToFPInst::SIToFPInst(
1845 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1846 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
1847 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
1850 SIToFPInst::SIToFPInst(
1851 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1852 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
1853 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
1856 FPToUIInst::FPToUIInst(
1857 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1858 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
1859 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
1862 FPToUIInst::FPToUIInst(
1863 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1864 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
1865 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
1868 FPToSIInst::FPToSIInst(
1869 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1870 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
1871 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
1874 FPToSIInst::FPToSIInst(
1875 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1876 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
1877 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
1880 PtrToIntInst::PtrToIntInst(
1881 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1882 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
1883 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
1886 PtrToIntInst::PtrToIntInst(
1887 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1888 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
1889 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
1892 IntToPtrInst::IntToPtrInst(
1893 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1894 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
1895 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
1898 IntToPtrInst::IntToPtrInst(
1899 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1900 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
1901 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
1904 BitCastInst::BitCastInst(
1905 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1906 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
1907 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
1910 BitCastInst::BitCastInst(
1911 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1912 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
1913 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
1916 //===----------------------------------------------------------------------===//
1918 //===----------------------------------------------------------------------===//
1920 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1921 const std::string &Name, Instruction *InsertBefore)
1922 : Instruction(Type::Int1Ty, op, Ops, 2, Name, InsertBefore) {
1923 Ops[0].init(LHS, this);
1924 Ops[1].init(RHS, this);
1925 SubclassData = predicate;
1926 if (op == Instruction::ICmp) {
1927 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
1928 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
1929 "Invalid ICmp predicate value");
1930 const Type* Op0Ty = getOperand(0)->getType();
1931 const Type* Op1Ty = getOperand(1)->getType();
1932 assert(Op0Ty == Op1Ty &&
1933 "Both operands to ICmp instruction are not of the same type!");
1934 // Check that the operands are the right type
1935 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
1936 "Invalid operand types for ICmp instruction");
1939 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
1940 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
1941 "Invalid FCmp predicate value");
1942 const Type* Op0Ty = getOperand(0)->getType();
1943 const Type* Op1Ty = getOperand(1)->getType();
1944 assert(Op0Ty == Op1Ty &&
1945 "Both operands to FCmp instruction are not of the same type!");
1946 // Check that the operands are the right type
1947 assert(Op0Ty->isFloatingPoint() &&
1948 "Invalid operand types for FCmp instruction");
1951 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1952 const std::string &Name, BasicBlock *InsertAtEnd)
1953 : Instruction(Type::Int1Ty, op, Ops, 2, Name, InsertAtEnd) {
1954 Ops[0].init(LHS, this);
1955 Ops[1].init(RHS, this);
1956 SubclassData = predicate;
1957 if (op == Instruction::ICmp) {
1958 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
1959 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
1960 "Invalid ICmp predicate value");
1962 const Type* Op0Ty = getOperand(0)->getType();
1963 const Type* Op1Ty = getOperand(1)->getType();
1964 assert(Op0Ty == Op1Ty &&
1965 "Both operands to ICmp instruction are not of the same type!");
1966 // Check that the operands are the right type
1967 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
1968 "Invalid operand types for ICmp instruction");
1971 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
1972 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
1973 "Invalid FCmp predicate value");
1974 const Type* Op0Ty = getOperand(0)->getType();
1975 const Type* Op1Ty = getOperand(1)->getType();
1976 assert(Op0Ty == Op1Ty &&
1977 "Both operands to FCmp instruction are not of the same type!");
1978 // Check that the operands are the right type
1979 assert(Op0Ty->isFloatingPoint() &&
1980 "Invalid operand types for FCmp instruction");
1984 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
1985 const std::string &Name, Instruction *InsertBefore) {
1986 if (Op == Instruction::ICmp) {
1987 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
1990 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
1995 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
1996 const std::string &Name, BasicBlock *InsertAtEnd) {
1997 if (Op == Instruction::ICmp) {
1998 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2001 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2005 void CmpInst::swapOperands() {
2006 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2009 cast<FCmpInst>(this)->swapOperands();
2012 bool CmpInst::isCommutative() {
2013 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2014 return IC->isCommutative();
2015 return cast<FCmpInst>(this)->isCommutative();
2018 bool CmpInst::isEquality() {
2019 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2020 return IC->isEquality();
2021 return cast<FCmpInst>(this)->isEquality();
2025 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2028 assert(!"Unknown icmp predicate!");
2029 case ICMP_EQ: return ICMP_NE;
2030 case ICMP_NE: return ICMP_EQ;
2031 case ICMP_UGT: return ICMP_ULE;
2032 case ICMP_ULT: return ICMP_UGE;
2033 case ICMP_UGE: return ICMP_ULT;
2034 case ICMP_ULE: return ICMP_UGT;
2035 case ICMP_SGT: return ICMP_SLE;
2036 case ICMP_SLT: return ICMP_SGE;
2037 case ICMP_SGE: return ICMP_SLT;
2038 case ICMP_SLE: return ICMP_SGT;
2042 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2044 default: assert(! "Unknown icmp predicate!");
2045 case ICMP_EQ: case ICMP_NE:
2047 case ICMP_SGT: return ICMP_SLT;
2048 case ICMP_SLT: return ICMP_SGT;
2049 case ICMP_SGE: return ICMP_SLE;
2050 case ICMP_SLE: return ICMP_SGE;
2051 case ICMP_UGT: return ICMP_ULT;
2052 case ICMP_ULT: return ICMP_UGT;
2053 case ICMP_UGE: return ICMP_ULE;
2054 case ICMP_ULE: return ICMP_UGE;
2058 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2060 default: assert(! "Unknown icmp predicate!");
2061 case ICMP_EQ: case ICMP_NE:
2062 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2064 case ICMP_UGT: return ICMP_SGT;
2065 case ICMP_ULT: return ICMP_SLT;
2066 case ICMP_UGE: return ICMP_SGE;
2067 case ICMP_ULE: return ICMP_SLE;
2071 bool ICmpInst::isSignedPredicate(Predicate pred) {
2073 default: assert(! "Unknown icmp predicate!");
2074 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2076 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2077 case ICMP_UGE: case ICMP_ULE:
2082 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2085 assert(!"Unknown icmp predicate!");
2086 case FCMP_OEQ: return FCMP_UNE;
2087 case FCMP_ONE: return FCMP_UEQ;
2088 case FCMP_OGT: return FCMP_ULE;
2089 case FCMP_OLT: return FCMP_UGE;
2090 case FCMP_OGE: return FCMP_ULT;
2091 case FCMP_OLE: return FCMP_UGT;
2092 case FCMP_UEQ: return FCMP_ONE;
2093 case FCMP_UNE: return FCMP_OEQ;
2094 case FCMP_UGT: return FCMP_OLE;
2095 case FCMP_ULT: return FCMP_OGE;
2096 case FCMP_UGE: return FCMP_OLT;
2097 case FCMP_ULE: return FCMP_OGT;
2098 case FCMP_ORD: return FCMP_UNO;
2099 case FCMP_UNO: return FCMP_ORD;
2100 case FCMP_TRUE: return FCMP_FALSE;
2101 case FCMP_FALSE: return FCMP_TRUE;
2105 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2107 default: assert(!"Unknown fcmp predicate!");
2108 case FCMP_FALSE: case FCMP_TRUE:
2109 case FCMP_OEQ: case FCMP_ONE:
2110 case FCMP_UEQ: case FCMP_UNE:
2111 case FCMP_ORD: case FCMP_UNO:
2113 case FCMP_OGT: return FCMP_OLT;
2114 case FCMP_OLT: return FCMP_OGT;
2115 case FCMP_OGE: return FCMP_OLE;
2116 case FCMP_OLE: return FCMP_OGE;
2117 case FCMP_UGT: return FCMP_ULT;
2118 case FCMP_ULT: return FCMP_UGT;
2119 case FCMP_UGE: return FCMP_ULE;
2120 case FCMP_ULE: return FCMP_UGE;
2124 bool CmpInst::isUnsigned(unsigned short predicate) {
2125 switch (predicate) {
2126 default: return false;
2127 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2128 case ICmpInst::ICMP_UGE: return true;
2132 bool CmpInst::isSigned(unsigned short predicate){
2133 switch (predicate) {
2134 default: return false;
2135 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2136 case ICmpInst::ICMP_SGE: return true;
2140 bool CmpInst::isOrdered(unsigned short predicate) {
2141 switch (predicate) {
2142 default: return false;
2143 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2144 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2145 case FCmpInst::FCMP_ORD: return true;
2149 bool CmpInst::isUnordered(unsigned short predicate) {
2150 switch (predicate) {
2151 default: return false;
2152 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2153 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2154 case FCmpInst::FCMP_UNO: return true;
2158 //===----------------------------------------------------------------------===//
2159 // SwitchInst Implementation
2160 //===----------------------------------------------------------------------===//
2162 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2163 assert(Value && Default);
2164 ReservedSpace = 2+NumCases*2;
2166 OperandList = new Use[ReservedSpace];
2168 OperandList[0].init(Value, this);
2169 OperandList[1].init(Default, this);
2172 SwitchInst::SwitchInst(const SwitchInst &SI)
2173 : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
2174 SI.getNumOperands()) {
2175 Use *OL = OperandList, *InOL = SI.OperandList;
2176 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2177 OL[i].init(InOL[i], this);
2178 OL[i+1].init(InOL[i+1], this);
2182 SwitchInst::~SwitchInst() {
2183 delete [] OperandList;
2187 /// addCase - Add an entry to the switch instruction...
2189 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2190 unsigned OpNo = NumOperands;
2191 if (OpNo+2 > ReservedSpace)
2192 resizeOperands(0); // Get more space!
2193 // Initialize some new operands.
2194 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2195 NumOperands = OpNo+2;
2196 OperandList[OpNo].init(OnVal, this);
2197 OperandList[OpNo+1].init(Dest, this);
2200 /// removeCase - This method removes the specified successor from the switch
2201 /// instruction. Note that this cannot be used to remove the default
2202 /// destination (successor #0).
2204 void SwitchInst::removeCase(unsigned idx) {
2205 assert(idx != 0 && "Cannot remove the default case!");
2206 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2208 unsigned NumOps = getNumOperands();
2209 Use *OL = OperandList;
2211 // Move everything after this operand down.
2213 // FIXME: we could just swap with the end of the list, then erase. However,
2214 // client might not expect this to happen. The code as it is thrashes the
2215 // use/def lists, which is kinda lame.
2216 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2218 OL[i-2+1] = OL[i+1];
2221 // Nuke the last value.
2222 OL[NumOps-2].set(0);
2223 OL[NumOps-2+1].set(0);
2224 NumOperands = NumOps-2;
2227 /// resizeOperands - resize operands - This adjusts the length of the operands
2228 /// list according to the following behavior:
2229 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2230 /// of operation. This grows the number of ops by 1.5 times.
2231 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2232 /// 3. If NumOps == NumOperands, trim the reserved space.
2234 void SwitchInst::resizeOperands(unsigned NumOps) {
2236 NumOps = getNumOperands()/2*6;
2237 } else if (NumOps*2 > NumOperands) {
2238 // No resize needed.
2239 if (ReservedSpace >= NumOps) return;
2240 } else if (NumOps == NumOperands) {
2241 if (ReservedSpace == NumOps) return;
2246 ReservedSpace = NumOps;
2247 Use *NewOps = new Use[NumOps];
2248 Use *OldOps = OperandList;
2249 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2250 NewOps[i].init(OldOps[i], this);
2254 OperandList = NewOps;
2258 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2259 return getSuccessor(idx);
2261 unsigned SwitchInst::getNumSuccessorsV() const {
2262 return getNumSuccessors();
2264 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2265 setSuccessor(idx, B);
2269 // Define these methods here so vtables don't get emitted into every translation
2270 // unit that uses these classes.
2272 GetElementPtrInst *GetElementPtrInst::clone() const {
2273 return new GetElementPtrInst(*this);
2276 BinaryOperator *BinaryOperator::clone() const {
2277 return create(getOpcode(), Ops[0], Ops[1]);
2280 CmpInst* CmpInst::clone() const {
2281 return create(getOpcode(), getPredicate(), Ops[0], Ops[1]);
2284 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2285 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2286 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2287 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2288 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2289 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2290 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2291 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2292 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2293 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2294 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2295 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2296 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2297 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2298 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2299 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2300 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2301 CallInst *CallInst::clone() const { return new CallInst(*this); }
2302 ShiftInst *ShiftInst::clone() const { return new ShiftInst(*this); }
2303 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2304 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2306 ExtractElementInst *ExtractElementInst::clone() const {
2307 return new ExtractElementInst(*this);
2309 InsertElementInst *InsertElementInst::clone() const {
2310 return new InsertElementInst(*this);
2312 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2313 return new ShuffleVectorInst(*this);
2315 PHINode *PHINode::clone() const { return new PHINode(*this); }
2316 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2317 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2318 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2319 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2320 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2321 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}