1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "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"
21 #include "llvm/Support/ConstantRange.h"
22 #include "llvm/Support/MathExtras.h"
25 //===----------------------------------------------------------------------===//
27 //===----------------------------------------------------------------------===//
29 CallSite::CallSite(Instruction *C) {
30 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
33 unsigned CallSite::getCallingConv() const {
34 if (CallInst *CI = dyn_cast<CallInst>(I))
35 return CI->getCallingConv();
37 return cast<InvokeInst>(I)->getCallingConv();
39 void CallSite::setCallingConv(unsigned CC) {
40 if (CallInst *CI = dyn_cast<CallInst>(I))
41 CI->setCallingConv(CC);
43 cast<InvokeInst>(I)->setCallingConv(CC);
45 const PAListPtr &CallSite::getParamAttrs() const {
46 if (CallInst *CI = dyn_cast<CallInst>(I))
47 return CI->getParamAttrs();
49 return cast<InvokeInst>(I)->getParamAttrs();
51 void CallSite::setParamAttrs(const PAListPtr &PAL) {
52 if (CallInst *CI = dyn_cast<CallInst>(I))
53 CI->setParamAttrs(PAL);
55 cast<InvokeInst>(I)->setParamAttrs(PAL);
57 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
58 if (CallInst *CI = dyn_cast<CallInst>(I))
59 return CI->paramHasAttr(i, attr);
61 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
63 uint16_t CallSite::getParamAlignment(uint16_t i) const {
64 if (CallInst *CI = dyn_cast<CallInst>(I))
65 return CI->getParamAlignment(i);
67 return cast<InvokeInst>(I)->getParamAlignment(i);
70 bool CallSite::doesNotAccessMemory() const {
71 if (CallInst *CI = dyn_cast<CallInst>(I))
72 return CI->doesNotAccessMemory();
74 return cast<InvokeInst>(I)->doesNotAccessMemory();
76 bool CallSite::onlyReadsMemory() const {
77 if (CallInst *CI = dyn_cast<CallInst>(I))
78 return CI->onlyReadsMemory();
80 return cast<InvokeInst>(I)->onlyReadsMemory();
82 bool CallSite::doesNotThrow() const {
83 if (CallInst *CI = dyn_cast<CallInst>(I))
84 return CI->doesNotThrow();
86 return cast<InvokeInst>(I)->doesNotThrow();
88 void CallSite::setDoesNotThrow(bool doesNotThrow) {
89 if (CallInst *CI = dyn_cast<CallInst>(I))
90 CI->setDoesNotThrow(doesNotThrow);
92 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
95 //===----------------------------------------------------------------------===//
96 // TerminatorInst Class
97 //===----------------------------------------------------------------------===//
99 // Out of line virtual method, so the vtable, etc has a home.
100 TerminatorInst::~TerminatorInst() {
103 // Out of line virtual method, so the vtable, etc has a home.
104 UnaryInstruction::~UnaryInstruction() {
108 //===----------------------------------------------------------------------===//
110 //===----------------------------------------------------------------------===//
112 PHINode::PHINode(const PHINode &PN)
113 : Instruction(PN.getType(), Instruction::PHI,
114 new Use[PN.getNumOperands()], PN.getNumOperands()),
115 ReservedSpace(PN.getNumOperands()) {
116 Use *OL = OperandList;
117 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
118 OL[i].init(PN.getOperand(i), this);
119 OL[i+1].init(PN.getOperand(i+1), this);
123 PHINode::~PHINode() {
124 delete [] OperandList;
127 // removeIncomingValue - Remove an incoming value. This is useful if a
128 // predecessor basic block is deleted.
129 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
130 unsigned NumOps = getNumOperands();
131 Use *OL = OperandList;
132 assert(Idx*2 < NumOps && "BB not in PHI node!");
133 Value *Removed = OL[Idx*2];
135 // Move everything after this operand down.
137 // FIXME: we could just swap with the end of the list, then erase. However,
138 // client might not expect this to happen. The code as it is thrashes the
139 // use/def lists, which is kinda lame.
140 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
145 // Nuke the last value.
147 OL[NumOps-2+1].set(0);
148 NumOperands = NumOps-2;
150 // If the PHI node is dead, because it has zero entries, nuke it now.
151 if (NumOps == 2 && DeletePHIIfEmpty) {
152 // If anyone is using this PHI, make them use a dummy value instead...
153 replaceAllUsesWith(UndefValue::get(getType()));
159 /// resizeOperands - resize operands - This adjusts the length of the operands
160 /// list according to the following behavior:
161 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
162 /// of operation. This grows the number of ops by 1.5 times.
163 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
164 /// 3. If NumOps == NumOperands, trim the reserved space.
166 void PHINode::resizeOperands(unsigned NumOps) {
168 NumOps = (getNumOperands())*3/2;
169 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
170 } else if (NumOps*2 > NumOperands) {
172 if (ReservedSpace >= NumOps) return;
173 } else if (NumOps == NumOperands) {
174 if (ReservedSpace == NumOps) return;
179 ReservedSpace = NumOps;
180 Use *NewOps = new Use[NumOps];
181 Use *OldOps = OperandList;
182 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
183 NewOps[i].init(OldOps[i], this);
187 OperandList = NewOps;
190 /// hasConstantValue - If the specified PHI node always merges together the same
191 /// value, return the value, otherwise return null.
193 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
194 // If the PHI node only has one incoming value, eliminate the PHI node...
195 if (getNumIncomingValues() == 1) {
196 if (getIncomingValue(0) != this) // not X = phi X
197 return getIncomingValue(0);
199 return UndefValue::get(getType()); // Self cycle is dead.
202 // Otherwise if all of the incoming values are the same for the PHI, replace
203 // the PHI node with the incoming value.
206 bool HasUndefInput = false;
207 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
208 if (isa<UndefValue>(getIncomingValue(i))) {
209 HasUndefInput = true;
210 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
211 if (InVal && getIncomingValue(i) != InVal)
212 return 0; // Not the same, bail out.
214 InVal = getIncomingValue(i);
217 // The only case that could cause InVal to be null is if we have a PHI node
218 // that only has entries for itself. In this case, there is no entry into the
219 // loop, so kill the PHI.
221 if (InVal == 0) InVal = UndefValue::get(getType());
223 // If we have a PHI node like phi(X, undef, X), where X is defined by some
224 // instruction, we cannot always return X as the result of the PHI node. Only
225 // do this if X is not an instruction (thus it must dominate the PHI block),
226 // or if the client is prepared to deal with this possibility.
227 if (HasUndefInput && !AllowNonDominatingInstruction)
228 if (Instruction *IV = dyn_cast<Instruction>(InVal))
229 // If it's in the entry block, it dominates everything.
230 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
232 return 0; // Cannot guarantee that InVal dominates this PHINode.
234 // All of the incoming values are the same, return the value now.
239 //===----------------------------------------------------------------------===//
240 // CallInst Implementation
241 //===----------------------------------------------------------------------===//
243 CallInst::~CallInst() {
244 delete [] OperandList;
247 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
248 NumOperands = NumParams+1;
249 Use *OL = OperandList = new Use[NumParams+1];
250 OL[0].init(Func, this);
252 const FunctionType *FTy =
253 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
254 FTy = FTy; // silence warning.
256 assert((NumParams == FTy->getNumParams() ||
257 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
258 "Calling a function with bad signature!");
259 for (unsigned i = 0; i != NumParams; ++i) {
260 assert((i >= FTy->getNumParams() ||
261 FTy->getParamType(i) == Params[i]->getType()) &&
262 "Calling a function with a bad signature!");
263 OL[i+1].init(Params[i], this);
267 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
269 Use *OL = OperandList = new Use[3];
270 OL[0].init(Func, this);
271 OL[1].init(Actual1, this);
272 OL[2].init(Actual2, this);
274 const FunctionType *FTy =
275 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
276 FTy = FTy; // silence warning.
278 assert((FTy->getNumParams() == 2 ||
279 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
280 "Calling a function with bad signature");
281 assert((0 >= FTy->getNumParams() ||
282 FTy->getParamType(0) == Actual1->getType()) &&
283 "Calling a function with a bad signature!");
284 assert((1 >= FTy->getNumParams() ||
285 FTy->getParamType(1) == Actual2->getType()) &&
286 "Calling a function with a bad signature!");
289 void CallInst::init(Value *Func, Value *Actual) {
291 Use *OL = OperandList = new Use[2];
292 OL[0].init(Func, this);
293 OL[1].init(Actual, this);
295 const FunctionType *FTy =
296 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
297 FTy = FTy; // silence warning.
299 assert((FTy->getNumParams() == 1 ||
300 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
301 "Calling a function with bad signature");
302 assert((0 == FTy->getNumParams() ||
303 FTy->getParamType(0) == Actual->getType()) &&
304 "Calling a function with a bad signature!");
307 void CallInst::init(Value *Func) {
309 Use *OL = OperandList = new Use[1];
310 OL[0].init(Func, this);
312 const FunctionType *FTy =
313 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
314 FTy = FTy; // silence warning.
316 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
319 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
320 Instruction *InsertBefore)
321 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
322 ->getElementType())->getReturnType(),
323 Instruction::Call, 0, 0, InsertBefore) {
328 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
329 BasicBlock *InsertAtEnd)
330 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
331 ->getElementType())->getReturnType(),
332 Instruction::Call, 0, 0, InsertAtEnd) {
336 CallInst::CallInst(Value *Func, const std::string &Name,
337 Instruction *InsertBefore)
338 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
339 ->getElementType())->getReturnType(),
340 Instruction::Call, 0, 0, InsertBefore) {
345 CallInst::CallInst(Value *Func, const std::string &Name,
346 BasicBlock *InsertAtEnd)
347 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
348 ->getElementType())->getReturnType(),
349 Instruction::Call, 0, 0, InsertAtEnd) {
354 CallInst::CallInst(const CallInst &CI)
355 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
356 CI.getNumOperands()) {
357 setParamAttrs(CI.getParamAttrs());
358 SubclassData = CI.SubclassData;
359 Use *OL = OperandList;
360 Use *InOL = CI.OperandList;
361 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
362 OL[i].init(InOL[i], this);
365 bool CallInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
366 if (ParamAttrs.paramHasAttr(i, attr))
368 if (const Function *F = getCalledFunction())
369 return F->paramHasAttr(i, attr);
373 void CallInst::setDoesNotThrow(bool doesNotThrow) {
374 PAListPtr PAL = getParamAttrs();
376 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
378 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
383 //===----------------------------------------------------------------------===//
384 // InvokeInst Implementation
385 //===----------------------------------------------------------------------===//
387 InvokeInst::~InvokeInst() {
388 delete [] OperandList;
391 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
392 Value* const *Args, unsigned NumArgs) {
393 NumOperands = 3+NumArgs;
394 Use *OL = OperandList = new Use[3+NumArgs];
395 OL[0].init(Fn, this);
396 OL[1].init(IfNormal, this);
397 OL[2].init(IfException, this);
398 const FunctionType *FTy =
399 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
400 FTy = FTy; // silence warning.
402 assert(((NumArgs == FTy->getNumParams()) ||
403 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
404 "Calling a function with bad signature");
406 for (unsigned i = 0, e = NumArgs; i != e; i++) {
407 assert((i >= FTy->getNumParams() ||
408 FTy->getParamType(i) == Args[i]->getType()) &&
409 "Invoking a function with a bad signature!");
411 OL[i+3].init(Args[i], this);
415 InvokeInst::InvokeInst(const InvokeInst &II)
416 : TerminatorInst(II.getType(), Instruction::Invoke,
417 new Use[II.getNumOperands()], II.getNumOperands()) {
418 setParamAttrs(II.getParamAttrs());
419 SubclassData = II.SubclassData;
420 Use *OL = OperandList, *InOL = II.OperandList;
421 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
422 OL[i].init(InOL[i], this);
425 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
426 return getSuccessor(idx);
428 unsigned InvokeInst::getNumSuccessorsV() const {
429 return getNumSuccessors();
431 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
432 return setSuccessor(idx, B);
435 bool InvokeInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
436 if (ParamAttrs.paramHasAttr(i, attr))
438 if (const Function *F = getCalledFunction())
439 return F->paramHasAttr(i, attr);
443 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
444 PAListPtr PAL = getParamAttrs();
446 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
448 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
453 //===----------------------------------------------------------------------===//
454 // ReturnInst Implementation
455 //===----------------------------------------------------------------------===//
457 ReturnInst::ReturnInst(const ReturnInst &RI)
458 : TerminatorInst(Type::VoidTy, Instruction::Ret,
459 &RetVal, RI.getNumOperands()) {
460 unsigned N = RI.getNumOperands();
462 RetVal.init(RI.RetVal, this);
464 Use *OL = OperandList = new Use[N];
465 for (unsigned i = 0; i < N; ++i)
466 OL[i].init(RI.getOperand(i), this);
470 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
471 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
475 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
476 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
480 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
481 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
484 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
485 Instruction *InsertBefore)
486 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N, InsertBefore) {
490 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
491 BasicBlock *InsertAtEnd)
492 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N, InsertAtEnd) {
496 ReturnInst::ReturnInst(Value * const* retVals, unsigned N)
497 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, N) {
502 void ReturnInst::init(Value * const* retVals, unsigned N) {
503 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
506 if (NumOperands == 1) {
508 if (V->getType() == Type::VoidTy)
510 RetVal.init(V, this);
514 Use *OL = OperandList = new Use[NumOperands];
515 for (unsigned i = 0; i < NumOperands; ++i) {
516 Value *V = *retVals++;
517 assert(!isa<BasicBlock>(V) &&
518 "Cannot return basic block. Probably using the incorrect ctor");
523 unsigned ReturnInst::getNumSuccessorsV() const {
524 return getNumSuccessors();
527 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
528 /// emit the vtable for the class in this translation unit.
529 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
530 assert(0 && "ReturnInst has no successors!");
533 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
534 assert(0 && "ReturnInst has no successors!");
539 ReturnInst::~ReturnInst() {
541 delete [] OperandList;
544 //===----------------------------------------------------------------------===//
545 // UnwindInst Implementation
546 //===----------------------------------------------------------------------===//
548 UnwindInst::UnwindInst(Instruction *InsertBefore)
549 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
551 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
552 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
556 unsigned UnwindInst::getNumSuccessorsV() const {
557 return getNumSuccessors();
560 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
561 assert(0 && "UnwindInst has no successors!");
564 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
565 assert(0 && "UnwindInst has no successors!");
570 //===----------------------------------------------------------------------===//
571 // UnreachableInst Implementation
572 //===----------------------------------------------------------------------===//
574 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
575 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
577 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
578 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
581 unsigned UnreachableInst::getNumSuccessorsV() const {
582 return getNumSuccessors();
585 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
586 assert(0 && "UnwindInst has no successors!");
589 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
590 assert(0 && "UnwindInst has no successors!");
595 //===----------------------------------------------------------------------===//
596 // BranchInst Implementation
597 //===----------------------------------------------------------------------===//
599 void BranchInst::AssertOK() {
601 assert(getCondition()->getType() == Type::Int1Ty &&
602 "May only branch on boolean predicates!");
605 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
606 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
607 assert(IfTrue != 0 && "Branch destination may not be null!");
608 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
610 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
611 Instruction *InsertBefore)
612 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
613 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
614 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
615 Ops[2].init(Cond, this);
621 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
622 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
623 assert(IfTrue != 0 && "Branch destination may not be null!");
624 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
627 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
628 BasicBlock *InsertAtEnd)
629 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
630 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
631 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
632 Ops[2].init(Cond, this);
639 BranchInst::BranchInst(const BranchInst &BI) :
640 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
641 OperandList[0].init(BI.getOperand(0), this);
642 if (BI.getNumOperands() != 1) {
643 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
644 OperandList[1].init(BI.getOperand(1), this);
645 OperandList[2].init(BI.getOperand(2), this);
649 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
650 return getSuccessor(idx);
652 unsigned BranchInst::getNumSuccessorsV() const {
653 return getNumSuccessors();
655 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
656 setSuccessor(idx, B);
660 //===----------------------------------------------------------------------===//
661 // AllocationInst Implementation
662 //===----------------------------------------------------------------------===//
664 static Value *getAISize(Value *Amt) {
666 Amt = ConstantInt::get(Type::Int32Ty, 1);
668 assert(!isa<BasicBlock>(Amt) &&
669 "Passed basic block into allocation size parameter! Use other ctor");
670 assert(Amt->getType() == Type::Int32Ty &&
671 "Malloc/Allocation array size is not a 32-bit integer!");
676 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
677 unsigned Align, const std::string &Name,
678 Instruction *InsertBefore)
679 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
680 InsertBefore), Alignment(Align) {
681 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
682 assert(Ty != Type::VoidTy && "Cannot allocate void!");
686 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
687 unsigned Align, const std::string &Name,
688 BasicBlock *InsertAtEnd)
689 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
690 InsertAtEnd), Alignment(Align) {
691 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
692 assert(Ty != Type::VoidTy && "Cannot allocate void!");
696 // Out of line virtual method, so the vtable, etc has a home.
697 AllocationInst::~AllocationInst() {
700 bool AllocationInst::isArrayAllocation() const {
701 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
702 return CI->getZExtValue() != 1;
706 const Type *AllocationInst::getAllocatedType() const {
707 return getType()->getElementType();
710 AllocaInst::AllocaInst(const AllocaInst &AI)
711 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
712 Instruction::Alloca, AI.getAlignment()) {
715 MallocInst::MallocInst(const MallocInst &MI)
716 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
717 Instruction::Malloc, MI.getAlignment()) {
720 //===----------------------------------------------------------------------===//
721 // FreeInst Implementation
722 //===----------------------------------------------------------------------===//
724 void FreeInst::AssertOK() {
725 assert(isa<PointerType>(getOperand(0)->getType()) &&
726 "Can not free something of nonpointer type!");
729 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
730 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
734 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
735 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
740 //===----------------------------------------------------------------------===//
741 // LoadInst Implementation
742 //===----------------------------------------------------------------------===//
744 void LoadInst::AssertOK() {
745 assert(isa<PointerType>(getOperand(0)->getType()) &&
746 "Ptr must have pointer type.");
749 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
750 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
751 Load, Ptr, InsertBef) {
758 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
759 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
760 Load, Ptr, InsertAE) {
767 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
768 Instruction *InsertBef)
769 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
770 Load, Ptr, InsertBef) {
771 setVolatile(isVolatile);
777 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
778 unsigned Align, Instruction *InsertBef)
779 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
780 Load, Ptr, InsertBef) {
781 setVolatile(isVolatile);
787 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
788 unsigned Align, BasicBlock *InsertAE)
789 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
790 Load, Ptr, InsertAE) {
791 setVolatile(isVolatile);
797 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
798 BasicBlock *InsertAE)
799 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
800 Load, Ptr, InsertAE) {
801 setVolatile(isVolatile);
809 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
810 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
811 Load, Ptr, InsertBef) {
815 if (Name && Name[0]) setName(Name);
818 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
819 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
820 Load, Ptr, InsertAE) {
824 if (Name && Name[0]) setName(Name);
827 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
828 Instruction *InsertBef)
829 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
830 Load, Ptr, InsertBef) {
831 setVolatile(isVolatile);
834 if (Name && Name[0]) setName(Name);
837 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
838 BasicBlock *InsertAE)
839 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
840 Load, Ptr, InsertAE) {
841 setVolatile(isVolatile);
844 if (Name && Name[0]) setName(Name);
847 void LoadInst::setAlignment(unsigned Align) {
848 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
849 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
852 //===----------------------------------------------------------------------===//
853 // StoreInst Implementation
854 //===----------------------------------------------------------------------===//
856 void StoreInst::AssertOK() {
857 assert(isa<PointerType>(getOperand(1)->getType()) &&
858 "Ptr must have pointer type!");
859 assert(getOperand(0)->getType() ==
860 cast<PointerType>(getOperand(1)->getType())->getElementType()
861 && "Ptr must be a pointer to Val type!");
865 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
866 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
867 Ops[0].init(val, this);
868 Ops[1].init(addr, this);
874 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
875 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
876 Ops[0].init(val, this);
877 Ops[1].init(addr, this);
883 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
884 Instruction *InsertBefore)
885 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
886 Ops[0].init(val, this);
887 Ops[1].init(addr, this);
888 setVolatile(isVolatile);
893 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
894 unsigned Align, Instruction *InsertBefore)
895 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
896 Ops[0].init(val, this);
897 Ops[1].init(addr, this);
898 setVolatile(isVolatile);
903 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
904 unsigned Align, BasicBlock *InsertAtEnd)
905 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
906 Ops[0].init(val, this);
907 Ops[1].init(addr, this);
908 setVolatile(isVolatile);
913 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
914 BasicBlock *InsertAtEnd)
915 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
916 Ops[0].init(val, this);
917 Ops[1].init(addr, this);
918 setVolatile(isVolatile);
923 void StoreInst::setAlignment(unsigned Align) {
924 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
925 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
928 //===----------------------------------------------------------------------===//
929 // GetElementPtrInst Implementation
930 //===----------------------------------------------------------------------===//
932 static unsigned retrieveAddrSpace(const Value *Val) {
933 return cast<PointerType>(Val->getType())->getAddressSpace();
936 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
937 NumOperands = 1+NumIdx;
938 Use *OL = OperandList = new Use[NumOperands];
939 OL[0].init(Ptr, this);
941 for (unsigned i = 0; i != NumIdx; ++i)
942 OL[i+1].init(Idx[i], this);
945 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
947 Use *OL = OperandList = new Use[2];
948 OL[0].init(Ptr, this);
949 OL[1].init(Idx, this);
952 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
953 const std::string &Name, Instruction *InBe)
954 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
955 retrieveAddrSpace(Ptr)),
956 GetElementPtr, 0, 0, InBe) {
961 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
962 const std::string &Name, BasicBlock *IAE)
963 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
964 retrieveAddrSpace(Ptr)),
965 GetElementPtr, 0, 0, IAE) {
970 GetElementPtrInst::~GetElementPtrInst() {
971 delete[] OperandList;
974 // getIndexedType - Returns the type of the element that would be loaded with
975 // a load instruction with the specified parameters.
977 // A null type is returned if the indices are invalid for the specified
980 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
983 bool AllowCompositeLeaf) {
984 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
986 // Handle the special case of the empty set index set...
988 if (AllowCompositeLeaf ||
989 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
990 return cast<PointerType>(Ptr)->getElementType();
996 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
997 if (NumIdx == CurIdx) {
998 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
999 return 0; // Can't load a whole structure or array!?!?
1002 Value *Index = Idxs[CurIdx++];
1003 if (isa<PointerType>(CT) && CurIdx != 1)
1004 return 0; // Can only index into pointer types at the first index!
1005 if (!CT->indexValid(Index)) return 0;
1006 Ptr = CT->getTypeAtIndex(Index);
1008 // If the new type forwards to another type, then it is in the middle
1009 // of being refined to another type (and hence, may have dropped all
1010 // references to what it was using before). So, use the new forwarded
1012 if (const Type * Ty = Ptr->getForwardedType()) {
1016 return CurIdx == NumIdx ? Ptr : 0;
1019 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1020 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1021 if (!PTy) return 0; // Type isn't a pointer type!
1023 // Check the pointer index.
1024 if (!PTy->indexValid(Idx)) return 0;
1026 return PTy->getElementType();
1030 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1031 /// zeros. If so, the result pointer and the first operand have the same
1032 /// value, just potentially different types.
1033 bool GetElementPtrInst::hasAllZeroIndices() const {
1034 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1035 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1036 if (!CI->isZero()) return false;
1044 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1045 /// constant integers. If so, the result pointer and the first operand have
1046 /// a constant offset between them.
1047 bool GetElementPtrInst::hasAllConstantIndices() const {
1048 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1049 if (!isa<ConstantInt>(getOperand(i)))
1056 //===----------------------------------------------------------------------===//
1057 // ExtractElementInst Implementation
1058 //===----------------------------------------------------------------------===//
1060 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1061 const std::string &Name,
1062 Instruction *InsertBef)
1063 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1064 ExtractElement, Ops, 2, InsertBef) {
1065 assert(isValidOperands(Val, Index) &&
1066 "Invalid extractelement instruction operands!");
1067 Ops[0].init(Val, this);
1068 Ops[1].init(Index, this);
1072 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1073 const std::string &Name,
1074 Instruction *InsertBef)
1075 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1076 ExtractElement, Ops, 2, InsertBef) {
1077 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1078 assert(isValidOperands(Val, Index) &&
1079 "Invalid extractelement instruction operands!");
1080 Ops[0].init(Val, this);
1081 Ops[1].init(Index, this);
1086 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1087 const std::string &Name,
1088 BasicBlock *InsertAE)
1089 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1090 ExtractElement, Ops, 2, InsertAE) {
1091 assert(isValidOperands(Val, Index) &&
1092 "Invalid extractelement instruction operands!");
1094 Ops[0].init(Val, this);
1095 Ops[1].init(Index, this);
1099 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1100 const std::string &Name,
1101 BasicBlock *InsertAE)
1102 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1103 ExtractElement, Ops, 2, InsertAE) {
1104 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1105 assert(isValidOperands(Val, Index) &&
1106 "Invalid extractelement instruction operands!");
1108 Ops[0].init(Val, this);
1109 Ops[1].init(Index, this);
1114 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1115 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1121 //===----------------------------------------------------------------------===//
1122 // InsertElementInst Implementation
1123 //===----------------------------------------------------------------------===//
1125 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1126 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1127 Ops[0].init(IE.Ops[0], this);
1128 Ops[1].init(IE.Ops[1], this);
1129 Ops[2].init(IE.Ops[2], this);
1131 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1132 const std::string &Name,
1133 Instruction *InsertBef)
1134 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1135 assert(isValidOperands(Vec, Elt, Index) &&
1136 "Invalid insertelement instruction operands!");
1137 Ops[0].init(Vec, this);
1138 Ops[1].init(Elt, this);
1139 Ops[2].init(Index, this);
1143 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1144 const std::string &Name,
1145 Instruction *InsertBef)
1146 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1147 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1148 assert(isValidOperands(Vec, Elt, Index) &&
1149 "Invalid insertelement instruction operands!");
1150 Ops[0].init(Vec, this);
1151 Ops[1].init(Elt, this);
1152 Ops[2].init(Index, this);
1157 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1158 const std::string &Name,
1159 BasicBlock *InsertAE)
1160 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1161 assert(isValidOperands(Vec, Elt, Index) &&
1162 "Invalid insertelement instruction operands!");
1164 Ops[0].init(Vec, this);
1165 Ops[1].init(Elt, this);
1166 Ops[2].init(Index, this);
1170 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1171 const std::string &Name,
1172 BasicBlock *InsertAE)
1173 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1174 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1175 assert(isValidOperands(Vec, Elt, Index) &&
1176 "Invalid insertelement instruction operands!");
1178 Ops[0].init(Vec, this);
1179 Ops[1].init(Elt, this);
1180 Ops[2].init(Index, this);
1184 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1185 const Value *Index) {
1186 if (!isa<VectorType>(Vec->getType()))
1187 return false; // First operand of insertelement must be vector type.
1189 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1190 return false;// Second operand of insertelement must be vector element type.
1192 if (Index->getType() != Type::Int32Ty)
1193 return false; // Third operand of insertelement must be uint.
1198 //===----------------------------------------------------------------------===//
1199 // ShuffleVectorInst Implementation
1200 //===----------------------------------------------------------------------===//
1202 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1203 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1204 Ops[0].init(SV.Ops[0], this);
1205 Ops[1].init(SV.Ops[1], this);
1206 Ops[2].init(SV.Ops[2], this);
1209 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1210 const std::string &Name,
1211 Instruction *InsertBefore)
1212 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1213 assert(isValidOperands(V1, V2, Mask) &&
1214 "Invalid shuffle vector instruction operands!");
1215 Ops[0].init(V1, this);
1216 Ops[1].init(V2, this);
1217 Ops[2].init(Mask, this);
1221 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1222 const std::string &Name,
1223 BasicBlock *InsertAtEnd)
1224 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1225 assert(isValidOperands(V1, V2, Mask) &&
1226 "Invalid shuffle vector instruction operands!");
1228 Ops[0].init(V1, this);
1229 Ops[1].init(V2, this);
1230 Ops[2].init(Mask, this);
1234 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1235 const Value *Mask) {
1236 if (!isa<VectorType>(V1->getType()) ||
1237 V1->getType() != V2->getType())
1240 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1241 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1242 MaskTy->getElementType() != Type::Int32Ty ||
1243 MaskTy->getNumElements() !=
1244 cast<VectorType>(V1->getType())->getNumElements())
1249 /// getMaskValue - Return the index from the shuffle mask for the specified
1250 /// output result. This is either -1 if the element is undef or a number less
1251 /// than 2*numelements.
1252 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1253 const Constant *Mask = cast<Constant>(getOperand(2));
1254 if (isa<UndefValue>(Mask)) return -1;
1255 if (isa<ConstantAggregateZero>(Mask)) return 0;
1256 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1257 assert(i < MaskCV->getNumOperands() && "Index out of range");
1259 if (isa<UndefValue>(MaskCV->getOperand(i)))
1261 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1265 //===----------------------------------------------------------------------===//
1266 // BinaryOperator Class
1267 //===----------------------------------------------------------------------===//
1269 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1270 const Type *Ty, const std::string &Name,
1271 Instruction *InsertBefore)
1272 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1273 Ops[0].init(S1, this);
1274 Ops[1].init(S2, this);
1279 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1280 const Type *Ty, const std::string &Name,
1281 BasicBlock *InsertAtEnd)
1282 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1283 Ops[0].init(S1, this);
1284 Ops[1].init(S2, this);
1290 void BinaryOperator::init(BinaryOps iType) {
1291 Value *LHS = getOperand(0), *RHS = getOperand(1);
1292 LHS = LHS; RHS = RHS; // Silence warnings.
1293 assert(LHS->getType() == RHS->getType() &&
1294 "Binary operator operand types must match!");
1299 assert(getType() == LHS->getType() &&
1300 "Arithmetic operation should return same type as operands!");
1301 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1302 isa<VectorType>(getType())) &&
1303 "Tried to create an arithmetic operation on a non-arithmetic type!");
1307 assert(getType() == LHS->getType() &&
1308 "Arithmetic operation should return same type as operands!");
1309 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1310 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1311 "Incorrect operand type (not integer) for S/UDIV");
1314 assert(getType() == LHS->getType() &&
1315 "Arithmetic operation should return same type as operands!");
1316 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1317 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1318 && "Incorrect operand type (not floating point) for FDIV");
1322 assert(getType() == LHS->getType() &&
1323 "Arithmetic operation should return same type as operands!");
1324 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1325 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1326 "Incorrect operand type (not integer) for S/UREM");
1329 assert(getType() == LHS->getType() &&
1330 "Arithmetic operation should return same type as operands!");
1331 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1332 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1333 && "Incorrect operand type (not floating point) for FREM");
1338 assert(getType() == LHS->getType() &&
1339 "Shift operation should return same type as operands!");
1340 assert(getType()->isInteger() &&
1341 "Shift operation requires integer operands");
1345 assert(getType() == LHS->getType() &&
1346 "Logical operation should return same type as operands!");
1347 assert((getType()->isInteger() ||
1348 (isa<VectorType>(getType()) &&
1349 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1350 "Tried to create a logical operation on a non-integral type!");
1358 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1359 const std::string &Name,
1360 Instruction *InsertBefore) {
1361 assert(S1->getType() == S2->getType() &&
1362 "Cannot create binary operator with two operands of differing type!");
1363 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1366 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1367 const std::string &Name,
1368 BasicBlock *InsertAtEnd) {
1369 BinaryOperator *Res = create(Op, S1, S2, Name);
1370 InsertAtEnd->getInstList().push_back(Res);
1374 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1375 Instruction *InsertBefore) {
1376 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1377 return new BinaryOperator(Instruction::Sub,
1379 Op->getType(), Name, InsertBefore);
1382 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1383 BasicBlock *InsertAtEnd) {
1384 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1385 return new BinaryOperator(Instruction::Sub,
1387 Op->getType(), Name, InsertAtEnd);
1390 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1391 Instruction *InsertBefore) {
1393 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1394 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1395 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1397 C = ConstantInt::getAllOnesValue(Op->getType());
1400 return new BinaryOperator(Instruction::Xor, Op, C,
1401 Op->getType(), Name, InsertBefore);
1404 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1405 BasicBlock *InsertAtEnd) {
1407 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1408 // Create a vector of all ones values.
1409 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1411 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1413 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1416 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1417 Op->getType(), Name, InsertAtEnd);
1421 // isConstantAllOnes - Helper function for several functions below
1422 static inline bool isConstantAllOnes(const Value *V) {
1423 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1424 return CI->isAllOnesValue();
1425 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1426 return CV->isAllOnesValue();
1430 bool BinaryOperator::isNeg(const Value *V) {
1431 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1432 if (Bop->getOpcode() == Instruction::Sub)
1433 return Bop->getOperand(0) ==
1434 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1438 bool BinaryOperator::isNot(const Value *V) {
1439 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1440 return (Bop->getOpcode() == Instruction::Xor &&
1441 (isConstantAllOnes(Bop->getOperand(1)) ||
1442 isConstantAllOnes(Bop->getOperand(0))));
1446 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1447 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1448 return cast<BinaryOperator>(BinOp)->getOperand(1);
1451 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1452 return getNegArgument(const_cast<Value*>(BinOp));
1455 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1456 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1457 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1458 Value *Op0 = BO->getOperand(0);
1459 Value *Op1 = BO->getOperand(1);
1460 if (isConstantAllOnes(Op0)) return Op1;
1462 assert(isConstantAllOnes(Op1));
1466 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1467 return getNotArgument(const_cast<Value*>(BinOp));
1471 // swapOperands - Exchange the two operands to this instruction. This
1472 // instruction is safe to use on any binary instruction and does not
1473 // modify the semantics of the instruction. If the instruction is
1474 // order dependent (SetLT f.e.) the opcode is changed.
1476 bool BinaryOperator::swapOperands() {
1477 if (!isCommutative())
1478 return true; // Can't commute operands
1479 std::swap(Ops[0], Ops[1]);
1483 //===----------------------------------------------------------------------===//
1485 //===----------------------------------------------------------------------===//
1487 // Just determine if this cast only deals with integral->integral conversion.
1488 bool CastInst::isIntegerCast() const {
1489 switch (getOpcode()) {
1490 default: return false;
1491 case Instruction::ZExt:
1492 case Instruction::SExt:
1493 case Instruction::Trunc:
1495 case Instruction::BitCast:
1496 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1500 bool CastInst::isLosslessCast() const {
1501 // Only BitCast can be lossless, exit fast if we're not BitCast
1502 if (getOpcode() != Instruction::BitCast)
1505 // Identity cast is always lossless
1506 const Type* SrcTy = getOperand(0)->getType();
1507 const Type* DstTy = getType();
1511 // Pointer to pointer is always lossless.
1512 if (isa<PointerType>(SrcTy))
1513 return isa<PointerType>(DstTy);
1514 return false; // Other types have no identity values
1517 /// This function determines if the CastInst does not require any bits to be
1518 /// changed in order to effect the cast. Essentially, it identifies cases where
1519 /// no code gen is necessary for the cast, hence the name no-op cast. For
1520 /// example, the following are all no-op casts:
1521 /// # bitcast uint %X, int
1522 /// # bitcast uint* %x, sbyte*
1523 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1524 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1525 /// @brief Determine if a cast is a no-op.
1526 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1527 switch (getOpcode()) {
1529 assert(!"Invalid CastOp");
1530 case Instruction::Trunc:
1531 case Instruction::ZExt:
1532 case Instruction::SExt:
1533 case Instruction::FPTrunc:
1534 case Instruction::FPExt:
1535 case Instruction::UIToFP:
1536 case Instruction::SIToFP:
1537 case Instruction::FPToUI:
1538 case Instruction::FPToSI:
1539 return false; // These always modify bits
1540 case Instruction::BitCast:
1541 return true; // BitCast never modifies bits.
1542 case Instruction::PtrToInt:
1543 return IntPtrTy->getPrimitiveSizeInBits() ==
1544 getType()->getPrimitiveSizeInBits();
1545 case Instruction::IntToPtr:
1546 return IntPtrTy->getPrimitiveSizeInBits() ==
1547 getOperand(0)->getType()->getPrimitiveSizeInBits();
1551 /// This function determines if a pair of casts can be eliminated and what
1552 /// opcode should be used in the elimination. This assumes that there are two
1553 /// instructions like this:
1554 /// * %F = firstOpcode SrcTy %x to MidTy
1555 /// * %S = secondOpcode MidTy %F to DstTy
1556 /// The function returns a resultOpcode so these two casts can be replaced with:
1557 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1558 /// If no such cast is permited, the function returns 0.
1559 unsigned CastInst::isEliminableCastPair(
1560 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1561 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1563 // Define the 144 possibilities for these two cast instructions. The values
1564 // in this matrix determine what to do in a given situation and select the
1565 // case in the switch below. The rows correspond to firstOp, the columns
1566 // correspond to secondOp. In looking at the table below, keep in mind
1567 // the following cast properties:
1569 // Size Compare Source Destination
1570 // Operator Src ? Size Type Sign Type Sign
1571 // -------- ------------ ------------------- ---------------------
1572 // TRUNC > Integer Any Integral Any
1573 // ZEXT < Integral Unsigned Integer Any
1574 // SEXT < Integral Signed Integer Any
1575 // FPTOUI n/a FloatPt n/a Integral Unsigned
1576 // FPTOSI n/a FloatPt n/a Integral Signed
1577 // UITOFP n/a Integral Unsigned FloatPt n/a
1578 // SITOFP n/a Integral Signed FloatPt n/a
1579 // FPTRUNC > FloatPt n/a FloatPt n/a
1580 // FPEXT < FloatPt n/a FloatPt n/a
1581 // PTRTOINT n/a Pointer n/a Integral Unsigned
1582 // INTTOPTR n/a Integral Unsigned Pointer n/a
1583 // BITCONVERT = FirstClass n/a FirstClass n/a
1585 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1586 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1587 // into "fptoui double to ulong", but this loses information about the range
1588 // of the produced value (we no longer know the top-part is all zeros).
1589 // Further this conversion is often much more expensive for typical hardware,
1590 // and causes issues when building libgcc. We disallow fptosi+sext for the
1592 const unsigned numCastOps =
1593 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1594 static const uint8_t CastResults[numCastOps][numCastOps] = {
1595 // T F F U S F F P I B -+
1596 // R Z S P P I I T P 2 N T |
1597 // U E E 2 2 2 2 R E I T C +- secondOp
1598 // N X X U S F F N X N 2 V |
1599 // C T T I I P P C T T P T -+
1600 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1601 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1602 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1603 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1604 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1605 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1606 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1607 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1608 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1609 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1610 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1611 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1614 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1615 [secondOp-Instruction::CastOpsBegin];
1618 // categorically disallowed
1621 // allowed, use first cast's opcode
1624 // allowed, use second cast's opcode
1627 // no-op cast in second op implies firstOp as long as the DestTy
1629 if (DstTy->isInteger())
1633 // no-op cast in second op implies firstOp as long as the DestTy
1634 // is floating point
1635 if (DstTy->isFloatingPoint())
1639 // no-op cast in first op implies secondOp as long as the SrcTy
1641 if (SrcTy->isInteger())
1645 // no-op cast in first op implies secondOp as long as the SrcTy
1646 // is a floating point
1647 if (SrcTy->isFloatingPoint())
1651 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1652 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1653 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1654 if (MidSize >= PtrSize)
1655 return Instruction::BitCast;
1659 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1660 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1661 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1662 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1663 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1664 if (SrcSize == DstSize)
1665 return Instruction::BitCast;
1666 else if (SrcSize < DstSize)
1670 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1671 return Instruction::ZExt;
1673 // fpext followed by ftrunc is allowed if the bit size returned to is
1674 // the same as the original, in which case its just a bitcast
1676 return Instruction::BitCast;
1677 return 0; // If the types are not the same we can't eliminate it.
1679 // bitcast followed by ptrtoint is allowed as long as the bitcast
1680 // is a pointer to pointer cast.
1681 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1685 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1686 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1690 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1691 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1692 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1693 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1694 if (SrcSize <= PtrSize && SrcSize == DstSize)
1695 return Instruction::BitCast;
1699 // cast combination can't happen (error in input). This is for all cases
1700 // where the MidTy is not the same for the two cast instructions.
1701 assert(!"Invalid Cast Combination");
1704 assert(!"Error in CastResults table!!!");
1710 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1711 const std::string &Name, Instruction *InsertBefore) {
1712 // Construct and return the appropriate CastInst subclass
1714 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1715 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1716 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1717 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1718 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1719 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1720 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1721 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1722 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1723 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1724 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1725 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1727 assert(!"Invalid opcode provided");
1732 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1733 const std::string &Name, BasicBlock *InsertAtEnd) {
1734 // Construct and return the appropriate CastInst subclass
1736 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1737 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1738 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1739 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1740 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1741 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1742 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1743 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1744 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1745 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1746 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1747 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1749 assert(!"Invalid opcode provided");
1754 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1755 const std::string &Name,
1756 Instruction *InsertBefore) {
1757 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1758 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1759 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1762 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1763 const std::string &Name,
1764 BasicBlock *InsertAtEnd) {
1765 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1766 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1767 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1770 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1771 const std::string &Name,
1772 Instruction *InsertBefore) {
1773 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1774 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1775 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1778 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1779 const std::string &Name,
1780 BasicBlock *InsertAtEnd) {
1781 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1782 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1783 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1786 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1787 const std::string &Name,
1788 Instruction *InsertBefore) {
1789 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1790 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1791 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1794 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1795 const std::string &Name,
1796 BasicBlock *InsertAtEnd) {
1797 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1798 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1799 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1802 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1803 const std::string &Name,
1804 BasicBlock *InsertAtEnd) {
1805 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1806 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1809 if (Ty->isInteger())
1810 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1811 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1814 /// @brief Create a BitCast or a PtrToInt cast instruction
1815 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1816 const std::string &Name,
1817 Instruction *InsertBefore) {
1818 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1819 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1822 if (Ty->isInteger())
1823 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1824 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1827 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1828 bool isSigned, const std::string &Name,
1829 Instruction *InsertBefore) {
1830 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1831 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1832 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1833 Instruction::CastOps opcode =
1834 (SrcBits == DstBits ? Instruction::BitCast :
1835 (SrcBits > DstBits ? Instruction::Trunc :
1836 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1837 return create(opcode, C, Ty, Name, InsertBefore);
1840 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1841 bool isSigned, const std::string &Name,
1842 BasicBlock *InsertAtEnd) {
1843 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1844 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1845 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1846 Instruction::CastOps opcode =
1847 (SrcBits == DstBits ? Instruction::BitCast :
1848 (SrcBits > DstBits ? Instruction::Trunc :
1849 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1850 return create(opcode, C, Ty, Name, InsertAtEnd);
1853 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1854 const std::string &Name,
1855 Instruction *InsertBefore) {
1856 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1858 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1859 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1860 Instruction::CastOps opcode =
1861 (SrcBits == DstBits ? Instruction::BitCast :
1862 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1863 return create(opcode, C, Ty, Name, InsertBefore);
1866 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1867 const std::string &Name,
1868 BasicBlock *InsertAtEnd) {
1869 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1871 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1872 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1873 Instruction::CastOps opcode =
1874 (SrcBits == DstBits ? Instruction::BitCast :
1875 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1876 return create(opcode, C, Ty, Name, InsertAtEnd);
1879 // Check whether it is valid to call getCastOpcode for these types.
1880 // This routine must be kept in sync with getCastOpcode.
1881 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
1882 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
1885 if (SrcTy == DestTy)
1888 // Get the bit sizes, we'll need these
1889 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1890 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1892 // Run through the possibilities ...
1893 if (DestTy->isInteger()) { // Casting to integral
1894 if (SrcTy->isInteger()) { // Casting from integral
1896 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1898 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1899 // Casting from vector
1900 return DestBits == PTy->getBitWidth();
1901 } else { // Casting from something else
1902 return isa<PointerType>(SrcTy);
1904 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1905 if (SrcTy->isInteger()) { // Casting from integral
1907 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1909 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1910 // Casting from vector
1911 return DestBits == PTy->getBitWidth();
1912 } else { // Casting from something else
1915 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1916 // Casting to vector
1917 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1918 // Casting from vector
1919 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
1920 } else { // Casting from something else
1921 return DestPTy->getBitWidth() == SrcBits;
1923 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
1924 if (isa<PointerType>(SrcTy)) { // Casting from pointer
1926 } else if (SrcTy->isInteger()) { // Casting from integral
1928 } else { // Casting from something else
1931 } else { // Casting to something else
1936 // Provide a way to get a "cast" where the cast opcode is inferred from the
1937 // types and size of the operand. This, basically, is a parallel of the
1938 // logic in the castIsValid function below. This axiom should hold:
1939 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1940 // should not assert in castIsValid. In other words, this produces a "correct"
1941 // casting opcode for the arguments passed to it.
1942 // This routine must be kept in sync with isCastable.
1943 Instruction::CastOps
1944 CastInst::getCastOpcode(
1945 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1946 // Get the bit sizes, we'll need these
1947 const Type *SrcTy = Src->getType();
1948 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1949 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1951 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
1952 "Only first class types are castable!");
1954 // Run through the possibilities ...
1955 if (DestTy->isInteger()) { // Casting to integral
1956 if (SrcTy->isInteger()) { // Casting from integral
1957 if (DestBits < SrcBits)
1958 return Trunc; // int -> smaller int
1959 else if (DestBits > SrcBits) { // its an extension
1961 return SExt; // signed -> SEXT
1963 return ZExt; // unsigned -> ZEXT
1965 return BitCast; // Same size, No-op cast
1967 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1969 return FPToSI; // FP -> sint
1971 return FPToUI; // FP -> uint
1972 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1973 assert(DestBits == PTy->getBitWidth() &&
1974 "Casting vector to integer of different width");
1975 return BitCast; // Same size, no-op cast
1977 assert(isa<PointerType>(SrcTy) &&
1978 "Casting from a value that is not first-class type");
1979 return PtrToInt; // ptr -> int
1981 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1982 if (SrcTy->isInteger()) { // Casting from integral
1984 return SIToFP; // sint -> FP
1986 return UIToFP; // uint -> FP
1987 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1988 if (DestBits < SrcBits) {
1989 return FPTrunc; // FP -> smaller FP
1990 } else if (DestBits > SrcBits) {
1991 return FPExt; // FP -> larger FP
1993 return BitCast; // same size, no-op cast
1995 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1996 assert(DestBits == PTy->getBitWidth() &&
1997 "Casting vector to floating point of different width");
1998 return BitCast; // same size, no-op cast
2000 assert(0 && "Casting pointer or non-first class to float");
2002 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2003 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2004 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2005 "Casting vector to vector of different widths");
2006 return BitCast; // vector -> vector
2007 } else if (DestPTy->getBitWidth() == SrcBits) {
2008 return BitCast; // float/int -> vector
2010 assert(!"Illegal cast to vector (wrong type or size)");
2012 } else if (isa<PointerType>(DestTy)) {
2013 if (isa<PointerType>(SrcTy)) {
2014 return BitCast; // ptr -> ptr
2015 } else if (SrcTy->isInteger()) {
2016 return IntToPtr; // int -> ptr
2018 assert(!"Casting pointer to other than pointer or int");
2021 assert(!"Casting to type that is not first-class");
2024 // If we fall through to here we probably hit an assertion cast above
2025 // and assertions are not turned on. Anything we return is an error, so
2026 // BitCast is as good a choice as any.
2030 //===----------------------------------------------------------------------===//
2031 // CastInst SubClass Constructors
2032 //===----------------------------------------------------------------------===//
2034 /// Check that the construction parameters for a CastInst are correct. This
2035 /// could be broken out into the separate constructors but it is useful to have
2036 /// it in one place and to eliminate the redundant code for getting the sizes
2037 /// of the types involved.
2039 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2041 // Check for type sanity on the arguments
2042 const Type *SrcTy = S->getType();
2043 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2046 // Get the size of the types in bits, we'll need this later
2047 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2048 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2050 // Switch on the opcode provided
2052 default: return false; // This is an input error
2053 case Instruction::Trunc:
2054 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2055 case Instruction::ZExt:
2056 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2057 case Instruction::SExt:
2058 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2059 case Instruction::FPTrunc:
2060 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2061 SrcBitSize > DstBitSize;
2062 case Instruction::FPExt:
2063 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2064 SrcBitSize < DstBitSize;
2065 case Instruction::UIToFP:
2066 case Instruction::SIToFP:
2067 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2068 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2069 return SVTy->getElementType()->isInteger() &&
2070 DVTy->getElementType()->isFloatingPoint() &&
2071 SVTy->getNumElements() == DVTy->getNumElements();
2074 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2075 case Instruction::FPToUI:
2076 case Instruction::FPToSI:
2077 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2078 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2079 return SVTy->getElementType()->isFloatingPoint() &&
2080 DVTy->getElementType()->isInteger() &&
2081 SVTy->getNumElements() == DVTy->getNumElements();
2084 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2085 case Instruction::PtrToInt:
2086 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2087 case Instruction::IntToPtr:
2088 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2089 case Instruction::BitCast:
2090 // BitCast implies a no-op cast of type only. No bits change.
2091 // However, you can't cast pointers to anything but pointers.
2092 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2095 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2096 // these cases, the cast is okay if the source and destination bit widths
2098 return SrcBitSize == DstBitSize;
2102 TruncInst::TruncInst(
2103 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2104 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2105 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2108 TruncInst::TruncInst(
2109 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2110 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2111 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2115 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2116 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2117 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2121 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2122 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2123 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2126 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2127 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2128 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2132 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2133 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2134 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2137 FPTruncInst::FPTruncInst(
2138 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2139 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2140 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2143 FPTruncInst::FPTruncInst(
2144 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2145 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2146 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2149 FPExtInst::FPExtInst(
2150 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2151 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2152 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2155 FPExtInst::FPExtInst(
2156 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2157 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2158 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2161 UIToFPInst::UIToFPInst(
2162 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2163 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2164 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2167 UIToFPInst::UIToFPInst(
2168 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2169 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2170 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2173 SIToFPInst::SIToFPInst(
2174 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2175 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2176 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2179 SIToFPInst::SIToFPInst(
2180 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2181 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2182 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2185 FPToUIInst::FPToUIInst(
2186 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2187 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2188 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2191 FPToUIInst::FPToUIInst(
2192 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2193 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2194 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2197 FPToSIInst::FPToSIInst(
2198 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2199 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2200 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2203 FPToSIInst::FPToSIInst(
2204 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2205 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2206 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2209 PtrToIntInst::PtrToIntInst(
2210 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2211 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2212 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2215 PtrToIntInst::PtrToIntInst(
2216 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2217 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2218 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2221 IntToPtrInst::IntToPtrInst(
2222 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2223 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2224 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2227 IntToPtrInst::IntToPtrInst(
2228 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2229 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2230 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2233 BitCastInst::BitCastInst(
2234 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2235 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2236 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2239 BitCastInst::BitCastInst(
2240 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2241 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2242 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2245 //===----------------------------------------------------------------------===//
2247 //===----------------------------------------------------------------------===//
2249 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2250 const std::string &Name, Instruction *InsertBefore)
2251 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2252 Ops[0].init(LHS, this);
2253 Ops[1].init(RHS, this);
2254 SubclassData = predicate;
2256 if (op == Instruction::ICmp) {
2257 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2258 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2259 "Invalid ICmp predicate value");
2260 const Type* Op0Ty = getOperand(0)->getType();
2261 const Type* Op1Ty = getOperand(1)->getType();
2262 assert(Op0Ty == Op1Ty &&
2263 "Both operands to ICmp instruction are not of the same type!");
2264 // Check that the operands are the right type
2265 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2266 "Invalid operand types for ICmp instruction");
2269 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2270 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2271 "Invalid FCmp predicate value");
2272 const Type* Op0Ty = getOperand(0)->getType();
2273 const Type* Op1Ty = getOperand(1)->getType();
2274 assert(Op0Ty == Op1Ty &&
2275 "Both operands to FCmp instruction are not of the same type!");
2276 // Check that the operands are the right type
2277 assert(Op0Ty->isFloatingPoint() &&
2278 "Invalid operand types for FCmp instruction");
2281 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2282 const std::string &Name, BasicBlock *InsertAtEnd)
2283 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2284 Ops[0].init(LHS, this);
2285 Ops[1].init(RHS, this);
2286 SubclassData = predicate;
2288 if (op == Instruction::ICmp) {
2289 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2290 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2291 "Invalid ICmp predicate value");
2293 const Type* Op0Ty = getOperand(0)->getType();
2294 const Type* Op1Ty = getOperand(1)->getType();
2295 assert(Op0Ty == Op1Ty &&
2296 "Both operands to ICmp instruction are not of the same type!");
2297 // Check that the operands are the right type
2298 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2299 "Invalid operand types for ICmp instruction");
2302 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2303 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2304 "Invalid FCmp predicate value");
2305 const Type* Op0Ty = getOperand(0)->getType();
2306 const Type* Op1Ty = getOperand(1)->getType();
2307 assert(Op0Ty == Op1Ty &&
2308 "Both operands to FCmp instruction are not of the same type!");
2309 // Check that the operands are the right type
2310 assert(Op0Ty->isFloatingPoint() &&
2311 "Invalid operand types for FCmp instruction");
2315 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2316 const std::string &Name, Instruction *InsertBefore) {
2317 if (Op == Instruction::ICmp) {
2318 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2321 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2326 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2327 const std::string &Name, BasicBlock *InsertAtEnd) {
2328 if (Op == Instruction::ICmp) {
2329 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2332 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2336 void CmpInst::swapOperands() {
2337 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2340 cast<FCmpInst>(this)->swapOperands();
2343 bool CmpInst::isCommutative() {
2344 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2345 return IC->isCommutative();
2346 return cast<FCmpInst>(this)->isCommutative();
2349 bool CmpInst::isEquality() {
2350 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2351 return IC->isEquality();
2352 return cast<FCmpInst>(this)->isEquality();
2356 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2359 assert(!"Unknown icmp predicate!");
2360 case ICMP_EQ: return ICMP_NE;
2361 case ICMP_NE: return ICMP_EQ;
2362 case ICMP_UGT: return ICMP_ULE;
2363 case ICMP_ULT: return ICMP_UGE;
2364 case ICMP_UGE: return ICMP_ULT;
2365 case ICMP_ULE: return ICMP_UGT;
2366 case ICMP_SGT: return ICMP_SLE;
2367 case ICMP_SLT: return ICMP_SGE;
2368 case ICMP_SGE: return ICMP_SLT;
2369 case ICMP_SLE: return ICMP_SGT;
2373 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2375 default: assert(! "Unknown icmp predicate!");
2376 case ICMP_EQ: case ICMP_NE:
2378 case ICMP_SGT: return ICMP_SLT;
2379 case ICMP_SLT: return ICMP_SGT;
2380 case ICMP_SGE: return ICMP_SLE;
2381 case ICMP_SLE: return ICMP_SGE;
2382 case ICMP_UGT: return ICMP_ULT;
2383 case ICMP_ULT: return ICMP_UGT;
2384 case ICMP_UGE: return ICMP_ULE;
2385 case ICMP_ULE: return ICMP_UGE;
2389 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2391 default: assert(! "Unknown icmp predicate!");
2392 case ICMP_EQ: case ICMP_NE:
2393 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2395 case ICMP_UGT: return ICMP_SGT;
2396 case ICMP_ULT: return ICMP_SLT;
2397 case ICMP_UGE: return ICMP_SGE;
2398 case ICMP_ULE: return ICMP_SLE;
2402 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2404 default: assert(! "Unknown icmp predicate!");
2405 case ICMP_EQ: case ICMP_NE:
2406 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2408 case ICMP_SGT: return ICMP_UGT;
2409 case ICMP_SLT: return ICMP_ULT;
2410 case ICMP_SGE: return ICMP_UGE;
2411 case ICMP_SLE: return ICMP_ULE;
2415 bool ICmpInst::isSignedPredicate(Predicate pred) {
2417 default: assert(! "Unknown icmp predicate!");
2418 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2420 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2421 case ICMP_UGE: case ICMP_ULE:
2426 /// Initialize a set of values that all satisfy the condition with C.
2429 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2432 uint32_t BitWidth = C.getBitWidth();
2434 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2435 case ICmpInst::ICMP_EQ: Upper++; break;
2436 case ICmpInst::ICMP_NE: Lower++; break;
2437 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2438 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2439 case ICmpInst::ICMP_UGT:
2440 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2442 case ICmpInst::ICMP_SGT:
2443 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2445 case ICmpInst::ICMP_ULE:
2446 Lower = APInt::getMinValue(BitWidth); Upper++;
2448 case ICmpInst::ICMP_SLE:
2449 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2451 case ICmpInst::ICMP_UGE:
2452 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2454 case ICmpInst::ICMP_SGE:
2455 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2458 return ConstantRange(Lower, Upper);
2461 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2464 assert(!"Unknown icmp predicate!");
2465 case FCMP_OEQ: return FCMP_UNE;
2466 case FCMP_ONE: return FCMP_UEQ;
2467 case FCMP_OGT: return FCMP_ULE;
2468 case FCMP_OLT: return FCMP_UGE;
2469 case FCMP_OGE: return FCMP_ULT;
2470 case FCMP_OLE: return FCMP_UGT;
2471 case FCMP_UEQ: return FCMP_ONE;
2472 case FCMP_UNE: return FCMP_OEQ;
2473 case FCMP_UGT: return FCMP_OLE;
2474 case FCMP_ULT: return FCMP_OGE;
2475 case FCMP_UGE: return FCMP_OLT;
2476 case FCMP_ULE: return FCMP_OGT;
2477 case FCMP_ORD: return FCMP_UNO;
2478 case FCMP_UNO: return FCMP_ORD;
2479 case FCMP_TRUE: return FCMP_FALSE;
2480 case FCMP_FALSE: return FCMP_TRUE;
2484 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2486 default: assert(!"Unknown fcmp predicate!");
2487 case FCMP_FALSE: case FCMP_TRUE:
2488 case FCMP_OEQ: case FCMP_ONE:
2489 case FCMP_UEQ: case FCMP_UNE:
2490 case FCMP_ORD: case FCMP_UNO:
2492 case FCMP_OGT: return FCMP_OLT;
2493 case FCMP_OLT: return FCMP_OGT;
2494 case FCMP_OGE: return FCMP_OLE;
2495 case FCMP_OLE: return FCMP_OGE;
2496 case FCMP_UGT: return FCMP_ULT;
2497 case FCMP_ULT: return FCMP_UGT;
2498 case FCMP_UGE: return FCMP_ULE;
2499 case FCMP_ULE: return FCMP_UGE;
2503 bool CmpInst::isUnsigned(unsigned short predicate) {
2504 switch (predicate) {
2505 default: return false;
2506 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2507 case ICmpInst::ICMP_UGE: return true;
2511 bool CmpInst::isSigned(unsigned short predicate){
2512 switch (predicate) {
2513 default: return false;
2514 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2515 case ICmpInst::ICMP_SGE: return true;
2519 bool CmpInst::isOrdered(unsigned short predicate) {
2520 switch (predicate) {
2521 default: return false;
2522 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2523 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2524 case FCmpInst::FCMP_ORD: return true;
2528 bool CmpInst::isUnordered(unsigned short predicate) {
2529 switch (predicate) {
2530 default: return false;
2531 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2532 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2533 case FCmpInst::FCMP_UNO: return true;
2537 //===----------------------------------------------------------------------===//
2538 // SwitchInst Implementation
2539 //===----------------------------------------------------------------------===//
2541 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2542 assert(Value && Default);
2543 ReservedSpace = 2+NumCases*2;
2545 OperandList = new Use[ReservedSpace];
2547 OperandList[0].init(Value, this);
2548 OperandList[1].init(Default, this);
2551 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2552 /// switch on and a default destination. The number of additional cases can
2553 /// be specified here to make memory allocation more efficient. This
2554 /// constructor can also autoinsert before another instruction.
2555 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2556 Instruction *InsertBefore)
2557 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2558 init(Value, Default, NumCases);
2561 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2562 /// switch on and a default destination. The number of additional cases can
2563 /// be specified here to make memory allocation more efficient. This
2564 /// constructor also autoinserts at the end of the specified BasicBlock.
2565 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2566 BasicBlock *InsertAtEnd)
2567 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2568 init(Value, Default, NumCases);
2571 SwitchInst::SwitchInst(const SwitchInst &SI)
2572 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2573 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2574 Use *OL = OperandList, *InOL = SI.OperandList;
2575 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2576 OL[i].init(InOL[i], this);
2577 OL[i+1].init(InOL[i+1], this);
2581 SwitchInst::~SwitchInst() {
2582 delete [] OperandList;
2586 /// addCase - Add an entry to the switch instruction...
2588 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2589 unsigned OpNo = NumOperands;
2590 if (OpNo+2 > ReservedSpace)
2591 resizeOperands(0); // Get more space!
2592 // Initialize some new operands.
2593 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2594 NumOperands = OpNo+2;
2595 OperandList[OpNo].init(OnVal, this);
2596 OperandList[OpNo+1].init(Dest, this);
2599 /// removeCase - This method removes the specified successor from the switch
2600 /// instruction. Note that this cannot be used to remove the default
2601 /// destination (successor #0).
2603 void SwitchInst::removeCase(unsigned idx) {
2604 assert(idx != 0 && "Cannot remove the default case!");
2605 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2607 unsigned NumOps = getNumOperands();
2608 Use *OL = OperandList;
2610 // Move everything after this operand down.
2612 // FIXME: we could just swap with the end of the list, then erase. However,
2613 // client might not expect this to happen. The code as it is thrashes the
2614 // use/def lists, which is kinda lame.
2615 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2617 OL[i-2+1] = OL[i+1];
2620 // Nuke the last value.
2621 OL[NumOps-2].set(0);
2622 OL[NumOps-2+1].set(0);
2623 NumOperands = NumOps-2;
2626 /// resizeOperands - resize operands - This adjusts the length of the operands
2627 /// list according to the following behavior:
2628 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2629 /// of operation. This grows the number of ops by 1.5 times.
2630 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2631 /// 3. If NumOps == NumOperands, trim the reserved space.
2633 void SwitchInst::resizeOperands(unsigned NumOps) {
2635 NumOps = getNumOperands()/2*6;
2636 } else if (NumOps*2 > NumOperands) {
2637 // No resize needed.
2638 if (ReservedSpace >= NumOps) return;
2639 } else if (NumOps == NumOperands) {
2640 if (ReservedSpace == NumOps) return;
2645 ReservedSpace = NumOps;
2646 Use *NewOps = new Use[NumOps];
2647 Use *OldOps = OperandList;
2648 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2649 NewOps[i].init(OldOps[i], this);
2653 OperandList = NewOps;
2657 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2658 return getSuccessor(idx);
2660 unsigned SwitchInst::getNumSuccessorsV() const {
2661 return getNumSuccessors();
2663 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2664 setSuccessor(idx, B);
2667 //===----------------------------------------------------------------------===//
2668 // GetResultInst Implementation
2669 //===----------------------------------------------------------------------===//
2671 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2672 const std::string &Name,
2673 Instruction *InsertBef)
2674 : Instruction(cast<StructType>(Aggregate->getType())->getElementType(Index),
2675 GetResult, &Aggr, 1, InsertBef) {
2676 assert(isValidOperands(Aggregate, Index) && "Invalid GetResultInst operands!");
2677 Aggr.init(Aggregate, this);
2682 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2686 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2687 unsigned NumElements = STy->getNumElements();
2688 if (Index >= NumElements)
2691 // getresult aggregate value's element types are restricted to
2692 // avoid nested aggregates.
2693 for (unsigned i = 0; i < NumElements; ++i)
2694 if (!STy->getElementType(i)->isFirstClassType())
2697 // Otherwise, Aggregate is valid.
2703 // Define these methods here so vtables don't get emitted into every translation
2704 // unit that uses these classes.
2706 GetElementPtrInst *GetElementPtrInst::clone() const {
2707 return new GetElementPtrInst(*this);
2710 BinaryOperator *BinaryOperator::clone() const {
2711 return create(getOpcode(), Ops[0], Ops[1]);
2714 FCmpInst* FCmpInst::clone() const {
2715 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2717 ICmpInst* ICmpInst::clone() const {
2718 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2721 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2722 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2723 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2724 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2725 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2726 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2727 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2728 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2729 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2730 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2731 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2732 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2733 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2734 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2735 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2736 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2737 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2738 CallInst *CallInst::clone() const { return new CallInst(*this); }
2739 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2740 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2742 ExtractElementInst *ExtractElementInst::clone() const {
2743 return new ExtractElementInst(*this);
2745 InsertElementInst *InsertElementInst::clone() const {
2746 return new InsertElementInst(*this);
2748 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2749 return new ShuffleVectorInst(*this);
2751 PHINode *PHINode::clone() const { return new PHINode(*this); }
2752 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2753 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2754 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2755 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2756 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2757 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2758 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }