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());
207 assert((Params.size() == FTy->getNumParams() ||
208 (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
209 "Calling a function with bad signature!");
210 for (unsigned i = 0, e = Params.size(); i != e; ++i) {
211 assert((i >= FTy->getNumParams() ||
212 FTy->getParamType(i) == Params[i]->getType()) &&
213 "Calling a function with a bad signature!");
214 OL[i+1].init(Params[i], this);
218 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
220 Use *OL = OperandList = new Use[3];
221 OL[0].init(Func, this);
222 OL[1].init(Actual1, this);
223 OL[2].init(Actual2, this);
225 const FunctionType *FTy =
226 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
228 assert((FTy->getNumParams() == 2 ||
229 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
230 "Calling a function with bad signature");
231 assert((0 >= FTy->getNumParams() ||
232 FTy->getParamType(0) == Actual1->getType()) &&
233 "Calling a function with a bad signature!");
234 assert((1 >= FTy->getNumParams() ||
235 FTy->getParamType(1) == Actual2->getType()) &&
236 "Calling a function with a bad signature!");
239 void CallInst::init(Value *Func, Value *Actual) {
241 Use *OL = OperandList = new Use[2];
242 OL[0].init(Func, this);
243 OL[1].init(Actual, this);
245 const FunctionType *FTy =
246 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
248 assert((FTy->getNumParams() == 1 ||
249 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
250 "Calling a function with bad signature");
251 assert((0 == FTy->getNumParams() ||
252 FTy->getParamType(0) == Actual->getType()) &&
253 "Calling a function with a bad signature!");
256 void CallInst::init(Value *Func) {
258 Use *OL = OperandList = new Use[1];
259 OL[0].init(Func, this);
261 const FunctionType *MTy =
262 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
264 assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
267 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
268 const std::string &Name, Instruction *InsertBefore)
269 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
270 ->getElementType())->getReturnType(),
271 Instruction::Call, 0, 0, Name, InsertBefore) {
275 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
276 const std::string &Name, BasicBlock *InsertAtEnd)
277 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
278 ->getElementType())->getReturnType(),
279 Instruction::Call, 0, 0, Name, InsertAtEnd) {
283 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
284 const std::string &Name, Instruction *InsertBefore)
285 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
286 ->getElementType())->getReturnType(),
287 Instruction::Call, 0, 0, Name, InsertBefore) {
288 init(Func, Actual1, Actual2);
291 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
292 const std::string &Name, BasicBlock *InsertAtEnd)
293 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
294 ->getElementType())->getReturnType(),
295 Instruction::Call, 0, 0, Name, InsertAtEnd) {
296 init(Func, Actual1, Actual2);
299 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
300 Instruction *InsertBefore)
301 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
302 ->getElementType())->getReturnType(),
303 Instruction::Call, 0, 0, Name, InsertBefore) {
307 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
308 BasicBlock *InsertAtEnd)
309 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
310 ->getElementType())->getReturnType(),
311 Instruction::Call, 0, 0, Name, InsertAtEnd) {
315 CallInst::CallInst(Value *Func, const std::string &Name,
316 Instruction *InsertBefore)
317 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
318 ->getElementType())->getReturnType(),
319 Instruction::Call, 0, 0, Name, InsertBefore) {
323 CallInst::CallInst(Value *Func, const std::string &Name,
324 BasicBlock *InsertAtEnd)
325 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
326 ->getElementType())->getReturnType(),
327 Instruction::Call, 0, 0, Name, InsertAtEnd) {
331 CallInst::CallInst(const CallInst &CI)
332 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
333 CI.getNumOperands()) {
334 SubclassData = CI.SubclassData;
335 Use *OL = OperandList;
336 Use *InOL = CI.OperandList;
337 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
338 OL[i].init(InOL[i], this);
342 //===----------------------------------------------------------------------===//
343 // InvokeInst Implementation
344 //===----------------------------------------------------------------------===//
346 InvokeInst::~InvokeInst() {
347 delete [] OperandList;
350 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
351 const std::vector<Value*> &Params) {
352 NumOperands = 3+Params.size();
353 Use *OL = OperandList = new Use[3+Params.size()];
354 OL[0].init(Fn, this);
355 OL[1].init(IfNormal, this);
356 OL[2].init(IfException, this);
357 const FunctionType *FTy =
358 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
360 assert((Params.size() == FTy->getNumParams()) ||
361 (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
362 "Calling a function with bad signature");
364 for (unsigned i = 0, e = Params.size(); i != e; i++) {
365 assert((i >= FTy->getNumParams() ||
366 FTy->getParamType(i) == Params[i]->getType()) &&
367 "Invoking a function with a bad signature!");
369 OL[i+3].init(Params[i], this);
373 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
374 BasicBlock *IfException,
375 const std::vector<Value*> &Params,
376 const std::string &Name, Instruction *InsertBefore)
377 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
378 ->getElementType())->getReturnType(),
379 Instruction::Invoke, 0, 0, Name, InsertBefore) {
380 init(Fn, IfNormal, IfException, Params);
383 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
384 BasicBlock *IfException,
385 const std::vector<Value*> &Params,
386 const std::string &Name, BasicBlock *InsertAtEnd)
387 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
388 ->getElementType())->getReturnType(),
389 Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
390 init(Fn, IfNormal, IfException, Params);
393 InvokeInst::InvokeInst(const InvokeInst &II)
394 : TerminatorInst(II.getType(), Instruction::Invoke,
395 new Use[II.getNumOperands()], II.getNumOperands()) {
396 SubclassData = II.SubclassData;
397 Use *OL = OperandList, *InOL = II.OperandList;
398 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
399 OL[i].init(InOL[i], this);
402 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
403 return getSuccessor(idx);
405 unsigned InvokeInst::getNumSuccessorsV() const {
406 return getNumSuccessors();
408 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
409 return setSuccessor(idx, B);
413 //===----------------------------------------------------------------------===//
414 // ReturnInst Implementation
415 //===----------------------------------------------------------------------===//
417 void ReturnInst::init(Value *retVal) {
418 if (retVal && retVal->getType() != Type::VoidTy) {
419 assert(!isa<BasicBlock>(retVal) &&
420 "Cannot return basic block. Probably using the incorrect ctor");
422 RetVal.init(retVal, this);
426 unsigned ReturnInst::getNumSuccessorsV() const {
427 return getNumSuccessors();
430 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
431 // emit the vtable for the class in this translation unit.
432 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
433 assert(0 && "ReturnInst has no successors!");
436 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
437 assert(0 && "ReturnInst has no successors!");
443 //===----------------------------------------------------------------------===//
444 // UnwindInst Implementation
445 //===----------------------------------------------------------------------===//
447 unsigned UnwindInst::getNumSuccessorsV() const {
448 return getNumSuccessors();
451 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
452 assert(0 && "UnwindInst has no successors!");
455 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
456 assert(0 && "UnwindInst has no successors!");
461 //===----------------------------------------------------------------------===//
462 // UnreachableInst Implementation
463 //===----------------------------------------------------------------------===//
465 unsigned UnreachableInst::getNumSuccessorsV() const {
466 return getNumSuccessors();
469 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
470 assert(0 && "UnwindInst has no successors!");
473 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
474 assert(0 && "UnwindInst has no successors!");
479 //===----------------------------------------------------------------------===//
480 // BranchInst Implementation
481 //===----------------------------------------------------------------------===//
483 void BranchInst::AssertOK() {
485 assert(getCondition()->getType() == Type::Int1Ty &&
486 "May only branch on boolean predicates!");
489 BranchInst::BranchInst(const BranchInst &BI) :
490 TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
491 OperandList[0].init(BI.getOperand(0), this);
492 if (BI.getNumOperands() != 1) {
493 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
494 OperandList[1].init(BI.getOperand(1), this);
495 OperandList[2].init(BI.getOperand(2), this);
499 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
500 return getSuccessor(idx);
502 unsigned BranchInst::getNumSuccessorsV() const {
503 return getNumSuccessors();
505 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
506 setSuccessor(idx, B);
510 //===----------------------------------------------------------------------===//
511 // AllocationInst Implementation
512 //===----------------------------------------------------------------------===//
514 static Value *getAISize(Value *Amt) {
516 Amt = ConstantInt::get(Type::Int32Ty, 1);
518 assert(!isa<BasicBlock>(Amt) &&
519 "Passed basic block into allocation size parameter! Ue other ctor");
520 assert(Amt->getType() == Type::Int32Ty &&
521 "Malloc/Allocation array size is not a 32-bit integer!");
526 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
527 unsigned Align, const std::string &Name,
528 Instruction *InsertBefore)
529 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
530 Name, InsertBefore), Alignment(Align) {
531 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
532 assert(Ty != Type::VoidTy && "Cannot allocate void!");
535 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
536 unsigned Align, const std::string &Name,
537 BasicBlock *InsertAtEnd)
538 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
539 Name, InsertAtEnd), Alignment(Align) {
540 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
541 assert(Ty != Type::VoidTy && "Cannot allocate void!");
544 // Out of line virtual method, so the vtable, etc has a home.
545 AllocationInst::~AllocationInst() {
548 bool AllocationInst::isArrayAllocation() const {
549 if (ConstantInt *CUI = dyn_cast<ConstantInt>(getOperand(0)))
550 return CUI->getZExtValue() != 1;
554 const Type *AllocationInst::getAllocatedType() const {
555 return getType()->getElementType();
558 AllocaInst::AllocaInst(const AllocaInst &AI)
559 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
560 Instruction::Alloca, AI.getAlignment()) {
563 MallocInst::MallocInst(const MallocInst &MI)
564 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
565 Instruction::Malloc, MI.getAlignment()) {
568 //===----------------------------------------------------------------------===//
569 // FreeInst Implementation
570 //===----------------------------------------------------------------------===//
572 void FreeInst::AssertOK() {
573 assert(isa<PointerType>(getOperand(0)->getType()) &&
574 "Can not free something of nonpointer type!");
577 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
578 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
582 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
583 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
588 //===----------------------------------------------------------------------===//
589 // LoadInst Implementation
590 //===----------------------------------------------------------------------===//
592 void LoadInst::AssertOK() {
593 assert(isa<PointerType>(getOperand(0)->getType()) &&
594 "Ptr must have pointer type.");
597 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
598 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
599 Load, Ptr, Name, InsertBef) {
604 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
605 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
606 Load, Ptr, Name, InsertAE) {
611 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
612 Instruction *InsertBef)
613 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
614 Load, Ptr, Name, InsertBef) {
615 setVolatile(isVolatile);
619 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
620 BasicBlock *InsertAE)
621 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
622 Load, Ptr, Name, InsertAE) {
623 setVolatile(isVolatile);
628 //===----------------------------------------------------------------------===//
629 // StoreInst Implementation
630 //===----------------------------------------------------------------------===//
632 void StoreInst::AssertOK() {
633 assert(isa<PointerType>(getOperand(1)->getType()) &&
634 "Ptr must have pointer type!");
635 assert(getOperand(0)->getType() ==
636 cast<PointerType>(getOperand(1)->getType())->getElementType()
637 && "Ptr must be a pointer to Val type!");
641 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
642 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
643 Ops[0].init(val, this);
644 Ops[1].init(addr, this);
649 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
650 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
651 Ops[0].init(val, this);
652 Ops[1].init(addr, this);
657 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
658 Instruction *InsertBefore)
659 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
660 Ops[0].init(val, this);
661 Ops[1].init(addr, this);
662 setVolatile(isVolatile);
666 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
667 BasicBlock *InsertAtEnd)
668 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
669 Ops[0].init(val, this);
670 Ops[1].init(addr, this);
671 setVolatile(isVolatile);
675 //===----------------------------------------------------------------------===//
676 // GetElementPtrInst Implementation
677 //===----------------------------------------------------------------------===//
679 // checkType - Simple wrapper function to give a better assertion failure
680 // message on bad indexes for a gep instruction.
682 static inline const Type *checkType(const Type *Ty) {
683 assert(Ty && "Invalid GetElementPtrInst indices for type!");
687 void GetElementPtrInst::init(Value *Ptr, const std::vector<Value*> &Idx) {
688 NumOperands = 1+Idx.size();
689 Use *OL = OperandList = new Use[NumOperands];
690 OL[0].init(Ptr, this);
692 for (unsigned i = 0, e = Idx.size(); i != e; ++i)
693 OL[i+1].init(Idx[i], this);
696 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
698 Use *OL = OperandList = new Use[3];
699 OL[0].init(Ptr, this);
700 OL[1].init(Idx0, this);
701 OL[2].init(Idx1, this);
704 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
706 Use *OL = OperandList = new Use[2];
707 OL[0].init(Ptr, this);
708 OL[1].init(Idx, this);
711 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
712 const std::string &Name, Instruction *InBe)
713 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
715 GetElementPtr, 0, 0, Name, InBe) {
719 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
720 const std::string &Name, BasicBlock *IAE)
721 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
723 GetElementPtr, 0, 0, Name, IAE) {
727 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
728 const std::string &Name, Instruction *InBe)
729 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
730 GetElementPtr, 0, 0, Name, InBe) {
734 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
735 const std::string &Name, BasicBlock *IAE)
736 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
737 GetElementPtr, 0, 0, Name, IAE) {
741 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
742 const std::string &Name, Instruction *InBe)
743 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
745 GetElementPtr, 0, 0, Name, InBe) {
746 init(Ptr, Idx0, Idx1);
749 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
750 const std::string &Name, BasicBlock *IAE)
751 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
753 GetElementPtr, 0, 0, Name, IAE) {
754 init(Ptr, Idx0, Idx1);
757 GetElementPtrInst::~GetElementPtrInst() {
758 delete[] OperandList;
761 // getIndexedType - Returns the type of the element that would be loaded with
762 // a load instruction with the specified parameters.
764 // A null type is returned if the indices are invalid for the specified
767 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
770 bool AllowCompositeLeaf) {
771 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
773 // Handle the special case of the empty set index set...
775 if (AllowCompositeLeaf ||
776 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
777 return cast<PointerType>(Ptr)->getElementType();
782 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
783 if (NumIdx == CurIdx) {
784 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
785 return 0; // Can't load a whole structure or array!?!?
788 Value *Index = Idxs[CurIdx++];
789 if (isa<PointerType>(CT) && CurIdx != 1)
790 return 0; // Can only index into pointer types at the first index!
791 if (!CT->indexValid(Index)) return 0;
792 Ptr = CT->getTypeAtIndex(Index);
794 // If the new type forwards to another type, then it is in the middle
795 // of being refined to another type (and hence, may have dropped all
796 // references to what it was using before). So, use the new forwarded
798 if (const Type * Ty = Ptr->getForwardedType()) {
802 return CurIdx == NumIdx ? Ptr : 0;
805 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
806 Value *Idx0, Value *Idx1,
807 bool AllowCompositeLeaf) {
808 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
809 if (!PTy) return 0; // Type isn't a pointer type!
811 // Check the pointer index.
812 if (!PTy->indexValid(Idx0)) return 0;
814 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
815 if (!CT || !CT->indexValid(Idx1)) return 0;
817 const Type *ElTy = CT->getTypeAtIndex(Idx1);
818 if (AllowCompositeLeaf || ElTy->isFirstClassType())
823 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
824 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
825 if (!PTy) return 0; // Type isn't a pointer type!
827 // Check the pointer index.
828 if (!PTy->indexValid(Idx)) return 0;
830 return PTy->getElementType();
833 //===----------------------------------------------------------------------===//
834 // ExtractElementInst Implementation
835 //===----------------------------------------------------------------------===//
837 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
838 const std::string &Name,
839 Instruction *InsertBef)
840 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
841 ExtractElement, Ops, 2, Name, InsertBef) {
842 assert(isValidOperands(Val, Index) &&
843 "Invalid extractelement instruction operands!");
844 Ops[0].init(Val, this);
845 Ops[1].init(Index, this);
848 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
849 const std::string &Name,
850 Instruction *InsertBef)
851 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
852 ExtractElement, Ops, 2, Name, InsertBef) {
853 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
854 assert(isValidOperands(Val, Index) &&
855 "Invalid extractelement instruction operands!");
856 Ops[0].init(Val, this);
857 Ops[1].init(Index, this);
861 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
862 const std::string &Name,
863 BasicBlock *InsertAE)
864 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
865 ExtractElement, Ops, 2, Name, InsertAE) {
866 assert(isValidOperands(Val, Index) &&
867 "Invalid extractelement instruction operands!");
869 Ops[0].init(Val, this);
870 Ops[1].init(Index, this);
873 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
874 const std::string &Name,
875 BasicBlock *InsertAE)
876 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
877 ExtractElement, Ops, 2, Name, InsertAE) {
878 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
879 assert(isValidOperands(Val, Index) &&
880 "Invalid extractelement instruction operands!");
882 Ops[0].init(Val, this);
883 Ops[1].init(Index, this);
887 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
888 if (!isa<PackedType>(Val->getType()) || Index->getType() != Type::Int32Ty)
894 //===----------------------------------------------------------------------===//
895 // InsertElementInst Implementation
896 //===----------------------------------------------------------------------===//
898 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
899 : Instruction(IE.getType(), InsertElement, Ops, 3) {
900 Ops[0].init(IE.Ops[0], this);
901 Ops[1].init(IE.Ops[1], this);
902 Ops[2].init(IE.Ops[2], this);
904 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
905 const std::string &Name,
906 Instruction *InsertBef)
907 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
908 assert(isValidOperands(Vec, Elt, Index) &&
909 "Invalid insertelement instruction operands!");
910 Ops[0].init(Vec, this);
911 Ops[1].init(Elt, this);
912 Ops[2].init(Index, this);
915 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
916 const std::string &Name,
917 Instruction *InsertBef)
918 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
919 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
920 assert(isValidOperands(Vec, Elt, Index) &&
921 "Invalid insertelement instruction operands!");
922 Ops[0].init(Vec, this);
923 Ops[1].init(Elt, this);
924 Ops[2].init(Index, this);
928 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
929 const std::string &Name,
930 BasicBlock *InsertAE)
931 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
932 assert(isValidOperands(Vec, Elt, Index) &&
933 "Invalid insertelement instruction operands!");
935 Ops[0].init(Vec, this);
936 Ops[1].init(Elt, this);
937 Ops[2].init(Index, this);
940 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
941 const std::string &Name,
942 BasicBlock *InsertAE)
943 : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
944 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
945 assert(isValidOperands(Vec, Elt, Index) &&
946 "Invalid insertelement instruction operands!");
948 Ops[0].init(Vec, this);
949 Ops[1].init(Elt, this);
950 Ops[2].init(Index, this);
953 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
954 const Value *Index) {
955 if (!isa<PackedType>(Vec->getType()))
956 return false; // First operand of insertelement must be packed type.
958 if (Elt->getType() != cast<PackedType>(Vec->getType())->getElementType())
959 return false;// Second operand of insertelement must be packed element type.
961 if (Index->getType() != Type::Int32Ty)
962 return false; // Third operand of insertelement must be uint.
967 //===----------------------------------------------------------------------===//
968 // ShuffleVectorInst Implementation
969 //===----------------------------------------------------------------------===//
971 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
972 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
973 Ops[0].init(SV.Ops[0], this);
974 Ops[1].init(SV.Ops[1], this);
975 Ops[2].init(SV.Ops[2], this);
978 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
979 const std::string &Name,
980 Instruction *InsertBefore)
981 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertBefore) {
982 assert(isValidOperands(V1, V2, Mask) &&
983 "Invalid shuffle vector instruction operands!");
984 Ops[0].init(V1, this);
985 Ops[1].init(V2, this);
986 Ops[2].init(Mask, this);
989 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
990 const std::string &Name,
991 BasicBlock *InsertAtEnd)
992 : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertAtEnd) {
993 assert(isValidOperands(V1, V2, Mask) &&
994 "Invalid shuffle vector instruction operands!");
996 Ops[0].init(V1, this);
997 Ops[1].init(V2, this);
998 Ops[2].init(Mask, this);
1001 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1002 const Value *Mask) {
1003 if (!isa<PackedType>(V1->getType())) return false;
1004 if (V1->getType() != V2->getType()) return false;
1005 if (!isa<PackedType>(Mask->getType()) ||
1006 cast<PackedType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1007 cast<PackedType>(Mask->getType())->getNumElements() !=
1008 cast<PackedType>(V1->getType())->getNumElements())
1014 //===----------------------------------------------------------------------===//
1015 // BinaryOperator Class
1016 //===----------------------------------------------------------------------===//
1018 void BinaryOperator::init(BinaryOps iType)
1020 Value *LHS = getOperand(0), *RHS = getOperand(1);
1021 assert(LHS->getType() == RHS->getType() &&
1022 "Binary operator operand types must match!");
1027 assert(getType() == LHS->getType() &&
1028 "Arithmetic operation should return same type as operands!");
1029 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1030 isa<PackedType>(getType())) &&
1031 "Tried to create an arithmetic operation on a non-arithmetic type!");
1035 assert(getType() == LHS->getType() &&
1036 "Arithmetic operation should return same type as operands!");
1037 assert((getType()->isInteger() || (isa<PackedType>(getType()) &&
1038 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1039 "Incorrect operand type (not integer) for S/UDIV");
1042 assert(getType() == LHS->getType() &&
1043 "Arithmetic operation should return same type as operands!");
1044 assert((getType()->isFloatingPoint() || (isa<PackedType>(getType()) &&
1045 cast<PackedType>(getType())->getElementType()->isFloatingPoint()))
1046 && "Incorrect operand type (not floating point) for FDIV");
1050 assert(getType() == LHS->getType() &&
1051 "Arithmetic operation should return same type as operands!");
1052 assert((getType()->isInteger() || (isa<PackedType>(getType()) &&
1053 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1054 "Incorrect operand type (not integer) for S/UREM");
1057 assert(getType() == LHS->getType() &&
1058 "Arithmetic operation should return same type as operands!");
1059 assert((getType()->isFloatingPoint() || (isa<PackedType>(getType()) &&
1060 cast<PackedType>(getType())->getElementType()->isFloatingPoint()))
1061 && "Incorrect operand type (not floating point) for FREM");
1065 assert(getType() == LHS->getType() &&
1066 "Logical operation should return same type as operands!");
1067 assert((getType()->isInteger() ||
1068 (isa<PackedType>(getType()) &&
1069 cast<PackedType>(getType())->getElementType()->isInteger())) &&
1070 "Tried to create a logical operation on a non-integral type!");
1078 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1079 const std::string &Name,
1080 Instruction *InsertBefore) {
1081 assert(S1->getType() == S2->getType() &&
1082 "Cannot create binary operator with two operands of differing type!");
1083 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1086 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1087 const std::string &Name,
1088 BasicBlock *InsertAtEnd) {
1089 BinaryOperator *Res = create(Op, S1, S2, Name);
1090 InsertAtEnd->getInstList().push_back(Res);
1094 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1095 Instruction *InsertBefore) {
1096 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1097 return new BinaryOperator(Instruction::Sub,
1099 Op->getType(), Name, InsertBefore);
1102 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1103 BasicBlock *InsertAtEnd) {
1104 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1105 return new BinaryOperator(Instruction::Sub,
1107 Op->getType(), Name, InsertAtEnd);
1110 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1111 Instruction *InsertBefore) {
1113 if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
1114 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1115 C = ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), C));
1117 C = ConstantInt::getAllOnesValue(Op->getType());
1120 return new BinaryOperator(Instruction::Xor, Op, C,
1121 Op->getType(), Name, InsertBefore);
1124 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1125 BasicBlock *InsertAtEnd) {
1127 if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
1128 // Create a vector of all ones values.
1129 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1131 ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1133 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1136 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1137 Op->getType(), Name, InsertAtEnd);
1141 // isConstantAllOnes - Helper function for several functions below
1142 static inline bool isConstantAllOnes(const Value *V) {
1143 return isa<ConstantInt>(V) &&cast<ConstantInt>(V)->isAllOnesValue();
1146 bool BinaryOperator::isNeg(const Value *V) {
1147 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1148 if (Bop->getOpcode() == Instruction::Sub)
1149 return Bop->getOperand(0) ==
1150 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1154 bool BinaryOperator::isNot(const Value *V) {
1155 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1156 return (Bop->getOpcode() == Instruction::Xor &&
1157 (isConstantAllOnes(Bop->getOperand(1)) ||
1158 isConstantAllOnes(Bop->getOperand(0))));
1162 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1163 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1164 return cast<BinaryOperator>(BinOp)->getOperand(1);
1167 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1168 return getNegArgument(const_cast<Value*>(BinOp));
1171 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1172 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1173 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1174 Value *Op0 = BO->getOperand(0);
1175 Value *Op1 = BO->getOperand(1);
1176 if (isConstantAllOnes(Op0)) return Op1;
1178 assert(isConstantAllOnes(Op1));
1182 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1183 return getNotArgument(const_cast<Value*>(BinOp));
1187 // swapOperands - Exchange the two operands to this instruction. This
1188 // instruction is safe to use on any binary instruction and does not
1189 // modify the semantics of the instruction. If the instruction is
1190 // order dependent (SetLT f.e.) the opcode is changed.
1192 bool BinaryOperator::swapOperands() {
1193 if (!isCommutative())
1194 return true; // Can't commute operands
1195 std::swap(Ops[0], Ops[1]);
1199 //===----------------------------------------------------------------------===//
1201 //===----------------------------------------------------------------------===//
1203 // Just determine if this cast only deals with integral->integral conversion.
1204 bool CastInst::isIntegerCast() const {
1205 switch (getOpcode()) {
1206 default: return false;
1207 case Instruction::ZExt:
1208 case Instruction::SExt:
1209 case Instruction::Trunc:
1211 case Instruction::BitCast:
1212 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1216 bool CastInst::isLosslessCast() const {
1217 // Only BitCast can be lossless, exit fast if we're not BitCast
1218 if (getOpcode() != Instruction::BitCast)
1221 // Identity cast is always lossless
1222 const Type* SrcTy = getOperand(0)->getType();
1223 const Type* DstTy = getType();
1227 // Pointer to pointer is always lossless.
1228 if (isa<PointerType>(SrcTy))
1229 return isa<PointerType>(DstTy);
1230 return false; // Other types have no identity values
1233 /// This function determines if the CastInst does not require any bits to be
1234 /// changed in order to effect the cast. Essentially, it identifies cases where
1235 /// no code gen is necessary for the cast, hence the name no-op cast. For
1236 /// example, the following are all no-op casts:
1237 /// # bitcast uint %X, int
1238 /// # bitcast uint* %x, sbyte*
1239 /// # bitcast packed< 2 x int > %x, packed< 4 x short>
1240 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1241 /// @brief Determine if a cast is a no-op.
1242 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1243 switch (getOpcode()) {
1245 assert(!"Invalid CastOp");
1246 case Instruction::Trunc:
1247 case Instruction::ZExt:
1248 case Instruction::SExt:
1249 case Instruction::FPTrunc:
1250 case Instruction::FPExt:
1251 case Instruction::UIToFP:
1252 case Instruction::SIToFP:
1253 case Instruction::FPToUI:
1254 case Instruction::FPToSI:
1255 return false; // These always modify bits
1256 case Instruction::BitCast:
1257 return true; // BitCast never modifies bits.
1258 case Instruction::PtrToInt:
1259 return IntPtrTy->getPrimitiveSizeInBits() ==
1260 getType()->getPrimitiveSizeInBits();
1261 case Instruction::IntToPtr:
1262 return IntPtrTy->getPrimitiveSizeInBits() ==
1263 getOperand(0)->getType()->getPrimitiveSizeInBits();
1267 /// This function determines if a pair of casts can be eliminated and what
1268 /// opcode should be used in the elimination. This assumes that there are two
1269 /// instructions like this:
1270 /// * %F = firstOpcode SrcTy %x to MidTy
1271 /// * %S = secondOpcode MidTy %F to DstTy
1272 /// The function returns a resultOpcode so these two casts can be replaced with:
1273 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1274 /// If no such cast is permited, the function returns 0.
1275 unsigned CastInst::isEliminableCastPair(
1276 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1277 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1279 // Define the 144 possibilities for these two cast instructions. The values
1280 // in this matrix determine what to do in a given situation and select the
1281 // case in the switch below. The rows correspond to firstOp, the columns
1282 // correspond to secondOp. In looking at the table below, keep in mind
1283 // the following cast properties:
1285 // Size Compare Source Destination
1286 // Operator Src ? Size Type Sign Type Sign
1287 // -------- ------------ ------------------- ---------------------
1288 // TRUNC > Integer Any Integral Any
1289 // ZEXT < Integral Unsigned Integer Any
1290 // SEXT < Integral Signed Integer Any
1291 // FPTOUI n/a FloatPt n/a Integral Unsigned
1292 // FPTOSI n/a FloatPt n/a Integral Signed
1293 // UITOFP n/a Integral Unsigned FloatPt n/a
1294 // SITOFP n/a Integral Signed FloatPt n/a
1295 // FPTRUNC > FloatPt n/a FloatPt n/a
1296 // FPEXT < FloatPt n/a FloatPt n/a
1297 // PTRTOINT n/a Pointer n/a Integral Unsigned
1298 // INTTOPTR n/a Integral Unsigned Pointer n/a
1299 // BITCONVERT = FirstClass n/a FirstClass n/a
1301 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1302 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1303 // into "fptoui double to ulong", but this loses information about the range
1304 // of the produced value (we no longer know the top-part is all zeros).
1305 // Further this conversion is often much more expensive for typical hardware,
1306 // and causes issues when building libgcc. We disallow fptosi+sext for the
1308 const unsigned numCastOps =
1309 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1310 static const uint8_t CastResults[numCastOps][numCastOps] = {
1311 // T F F U S F F P I B -+
1312 // R Z S P P I I T P 2 N T |
1313 // U E E 2 2 2 2 R E I T C +- secondOp
1314 // N X X U S F F N X N 2 V |
1315 // C T T I I P P C T T P T -+
1316 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1317 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1318 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1319 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1320 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1321 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1322 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1323 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1324 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1325 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1326 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1327 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1330 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1331 [secondOp-Instruction::CastOpsBegin];
1334 // categorically disallowed
1337 // allowed, use first cast's opcode
1340 // allowed, use second cast's opcode
1343 // no-op cast in second op implies firstOp as long as the DestTy
1345 if (DstTy->isInteger())
1349 // no-op cast in second op implies firstOp as long as the DestTy
1350 // is floating point
1351 if (DstTy->isFloatingPoint())
1355 // no-op cast in first op implies secondOp as long as the SrcTy
1357 if (SrcTy->isInteger())
1361 // no-op cast in first op implies secondOp as long as the SrcTy
1362 // is a floating point
1363 if (SrcTy->isFloatingPoint())
1367 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1368 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1369 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1370 if (MidSize >= PtrSize)
1371 return Instruction::BitCast;
1375 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1376 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1377 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1378 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1379 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1380 if (SrcSize == DstSize)
1381 return Instruction::BitCast;
1382 else if (SrcSize < DstSize)
1386 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1387 return Instruction::ZExt;
1389 // fpext followed by ftrunc is allowed if the bit size returned to is
1390 // the same as the original, in which case its just a bitcast
1392 return Instruction::BitCast;
1393 return 0; // If the types are not the same we can't eliminate it.
1395 // bitcast followed by ptrtoint is allowed as long as the bitcast
1396 // is a pointer to pointer cast.
1397 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1401 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1402 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1406 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1407 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1408 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1409 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1410 if (SrcSize <= PtrSize && SrcSize == DstSize)
1411 return Instruction::BitCast;
1415 // cast combination can't happen (error in input). This is for all cases
1416 // where the MidTy is not the same for the two cast instructions.
1417 assert(!"Invalid Cast Combination");
1420 assert(!"Error in CastResults table!!!");
1426 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1427 const std::string &Name, Instruction *InsertBefore) {
1428 // Construct and return the appropriate CastInst subclass
1430 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1431 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1432 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1433 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1434 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1435 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1436 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1437 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1438 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1439 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1440 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1441 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1443 assert(!"Invalid opcode provided");
1448 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1449 const std::string &Name, BasicBlock *InsertAtEnd) {
1450 // Construct and return the appropriate CastInst subclass
1452 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1453 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1454 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1455 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1456 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1457 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1458 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1459 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1460 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1461 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1462 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1463 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1465 assert(!"Invalid opcode provided");
1470 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1471 const std::string &Name,
1472 Instruction *InsertBefore) {
1473 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1474 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1475 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1478 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1479 const std::string &Name,
1480 BasicBlock *InsertAtEnd) {
1481 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1482 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1483 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1486 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1487 const std::string &Name,
1488 Instruction *InsertBefore) {
1489 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1490 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1491 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1494 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1495 const std::string &Name,
1496 BasicBlock *InsertAtEnd) {
1497 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1498 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1499 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1502 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1503 const std::string &Name,
1504 Instruction *InsertBefore) {
1505 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1506 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1507 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1510 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1511 const std::string &Name,
1512 BasicBlock *InsertAtEnd) {
1513 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1514 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1515 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1518 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1519 const std::string &Name,
1520 BasicBlock *InsertAtEnd) {
1521 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1522 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1525 if (Ty->isInteger())
1526 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1527 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1530 /// @brief Create a BitCast or a PtrToInt cast instruction
1531 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1532 const std::string &Name,
1533 Instruction *InsertBefore) {
1534 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1535 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1538 if (Ty->isInteger())
1539 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1540 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1543 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1544 bool isSigned, const std::string &Name,
1545 Instruction *InsertBefore) {
1546 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1547 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1548 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1549 Instruction::CastOps opcode =
1550 (SrcBits == DstBits ? Instruction::BitCast :
1551 (SrcBits > DstBits ? Instruction::Trunc :
1552 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1553 return create(opcode, C, Ty, Name, InsertBefore);
1556 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1557 bool isSigned, const std::string &Name,
1558 BasicBlock *InsertAtEnd) {
1559 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1560 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1561 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1562 Instruction::CastOps opcode =
1563 (SrcBits == DstBits ? Instruction::BitCast :
1564 (SrcBits > DstBits ? Instruction::Trunc :
1565 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1566 return create(opcode, C, Ty, Name, InsertAtEnd);
1569 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1570 const std::string &Name,
1571 Instruction *InsertBefore) {
1572 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1574 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1575 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1576 Instruction::CastOps opcode =
1577 (SrcBits == DstBits ? Instruction::BitCast :
1578 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1579 return create(opcode, C, Ty, Name, InsertBefore);
1582 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1583 const std::string &Name,
1584 BasicBlock *InsertAtEnd) {
1585 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1587 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1588 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1589 Instruction::CastOps opcode =
1590 (SrcBits == DstBits ? Instruction::BitCast :
1591 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1592 return create(opcode, C, Ty, Name, InsertAtEnd);
1595 // Provide a way to get a "cast" where the cast opcode is inferred from the
1596 // types and size of the operand. This, basically, is a parallel of the
1597 // logic in the castIsValid function below. This axiom should hold:
1598 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1599 // should not assert in castIsValid. In other words, this produces a "correct"
1600 // casting opcode for the arguments passed to it.
1601 Instruction::CastOps
1602 CastInst::getCastOpcode(
1603 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1604 // Get the bit sizes, we'll need these
1605 const Type *SrcTy = Src->getType();
1606 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1607 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/packed
1609 // Run through the possibilities ...
1610 if (DestTy->isInteger()) { // Casting to integral
1611 if (SrcTy->isInteger()) { // Casting from integral
1612 if (DestBits < SrcBits)
1613 return Trunc; // int -> smaller int
1614 else if (DestBits > SrcBits) { // its an extension
1616 return SExt; // signed -> SEXT
1618 return ZExt; // unsigned -> ZEXT
1620 return BitCast; // Same size, No-op cast
1622 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1624 return FPToSI; // FP -> sint
1626 return FPToUI; // FP -> uint
1627 } else if (const PackedType *PTy = dyn_cast<PackedType>(SrcTy)) {
1628 assert(DestBits == PTy->getBitWidth() &&
1629 "Casting packed to integer of different width");
1630 return BitCast; // Same size, no-op cast
1632 assert(isa<PointerType>(SrcTy) &&
1633 "Casting from a value that is not first-class type");
1634 return PtrToInt; // ptr -> int
1636 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1637 if (SrcTy->isInteger()) { // Casting from integral
1639 return SIToFP; // sint -> FP
1641 return UIToFP; // uint -> FP
1642 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1643 if (DestBits < SrcBits) {
1644 return FPTrunc; // FP -> smaller FP
1645 } else if (DestBits > SrcBits) {
1646 return FPExt; // FP -> larger FP
1648 return BitCast; // same size, no-op cast
1650 } else if (const PackedType *PTy = dyn_cast<PackedType>(SrcTy)) {
1651 assert(DestBits == PTy->getBitWidth() &&
1652 "Casting packed to floating point of different width");
1653 return BitCast; // same size, no-op cast
1655 assert(0 && "Casting pointer or non-first class to float");
1657 } else if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
1658 if (const PackedType *SrcPTy = dyn_cast<PackedType>(SrcTy)) {
1659 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1660 "Casting packed to packed of different widths");
1661 return BitCast; // packed -> packed
1662 } else if (DestPTy->getBitWidth() == SrcBits) {
1663 return BitCast; // float/int -> packed
1665 assert(!"Illegal cast to packed (wrong type or size)");
1667 } else if (isa<PointerType>(DestTy)) {
1668 if (isa<PointerType>(SrcTy)) {
1669 return BitCast; // ptr -> ptr
1670 } else if (SrcTy->isInteger()) {
1671 return IntToPtr; // int -> ptr
1673 assert(!"Casting pointer to other than pointer or int");
1676 assert(!"Casting to type that is not first-class");
1679 // If we fall through to here we probably hit an assertion cast above
1680 // and assertions are not turned on. Anything we return is an error, so
1681 // BitCast is as good a choice as any.
1685 //===----------------------------------------------------------------------===//
1686 // CastInst SubClass Constructors
1687 //===----------------------------------------------------------------------===//
1689 /// Check that the construction parameters for a CastInst are correct. This
1690 /// could be broken out into the separate constructors but it is useful to have
1691 /// it in one place and to eliminate the redundant code for getting the sizes
1692 /// of the types involved.
1694 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1696 // Check for type sanity on the arguments
1697 const Type *SrcTy = S->getType();
1698 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1701 // Get the size of the types in bits, we'll need this later
1702 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1703 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1705 // Switch on the opcode provided
1707 default: return false; // This is an input error
1708 case Instruction::Trunc:
1709 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1710 case Instruction::ZExt:
1711 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1712 case Instruction::SExt:
1713 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1714 case Instruction::FPTrunc:
1715 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1716 SrcBitSize > DstBitSize;
1717 case Instruction::FPExt:
1718 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1719 SrcBitSize < DstBitSize;
1720 case Instruction::UIToFP:
1721 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1722 case Instruction::SIToFP:
1723 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1724 case Instruction::FPToUI:
1725 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1726 case Instruction::FPToSI:
1727 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1728 case Instruction::PtrToInt:
1729 return isa<PointerType>(SrcTy) && DstTy->isInteger();
1730 case Instruction::IntToPtr:
1731 return SrcTy->isInteger() && isa<PointerType>(DstTy);
1732 case Instruction::BitCast:
1733 // BitCast implies a no-op cast of type only. No bits change.
1734 // However, you can't cast pointers to anything but pointers.
1735 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
1738 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
1739 // these cases, the cast is okay if the source and destination bit widths
1741 return SrcBitSize == DstBitSize;
1745 TruncInst::TruncInst(
1746 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1747 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
1748 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1751 TruncInst::TruncInst(
1752 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1753 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
1754 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
1758 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1759 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
1760 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1764 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1765 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
1766 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
1769 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1770 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
1771 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
1775 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1776 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
1777 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
1780 FPTruncInst::FPTruncInst(
1781 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1782 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
1783 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
1786 FPTruncInst::FPTruncInst(
1787 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1788 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
1789 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
1792 FPExtInst::FPExtInst(
1793 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1794 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
1795 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
1798 FPExtInst::FPExtInst(
1799 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1800 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
1801 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
1804 UIToFPInst::UIToFPInst(
1805 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1806 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
1807 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
1810 UIToFPInst::UIToFPInst(
1811 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1812 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
1813 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
1816 SIToFPInst::SIToFPInst(
1817 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1818 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
1819 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
1822 SIToFPInst::SIToFPInst(
1823 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1824 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
1825 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
1828 FPToUIInst::FPToUIInst(
1829 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1830 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
1831 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
1834 FPToUIInst::FPToUIInst(
1835 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1836 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
1837 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
1840 FPToSIInst::FPToSIInst(
1841 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1842 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
1843 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
1846 FPToSIInst::FPToSIInst(
1847 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1848 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
1849 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
1852 PtrToIntInst::PtrToIntInst(
1853 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1854 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
1855 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
1858 PtrToIntInst::PtrToIntInst(
1859 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1860 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
1861 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
1864 IntToPtrInst::IntToPtrInst(
1865 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1866 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
1867 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
1870 IntToPtrInst::IntToPtrInst(
1871 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1872 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
1873 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
1876 BitCastInst::BitCastInst(
1877 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
1878 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
1879 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
1882 BitCastInst::BitCastInst(
1883 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
1884 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
1885 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
1888 //===----------------------------------------------------------------------===//
1890 //===----------------------------------------------------------------------===//
1892 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1893 const std::string &Name, Instruction *InsertBefore)
1894 : Instruction(Type::Int1Ty, op, Ops, 2, Name, InsertBefore) {
1895 Ops[0].init(LHS, this);
1896 Ops[1].init(RHS, this);
1897 SubclassData = predicate;
1898 if (op == Instruction::ICmp) {
1899 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
1900 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
1901 "Invalid ICmp predicate value");
1902 const Type* Op0Ty = getOperand(0)->getType();
1903 const Type* Op1Ty = getOperand(1)->getType();
1904 assert(Op0Ty == Op1Ty &&
1905 "Both operands to ICmp instruction are not of the same type!");
1906 // Check that the operands are the right type
1907 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
1908 "Invalid operand types for ICmp instruction");
1911 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
1912 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
1913 "Invalid FCmp predicate value");
1914 const Type* Op0Ty = getOperand(0)->getType();
1915 const Type* Op1Ty = getOperand(1)->getType();
1916 assert(Op0Ty == Op1Ty &&
1917 "Both operands to FCmp instruction are not of the same type!");
1918 // Check that the operands are the right type
1919 assert(Op0Ty->isFloatingPoint() &&
1920 "Invalid operand types for FCmp instruction");
1923 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
1924 const std::string &Name, BasicBlock *InsertAtEnd)
1925 : Instruction(Type::Int1Ty, op, Ops, 2, Name, InsertAtEnd) {
1926 Ops[0].init(LHS, this);
1927 Ops[1].init(RHS, this);
1928 SubclassData = predicate;
1929 if (op == Instruction::ICmp) {
1930 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
1931 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
1932 "Invalid ICmp predicate value");
1934 const Type* Op0Ty = getOperand(0)->getType();
1935 const Type* Op1Ty = getOperand(1)->getType();
1936 assert(Op0Ty == Op1Ty &&
1937 "Both operands to ICmp instruction are not of the same type!");
1938 // Check that the operands are the right type
1939 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
1940 "Invalid operand types for ICmp instruction");
1943 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
1944 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
1945 "Invalid FCmp predicate value");
1946 const Type* Op0Ty = getOperand(0)->getType();
1947 const Type* Op1Ty = getOperand(1)->getType();
1948 assert(Op0Ty == Op1Ty &&
1949 "Both operands to FCmp instruction are not of the same type!");
1950 // Check that the operands are the right type
1951 assert(Op0Ty->isFloatingPoint() &&
1952 "Invalid operand types for FCmp instruction");
1956 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
1957 const std::string &Name, Instruction *InsertBefore) {
1958 if (Op == Instruction::ICmp) {
1959 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
1962 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
1967 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
1968 const std::string &Name, BasicBlock *InsertAtEnd) {
1969 if (Op == Instruction::ICmp) {
1970 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
1973 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
1977 void CmpInst::swapOperands() {
1978 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
1981 cast<FCmpInst>(this)->swapOperands();
1984 bool CmpInst::isCommutative() {
1985 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
1986 return IC->isCommutative();
1987 return cast<FCmpInst>(this)->isCommutative();
1990 bool CmpInst::isEquality() {
1991 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
1992 return IC->isEquality();
1993 return cast<FCmpInst>(this)->isEquality();
1997 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2000 assert(!"Unknown icmp predicate!");
2001 case ICMP_EQ: return ICMP_NE;
2002 case ICMP_NE: return ICMP_EQ;
2003 case ICMP_UGT: return ICMP_ULE;
2004 case ICMP_ULT: return ICMP_UGE;
2005 case ICMP_UGE: return ICMP_ULT;
2006 case ICMP_ULE: return ICMP_UGT;
2007 case ICMP_SGT: return ICMP_SLE;
2008 case ICMP_SLT: return ICMP_SGE;
2009 case ICMP_SGE: return ICMP_SLT;
2010 case ICMP_SLE: return ICMP_SGT;
2014 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2016 default: assert(! "Unknown icmp predicate!");
2017 case ICMP_EQ: case ICMP_NE:
2019 case ICMP_SGT: return ICMP_SLT;
2020 case ICMP_SLT: return ICMP_SGT;
2021 case ICMP_SGE: return ICMP_SLE;
2022 case ICMP_SLE: return ICMP_SGE;
2023 case ICMP_UGT: return ICMP_ULT;
2024 case ICMP_ULT: return ICMP_UGT;
2025 case ICMP_UGE: return ICMP_ULE;
2026 case ICMP_ULE: return ICMP_UGE;
2030 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2032 default: assert(! "Unknown icmp predicate!");
2033 case ICMP_EQ: case ICMP_NE:
2034 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2036 case ICMP_UGT: return ICMP_SGT;
2037 case ICMP_ULT: return ICMP_SLT;
2038 case ICMP_UGE: return ICMP_SGE;
2039 case ICMP_ULE: return ICMP_SLE;
2043 bool ICmpInst::isSignedPredicate(Predicate pred) {
2045 default: assert(! "Unknown icmp predicate!");
2046 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2048 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2049 case ICMP_UGE: case ICMP_ULE:
2054 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2057 assert(!"Unknown icmp predicate!");
2058 case FCMP_OEQ: return FCMP_UNE;
2059 case FCMP_ONE: return FCMP_UEQ;
2060 case FCMP_OGT: return FCMP_ULE;
2061 case FCMP_OLT: return FCMP_UGE;
2062 case FCMP_OGE: return FCMP_ULT;
2063 case FCMP_OLE: return FCMP_UGT;
2064 case FCMP_UEQ: return FCMP_ONE;
2065 case FCMP_UNE: return FCMP_OEQ;
2066 case FCMP_UGT: return FCMP_OLE;
2067 case FCMP_ULT: return FCMP_OGE;
2068 case FCMP_UGE: return FCMP_OLT;
2069 case FCMP_ULE: return FCMP_OGT;
2070 case FCMP_ORD: return FCMP_UNO;
2071 case FCMP_UNO: return FCMP_ORD;
2072 case FCMP_TRUE: return FCMP_FALSE;
2073 case FCMP_FALSE: return FCMP_TRUE;
2077 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2079 default: assert(!"Unknown fcmp predicate!");
2080 case FCMP_FALSE: case FCMP_TRUE:
2081 case FCMP_OEQ: case FCMP_ONE:
2082 case FCMP_UEQ: case FCMP_UNE:
2083 case FCMP_ORD: case FCMP_UNO:
2085 case FCMP_OGT: return FCMP_OLT;
2086 case FCMP_OLT: return FCMP_OGT;
2087 case FCMP_OGE: return FCMP_OLE;
2088 case FCMP_OLE: return FCMP_OGE;
2089 case FCMP_UGT: return FCMP_ULT;
2090 case FCMP_ULT: return FCMP_UGT;
2091 case FCMP_UGE: return FCMP_ULE;
2092 case FCMP_ULE: return FCMP_UGE;
2096 bool CmpInst::isUnsigned(unsigned short predicate) {
2097 switch (predicate) {
2098 default: return false;
2099 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2100 case ICmpInst::ICMP_UGE: return true;
2104 bool CmpInst::isSigned(unsigned short predicate){
2105 switch (predicate) {
2106 default: return false;
2107 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2108 case ICmpInst::ICMP_SGE: return true;
2112 bool CmpInst::isOrdered(unsigned short predicate) {
2113 switch (predicate) {
2114 default: return false;
2115 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2116 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2117 case FCmpInst::FCMP_ORD: return true;
2121 bool CmpInst::isUnordered(unsigned short predicate) {
2122 switch (predicate) {
2123 default: return false;
2124 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2125 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2126 case FCmpInst::FCMP_UNO: return true;
2130 //===----------------------------------------------------------------------===//
2131 // SwitchInst Implementation
2132 //===----------------------------------------------------------------------===//
2134 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2135 assert(Value && Default);
2136 ReservedSpace = 2+NumCases*2;
2138 OperandList = new Use[ReservedSpace];
2140 OperandList[0].init(Value, this);
2141 OperandList[1].init(Default, this);
2144 SwitchInst::SwitchInst(const SwitchInst &SI)
2145 : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
2146 SI.getNumOperands()) {
2147 Use *OL = OperandList, *InOL = SI.OperandList;
2148 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2149 OL[i].init(InOL[i], this);
2150 OL[i+1].init(InOL[i+1], this);
2154 SwitchInst::~SwitchInst() {
2155 delete [] OperandList;
2159 /// addCase - Add an entry to the switch instruction...
2161 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2162 unsigned OpNo = NumOperands;
2163 if (OpNo+2 > ReservedSpace)
2164 resizeOperands(0); // Get more space!
2165 // Initialize some new operands.
2166 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2167 NumOperands = OpNo+2;
2168 OperandList[OpNo].init(OnVal, this);
2169 OperandList[OpNo+1].init(Dest, this);
2172 /// removeCase - This method removes the specified successor from the switch
2173 /// instruction. Note that this cannot be used to remove the default
2174 /// destination (successor #0).
2176 void SwitchInst::removeCase(unsigned idx) {
2177 assert(idx != 0 && "Cannot remove the default case!");
2178 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2180 unsigned NumOps = getNumOperands();
2181 Use *OL = OperandList;
2183 // Move everything after this operand down.
2185 // FIXME: we could just swap with the end of the list, then erase. However,
2186 // client might not expect this to happen. The code as it is thrashes the
2187 // use/def lists, which is kinda lame.
2188 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2190 OL[i-2+1] = OL[i+1];
2193 // Nuke the last value.
2194 OL[NumOps-2].set(0);
2195 OL[NumOps-2+1].set(0);
2196 NumOperands = NumOps-2;
2199 /// resizeOperands - resize operands - This adjusts the length of the operands
2200 /// list according to the following behavior:
2201 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2202 /// of operation. This grows the number of ops by 1.5 times.
2203 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2204 /// 3. If NumOps == NumOperands, trim the reserved space.
2206 void SwitchInst::resizeOperands(unsigned NumOps) {
2208 NumOps = getNumOperands()/2*6;
2209 } else if (NumOps*2 > NumOperands) {
2210 // No resize needed.
2211 if (ReservedSpace >= NumOps) return;
2212 } else if (NumOps == NumOperands) {
2213 if (ReservedSpace == NumOps) return;
2218 ReservedSpace = NumOps;
2219 Use *NewOps = new Use[NumOps];
2220 Use *OldOps = OperandList;
2221 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2222 NewOps[i].init(OldOps[i], this);
2226 OperandList = NewOps;
2230 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2231 return getSuccessor(idx);
2233 unsigned SwitchInst::getNumSuccessorsV() const {
2234 return getNumSuccessors();
2236 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2237 setSuccessor(idx, B);
2241 // Define these methods here so vtables don't get emitted into every translation
2242 // unit that uses these classes.
2244 GetElementPtrInst *GetElementPtrInst::clone() const {
2245 return new GetElementPtrInst(*this);
2248 BinaryOperator *BinaryOperator::clone() const {
2249 return create(getOpcode(), Ops[0], Ops[1]);
2252 CmpInst* CmpInst::clone() const {
2253 return create(getOpcode(), getPredicate(), Ops[0], Ops[1]);
2256 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2257 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2258 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2259 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2260 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2261 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2262 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2263 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2264 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2265 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2266 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2267 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2268 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2269 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2270 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2271 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2272 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2273 CallInst *CallInst::clone() const { return new CallInst(*this); }
2274 ShiftInst *ShiftInst::clone() const { return new ShiftInst(*this); }
2275 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2276 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2278 ExtractElementInst *ExtractElementInst::clone() const {
2279 return new ExtractElementInst(*this);
2281 InsertElementInst *InsertElementInst::clone() const {
2282 return new InsertElementInst(*this);
2284 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2285 return new ShuffleVectorInst(*this);
2287 PHINode *PHINode::clone() const { return new PHINode(*this); }
2288 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2289 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2290 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2291 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2292 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2293 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}