1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Support/CallSite.h"
23 unsigned CallSite::getCallingConv() const {
24 if (CallInst *CI = dyn_cast<CallInst>(I))
25 return CI->getCallingConv();
27 return cast<InvokeInst>(I)->getCallingConv();
29 void CallSite::setCallingConv(unsigned CC) {
30 if (CallInst *CI = dyn_cast<CallInst>(I))
31 CI->setCallingConv(CC);
33 cast<InvokeInst>(I)->setCallingConv(CC);
37 //===----------------------------------------------------------------------===//
38 // TerminatorInst Class
39 //===----------------------------------------------------------------------===//
41 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
42 Use *Ops, unsigned NumOps, Instruction *IB)
43 : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IB) {
46 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
47 Use *Ops, unsigned NumOps, BasicBlock *IAE)
48 : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IAE) {
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
57 PHINode::PHINode(const PHINode &PN)
58 : Instruction(PN.getType(), Instruction::PHI,
59 new Use[PN.getNumOperands()], PN.getNumOperands()),
60 ReservedSpace(PN.getNumOperands()) {
61 Use *OL = OperandList;
62 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
63 OL[i].init(PN.getOperand(i), this);
64 OL[i+1].init(PN.getOperand(i+1), this);
69 delete [] OperandList;
72 // removeIncomingValue - Remove an incoming value. This is useful if a
73 // predecessor basic block is deleted.
74 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
75 unsigned NumOps = getNumOperands();
76 Use *OL = OperandList;
77 assert(Idx*2 < NumOps && "BB not in PHI node!");
78 Value *Removed = OL[Idx*2];
80 // Move everything after this operand down.
82 // FIXME: we could just swap with the end of the list, then erase. However,
83 // client might not expect this to happen. The code as it is thrashes the
84 // use/def lists, which is kinda lame.
85 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
90 // Nuke the last value.
92 OL[NumOps-2+1].set(0);
93 NumOperands = NumOps-2;
95 // If the PHI node is dead, because it has zero entries, nuke it now.
96 if (NumOps == 2 && DeletePHIIfEmpty) {
97 // If anyone is using this PHI, make them use a dummy value instead...
98 replaceAllUsesWith(UndefValue::get(getType()));
104 /// resizeOperands - resize operands - This adjusts the length of the operands
105 /// list according to the following behavior:
106 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
107 /// of operation. This grows the number of ops by 1.5 times.
108 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
109 /// 3. If NumOps == NumOperands, trim the reserved space.
111 void PHINode::resizeOperands(unsigned NumOps) {
113 NumOps = (getNumOperands())*3/2;
114 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
115 } else if (NumOps*2 > NumOperands) {
117 if (ReservedSpace >= NumOps) return;
118 } else if (NumOps == NumOperands) {
119 if (ReservedSpace == NumOps) return;
124 ReservedSpace = NumOps;
125 Use *NewOps = new Use[NumOps];
126 Use *OldOps = OperandList;
127 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
128 NewOps[i].init(OldOps[i], this);
132 OperandList = NewOps;
135 /// hasConstantValue - If the specified PHI node always merges together the same
136 /// value, return the value, otherwise return null.
138 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
139 // If the PHI node only has one incoming value, eliminate the PHI node...
140 if (getNumIncomingValues() == 1)
141 return getIncomingValue(0);
143 // Otherwise if all of the incoming values are the same for the PHI, replace
144 // the PHI node with the incoming value.
147 bool HasUndefInput = false;
148 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
149 if (isa<UndefValue>(getIncomingValue(i)))
150 HasUndefInput = true;
151 else if (getIncomingValue(i) != this) // Not the PHI node itself...
152 if (InVal && getIncomingValue(i) != InVal)
153 return 0; // Not the same, bail out.
155 InVal = getIncomingValue(i);
157 // The only case that could cause InVal to be null is if we have a PHI node
158 // that only has entries for itself. In this case, there is no entry into the
159 // loop, so kill the PHI.
161 if (InVal == 0) InVal = UndefValue::get(getType());
163 // If we have a PHI node like phi(X, undef, X), where X is defined by some
164 // instruction, we cannot always return X as the result of the PHI node. Only
165 // do this if X is not an instruction (thus it must dominate the PHI block),
166 // or if the client is prepared to deal with this possibility.
167 if (HasUndefInput && !AllowNonDominatingInstruction)
168 if (Instruction *IV = dyn_cast<Instruction>(InVal))
169 // If it's in the entry block, it dominates everything.
170 if (IV->getParent() != &IV->getParent()->getParent()->front())
171 return 0; // Cannot guarantee that InVal dominates this PHINode.
173 // All of the incoming values are the same, return the value now.
178 //===----------------------------------------------------------------------===//
179 // CallInst Implementation
180 //===----------------------------------------------------------------------===//
182 CallInst::~CallInst() {
183 delete [] OperandList;
186 void CallInst::init(Value *Func, const std::vector<Value*> &Params) {
187 NumOperands = Params.size()+1;
188 Use *OL = OperandList = new Use[Params.size()+1];
189 OL[0].init(Func, this);
191 const FunctionType *FTy =
192 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
194 assert((Params.size() == FTy->getNumParams() ||
195 (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
196 "Calling a function with bad signature");
197 for (unsigned i = 0, e = Params.size(); i != e; ++i)
198 OL[i+1].init(Params[i], this);
201 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
203 Use *OL = OperandList = new Use[3];
204 OL[0].init(Func, this);
205 OL[1].init(Actual1, this);
206 OL[2].init(Actual2, this);
208 const FunctionType *FTy =
209 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
211 assert((FTy->getNumParams() == 2 ||
212 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
213 "Calling a function with bad signature");
216 void CallInst::init(Value *Func, Value *Actual) {
218 Use *OL = OperandList = new Use[2];
219 OL[0].init(Func, this);
220 OL[1].init(Actual, this);
222 const FunctionType *FTy =
223 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
225 assert((FTy->getNumParams() == 1 ||
226 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
227 "Calling a function with bad signature");
230 void CallInst::init(Value *Func) {
232 Use *OL = OperandList = new Use[1];
233 OL[0].init(Func, this);
235 const FunctionType *MTy =
236 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
238 assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
241 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
242 const std::string &Name, Instruction *InsertBefore)
243 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
244 ->getElementType())->getReturnType(),
245 Instruction::Call, 0, 0, Name, InsertBefore) {
249 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
250 const std::string &Name, BasicBlock *InsertAtEnd)
251 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
252 ->getElementType())->getReturnType(),
253 Instruction::Call, 0, 0, Name, InsertAtEnd) {
257 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
258 const std::string &Name, Instruction *InsertBefore)
259 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
260 ->getElementType())->getReturnType(),
261 Instruction::Call, 0, 0, Name, InsertBefore) {
262 init(Func, Actual1, Actual2);
265 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
266 const std::string &Name, BasicBlock *InsertAtEnd)
267 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
268 ->getElementType())->getReturnType(),
269 Instruction::Call, 0, 0, Name, InsertAtEnd) {
270 init(Func, Actual1, Actual2);
273 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
274 Instruction *InsertBefore)
275 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
276 ->getElementType())->getReturnType(),
277 Instruction::Call, 0, 0, Name, InsertBefore) {
281 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
282 BasicBlock *InsertAtEnd)
283 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
284 ->getElementType())->getReturnType(),
285 Instruction::Call, 0, 0, Name, InsertAtEnd) {
289 CallInst::CallInst(Value *Func, const std::string &Name,
290 Instruction *InsertBefore)
291 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
292 ->getElementType())->getReturnType(),
293 Instruction::Call, 0, 0, Name, InsertBefore) {
297 CallInst::CallInst(Value *Func, const std::string &Name,
298 BasicBlock *InsertAtEnd)
299 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
300 ->getElementType())->getReturnType(),
301 Instruction::Call, 0, 0, Name, InsertAtEnd) {
305 CallInst::CallInst(const CallInst &CI)
306 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
307 CI.getNumOperands()) {
308 SubclassData = CI.SubclassData;
309 Use *OL = OperandList;
310 Use *InOL = CI.OperandList;
311 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
312 OL[i].init(InOL[i], this);
316 //===----------------------------------------------------------------------===//
317 // InvokeInst Implementation
318 //===----------------------------------------------------------------------===//
320 InvokeInst::~InvokeInst() {
321 delete [] OperandList;
324 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
325 const std::vector<Value*> &Params) {
326 NumOperands = 3+Params.size();
327 Use *OL = OperandList = new Use[3+Params.size()];
328 OL[0].init(Fn, this);
329 OL[1].init(IfNormal, this);
330 OL[2].init(IfException, this);
331 const FunctionType *FTy =
332 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
334 assert((Params.size() == FTy->getNumParams()) ||
335 (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
336 "Calling a function with bad signature");
338 for (unsigned i = 0, e = Params.size(); i != e; i++)
339 OL[i+3].init(Params[i], this);
342 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
343 BasicBlock *IfException,
344 const std::vector<Value*> &Params,
345 const std::string &Name, Instruction *InsertBefore)
346 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
347 ->getElementType())->getReturnType(),
348 Instruction::Invoke, 0, 0, Name, InsertBefore) {
349 init(Fn, IfNormal, IfException, Params);
352 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
353 BasicBlock *IfException,
354 const std::vector<Value*> &Params,
355 const std::string &Name, BasicBlock *InsertAtEnd)
356 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
357 ->getElementType())->getReturnType(),
358 Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
359 init(Fn, IfNormal, IfException, Params);
362 InvokeInst::InvokeInst(const InvokeInst &II)
363 : TerminatorInst(II.getType(), Instruction::Invoke,
364 new Use[II.getNumOperands()], II.getNumOperands()) {
365 SubclassData = II.SubclassData;
366 Use *OL = OperandList, *InOL = II.OperandList;
367 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
368 OL[i].init(InOL[i], this);
371 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
372 return getSuccessor(idx);
374 unsigned InvokeInst::getNumSuccessorsV() const {
375 return getNumSuccessors();
377 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
378 return setSuccessor(idx, B);
382 //===----------------------------------------------------------------------===//
383 // ReturnInst Implementation
384 //===----------------------------------------------------------------------===//
386 void ReturnInst::init(Value *retVal) {
387 if (retVal && retVal->getType() != Type::VoidTy) {
388 assert(!isa<BasicBlock>(retVal) &&
389 "Cannot return basic block. Probably using the incorrect ctor");
391 RetVal.init(retVal, this);
395 unsigned ReturnInst::getNumSuccessorsV() const {
396 return getNumSuccessors();
399 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
400 // emit the vtable for the class in this translation unit.
401 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
402 assert(0 && "ReturnInst has no successors!");
405 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
406 assert(0 && "ReturnInst has no successors!");
412 //===----------------------------------------------------------------------===//
413 // UnwindInst Implementation
414 //===----------------------------------------------------------------------===//
416 unsigned UnwindInst::getNumSuccessorsV() const {
417 return getNumSuccessors();
420 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
421 assert(0 && "UnwindInst has no successors!");
424 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
425 assert(0 && "UnwindInst has no successors!");
430 //===----------------------------------------------------------------------===//
431 // UnreachableInst Implementation
432 //===----------------------------------------------------------------------===//
434 unsigned UnreachableInst::getNumSuccessorsV() const {
435 return getNumSuccessors();
438 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
439 assert(0 && "UnwindInst has no successors!");
442 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
443 assert(0 && "UnwindInst has no successors!");
448 //===----------------------------------------------------------------------===//
449 // BranchInst Implementation
450 //===----------------------------------------------------------------------===//
452 void BranchInst::AssertOK() {
454 assert(getCondition()->getType() == Type::BoolTy &&
455 "May only branch on boolean predicates!");
458 BranchInst::BranchInst(const BranchInst &BI) :
459 TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
460 OperandList[0].init(BI.getOperand(0), this);
461 if (BI.getNumOperands() != 1) {
462 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
463 OperandList[1].init(BI.getOperand(1), this);
464 OperandList[2].init(BI.getOperand(2), this);
468 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
469 return getSuccessor(idx);
471 unsigned BranchInst::getNumSuccessorsV() const {
472 return getNumSuccessors();
474 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
475 setSuccessor(idx, B);
479 //===----------------------------------------------------------------------===//
480 // AllocationInst Implementation
481 //===----------------------------------------------------------------------===//
483 static Value *getAISize(Value *Amt) {
485 Amt = ConstantUInt::get(Type::UIntTy, 1);
487 assert(Amt->getType() == Type::UIntTy &&
488 "Malloc/Allocation array size != UIntTy!");
492 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
493 const std::string &Name,
494 Instruction *InsertBefore)
495 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
496 Name, InsertBefore) {
497 assert(Ty != Type::VoidTy && "Cannot allocate void!");
500 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
501 const std::string &Name,
502 BasicBlock *InsertAtEnd)
503 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
505 assert(Ty != Type::VoidTy && "Cannot allocate void!");
508 bool AllocationInst::isArrayAllocation() const {
509 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(getOperand(0)))
510 return CUI->getValue() != 1;
514 const Type *AllocationInst::getAllocatedType() const {
515 return getType()->getElementType();
518 AllocaInst::AllocaInst(const AllocaInst &AI)
519 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
520 Instruction::Alloca) {
523 MallocInst::MallocInst(const MallocInst &MI)
524 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
525 Instruction::Malloc) {
528 //===----------------------------------------------------------------------===//
529 // FreeInst Implementation
530 //===----------------------------------------------------------------------===//
532 void FreeInst::AssertOK() {
533 assert(isa<PointerType>(getOperand(0)->getType()) &&
534 "Can not free something of nonpointer type!");
537 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
538 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
542 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
543 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
548 //===----------------------------------------------------------------------===//
549 // LoadInst Implementation
550 //===----------------------------------------------------------------------===//
552 void LoadInst::AssertOK() {
553 assert(isa<PointerType>(getOperand(0)->getType()) &&
554 "Ptr must have pointer type.");
557 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
558 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
559 Load, Ptr, Name, InsertBef) {
564 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
565 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
566 Load, Ptr, Name, InsertAE) {
571 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
572 Instruction *InsertBef)
573 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
574 Load, Ptr, Name, InsertBef) {
575 setVolatile(isVolatile);
579 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
580 BasicBlock *InsertAE)
581 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
582 Load, Ptr, Name, InsertAE) {
583 setVolatile(isVolatile);
588 //===----------------------------------------------------------------------===//
589 // StoreInst Implementation
590 //===----------------------------------------------------------------------===//
592 void StoreInst::AssertOK() {
593 assert(isa<PointerType>(getOperand(1)->getType()) &&
594 "Ptr must have pointer type!");
595 assert(getOperand(0)->getType() ==
596 cast<PointerType>(getOperand(1)->getType())->getElementType()
597 && "Ptr must be a pointer to Val type!");
601 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
602 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
603 Ops[0].init(val, this);
604 Ops[1].init(addr, this);
609 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
610 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
611 Ops[0].init(val, this);
612 Ops[1].init(addr, this);
617 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
618 Instruction *InsertBefore)
619 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
620 Ops[0].init(val, this);
621 Ops[1].init(addr, this);
622 setVolatile(isVolatile);
626 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
627 BasicBlock *InsertAtEnd)
628 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
629 Ops[0].init(val, this);
630 Ops[1].init(addr, this);
631 setVolatile(isVolatile);
635 //===----------------------------------------------------------------------===//
636 // GetElementPtrInst Implementation
637 //===----------------------------------------------------------------------===//
639 // checkType - Simple wrapper function to give a better assertion failure
640 // message on bad indexes for a gep instruction.
642 static inline const Type *checkType(const Type *Ty) {
643 assert(Ty && "Invalid indices for type!");
647 void GetElementPtrInst::init(Value *Ptr, const std::vector<Value*> &Idx) {
648 NumOperands = 1+Idx.size();
649 Use *OL = OperandList = new Use[NumOperands];
650 OL[0].init(Ptr, this);
652 for (unsigned i = 0, e = Idx.size(); i != e; ++i)
653 OL[i+1].init(Idx[i], this);
656 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
658 Use *OL = OperandList = new Use[3];
659 OL[0].init(Ptr, this);
660 OL[1].init(Idx0, this);
661 OL[2].init(Idx1, this);
664 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
666 Use *OL = OperandList = new Use[2];
667 OL[0].init(Ptr, this);
668 OL[1].init(Idx, this);
671 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
672 const std::string &Name, Instruction *InBe)
673 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
675 GetElementPtr, 0, 0, Name, InBe) {
679 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
680 const std::string &Name, BasicBlock *IAE)
681 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
683 GetElementPtr, 0, 0, Name, IAE) {
687 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
688 const std::string &Name, Instruction *InBe)
689 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
690 GetElementPtr, 0, 0, Name, InBe) {
694 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
695 const std::string &Name, BasicBlock *IAE)
696 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
697 GetElementPtr, 0, 0, Name, IAE) {
701 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
702 const std::string &Name, Instruction *InBe)
703 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
705 GetElementPtr, 0, 0, Name, InBe) {
706 init(Ptr, Idx0, Idx1);
709 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
710 const std::string &Name, BasicBlock *IAE)
711 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
713 GetElementPtr, 0, 0, Name, IAE) {
714 init(Ptr, Idx0, Idx1);
717 GetElementPtrInst::~GetElementPtrInst() {
718 delete[] OperandList;
721 // getIndexedType - Returns the type of the element that would be loaded with
722 // a load instruction with the specified parameters.
724 // A null type is returned if the indices are invalid for the specified
727 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
728 const std::vector<Value*> &Idx,
729 bool AllowCompositeLeaf) {
730 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
732 // Handle the special case of the empty set index set...
734 if (AllowCompositeLeaf ||
735 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
736 return cast<PointerType>(Ptr)->getElementType();
741 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
742 if (Idx.size() == CurIdx) {
743 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
744 return 0; // Can't load a whole structure or array!?!?
747 Value *Index = Idx[CurIdx++];
748 if (isa<PointerType>(CT) && CurIdx != 1)
749 return 0; // Can only index into pointer types at the first index!
750 if (!CT->indexValid(Index)) return 0;
751 Ptr = CT->getTypeAtIndex(Index);
753 // If the new type forwards to another type, then it is in the middle
754 // of being refined to another type (and hence, may have dropped all
755 // references to what it was using before). So, use the new forwarded
757 if (const Type * Ty = Ptr->getForwardedType()) {
761 return CurIdx == Idx.size() ? Ptr : 0;
764 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
765 Value *Idx0, Value *Idx1,
766 bool AllowCompositeLeaf) {
767 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
768 if (!PTy) return 0; // Type isn't a pointer type!
770 // Check the pointer index.
771 if (!PTy->indexValid(Idx0)) return 0;
773 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
774 if (!CT || !CT->indexValid(Idx1)) return 0;
776 const Type *ElTy = CT->getTypeAtIndex(Idx1);
777 if (AllowCompositeLeaf || ElTy->isFirstClassType())
782 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
783 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
784 if (!PTy) return 0; // Type isn't a pointer type!
786 // Check the pointer index.
787 if (!PTy->indexValid(Idx)) return 0;
789 return PTy->getElementType();
792 //===----------------------------------------------------------------------===//
793 // BinaryOperator Class
794 //===----------------------------------------------------------------------===//
796 void BinaryOperator::init(BinaryOps iType)
798 Value *LHS = getOperand(0), *RHS = getOperand(1);
799 assert(LHS->getType() == RHS->getType() &&
800 "Binary operator operand types must match!");
806 assert(getType() == LHS->getType() &&
807 "Arithmetic operation should return same type as operands!");
808 assert((getType()->isInteger() ||
809 getType()->isFloatingPoint() ||
810 isa<PackedType>(getType()) ) &&
811 "Tried to create an arithmetic operation on a non-arithmetic type!");
815 assert(getType() == LHS->getType() &&
816 "Logical operation should return same type as operands!");
817 assert(getType()->isIntegral() &&
818 "Tried to create a logical operation on a non-integral type!");
820 case SetLT: case SetGT: case SetLE:
821 case SetGE: case SetEQ: case SetNE:
822 assert(getType() == Type::BoolTy && "Setcc must return bool!");
829 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
830 const std::string &Name,
831 Instruction *InsertBefore) {
832 assert(S1->getType() == S2->getType() &&
833 "Cannot create binary operator with two operands of differing type!");
835 // Binary comparison operators...
836 case SetLT: case SetGT: case SetLE:
837 case SetGE: case SetEQ: case SetNE:
838 return new SetCondInst(Op, S1, S2, Name, InsertBefore);
841 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
845 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
846 const std::string &Name,
847 BasicBlock *InsertAtEnd) {
848 BinaryOperator *Res = create(Op, S1, S2, Name);
849 InsertAtEnd->getInstList().push_back(Res);
853 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
854 Instruction *InsertBefore) {
855 if (!Op->getType()->isFloatingPoint())
856 return new BinaryOperator(Instruction::Sub,
857 Constant::getNullValue(Op->getType()), Op,
858 Op->getType(), Name, InsertBefore);
860 return new BinaryOperator(Instruction::Sub,
861 ConstantFP::get(Op->getType(), -0.0), Op,
862 Op->getType(), Name, InsertBefore);
865 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
866 BasicBlock *InsertAtEnd) {
867 if (!Op->getType()->isFloatingPoint())
868 return new BinaryOperator(Instruction::Sub,
869 Constant::getNullValue(Op->getType()), Op,
870 Op->getType(), Name, InsertAtEnd);
872 return new BinaryOperator(Instruction::Sub,
873 ConstantFP::get(Op->getType(), -0.0), Op,
874 Op->getType(), Name, InsertAtEnd);
877 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
878 Instruction *InsertBefore) {
879 return new BinaryOperator(Instruction::Xor, Op,
880 ConstantIntegral::getAllOnesValue(Op->getType()),
881 Op->getType(), Name, InsertBefore);
884 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
885 BasicBlock *InsertAtEnd) {
886 return new BinaryOperator(Instruction::Xor, Op,
887 ConstantIntegral::getAllOnesValue(Op->getType()),
888 Op->getType(), Name, InsertAtEnd);
892 // isConstantAllOnes - Helper function for several functions below
893 static inline bool isConstantAllOnes(const Value *V) {
894 return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
897 bool BinaryOperator::isNeg(const Value *V) {
898 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
899 if (Bop->getOpcode() == Instruction::Sub)
900 if (!V->getType()->isFloatingPoint())
901 return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
903 return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
907 bool BinaryOperator::isNot(const Value *V) {
908 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
909 return (Bop->getOpcode() == Instruction::Xor &&
910 (isConstantAllOnes(Bop->getOperand(1)) ||
911 isConstantAllOnes(Bop->getOperand(0))));
915 Value *BinaryOperator::getNegArgument(Value *BinOp) {
916 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
917 return cast<BinaryOperator>(BinOp)->getOperand(1);
920 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
921 return getNegArgument(const_cast<Value*>(BinOp));
924 Value *BinaryOperator::getNotArgument(Value *BinOp) {
925 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
926 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
927 Value *Op0 = BO->getOperand(0);
928 Value *Op1 = BO->getOperand(1);
929 if (isConstantAllOnes(Op0)) return Op1;
931 assert(isConstantAllOnes(Op1));
935 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
936 return getNotArgument(const_cast<Value*>(BinOp));
940 // swapOperands - Exchange the two operands to this instruction. This
941 // instruction is safe to use on any binary instruction and does not
942 // modify the semantics of the instruction. If the instruction is
943 // order dependent (SetLT f.e.) the opcode is changed.
945 bool BinaryOperator::swapOperands() {
947 ; // If the instruction is commutative, it is safe to swap the operands
948 else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
949 /// FIXME: SetCC instructions shouldn't all have different opcodes.
950 setOpcode(SCI->getSwappedCondition());
952 return true; // Can't commute operands
954 std::swap(Ops[0], Ops[1]);
959 //===----------------------------------------------------------------------===//
961 //===----------------------------------------------------------------------===//
963 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
964 const std::string &Name, Instruction *InsertBefore)
965 : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
967 // Make sure it's a valid type... getInverseCondition will assert out if not.
968 assert(getInverseCondition(Opcode));
971 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
972 const std::string &Name, BasicBlock *InsertAtEnd)
973 : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertAtEnd) {
975 // Make sure it's a valid type... getInverseCondition will assert out if not.
976 assert(getInverseCondition(Opcode));
979 // getInverseCondition - Return the inverse of the current condition opcode.
980 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
982 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
985 assert(0 && "Unknown setcc opcode!");
986 case SetEQ: return SetNE;
987 case SetNE: return SetEQ;
988 case SetGT: return SetLE;
989 case SetLT: return SetGE;
990 case SetGE: return SetLT;
991 case SetLE: return SetGT;
995 // getSwappedCondition - Return the condition opcode that would be the result
996 // of exchanging the two operands of the setcc instruction without changing
997 // the result produced. Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
999 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
1001 default: assert(0 && "Unknown setcc instruction!");
1002 case SetEQ: case SetNE: return Opcode;
1003 case SetGT: return SetLT;
1004 case SetLT: return SetGT;
1005 case SetGE: return SetLE;
1006 case SetLE: return SetGE;
1010 //===----------------------------------------------------------------------===//
1011 // SwitchInst Implementation
1012 //===----------------------------------------------------------------------===//
1014 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
1015 assert(Value && Default);
1016 ReservedSpace = 2+NumCases*2;
1018 OperandList = new Use[ReservedSpace];
1020 OperandList[0].init(Value, this);
1021 OperandList[1].init(Default, this);
1024 SwitchInst::SwitchInst(const SwitchInst &SI)
1025 : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
1026 SI.getNumOperands()) {
1027 Use *OL = OperandList, *InOL = SI.OperandList;
1028 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
1029 OL[i].init(InOL[i], this);
1030 OL[i+1].init(InOL[i+1], this);
1034 SwitchInst::~SwitchInst() {
1035 delete [] OperandList;
1039 /// addCase - Add an entry to the switch instruction...
1041 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
1042 unsigned OpNo = NumOperands;
1043 if (OpNo+2 > ReservedSpace)
1044 resizeOperands(0); // Get more space!
1045 // Initialize some new operands.
1046 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
1047 NumOperands = OpNo+2;
1048 OperandList[OpNo].init(OnVal, this);
1049 OperandList[OpNo+1].init(Dest, this);
1052 /// removeCase - This method removes the specified successor from the switch
1053 /// instruction. Note that this cannot be used to remove the default
1054 /// destination (successor #0).
1056 void SwitchInst::removeCase(unsigned idx) {
1057 assert(idx != 0 && "Cannot remove the default case!");
1058 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
1060 unsigned NumOps = getNumOperands();
1061 Use *OL = OperandList;
1063 // Move everything after this operand down.
1065 // FIXME: we could just swap with the end of the list, then erase. However,
1066 // client might not expect this to happen. The code as it is thrashes the
1067 // use/def lists, which is kinda lame.
1068 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
1070 OL[i-2+1] = OL[i+1];
1073 // Nuke the last value.
1074 OL[NumOps-2].set(0);
1075 OL[NumOps-2+1].set(0);
1076 NumOperands = NumOps-2;
1079 /// resizeOperands - resize operands - This adjusts the length of the operands
1080 /// list according to the following behavior:
1081 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
1082 /// of operation. This grows the number of ops by 1.5 times.
1083 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
1084 /// 3. If NumOps == NumOperands, trim the reserved space.
1086 void SwitchInst::resizeOperands(unsigned NumOps) {
1088 NumOps = getNumOperands()/2*6;
1089 } else if (NumOps*2 > NumOperands) {
1090 // No resize needed.
1091 if (ReservedSpace >= NumOps) return;
1092 } else if (NumOps == NumOperands) {
1093 if (ReservedSpace == NumOps) return;
1098 ReservedSpace = NumOps;
1099 Use *NewOps = new Use[NumOps];
1100 Use *OldOps = OperandList;
1101 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1102 NewOps[i].init(OldOps[i], this);
1106 OperandList = NewOps;
1110 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
1111 return getSuccessor(idx);
1113 unsigned SwitchInst::getNumSuccessorsV() const {
1114 return getNumSuccessors();
1116 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1117 setSuccessor(idx, B);
1121 // Define these methods here so vtables don't get emitted into every translation
1122 // unit that uses these classes.
1124 GetElementPtrInst *GetElementPtrInst::clone() const {
1125 return new GetElementPtrInst(*this);
1128 BinaryOperator *BinaryOperator::clone() const {
1129 return create(getOpcode(), Ops[0], Ops[1]);
1132 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
1133 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
1134 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
1135 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
1136 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
1137 CastInst *CastInst::clone() const { return new CastInst(*this); }
1138 CallInst *CallInst::clone() const { return new CallInst(*this); }
1139 ShiftInst *ShiftInst::clone() const { return new ShiftInst(*this); }
1140 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
1141 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
1142 PHINode *PHINode::clone() const { return new PHINode(*this); }
1143 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
1144 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
1145 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
1146 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
1147 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
1148 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}