Use the bool argument to hasConstantValue to decide whether the client is
[oota-llvm.git] / lib / VMCore / Instructions.cpp
1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements all of the non-inline methods for the LLVM instruction
11 // classes.
12 //
13 //===----------------------------------------------------------------------===//
14
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 using namespace llvm;
22
23 unsigned CallSite::getCallingConv() const {
24   if (CallInst *CI = dyn_cast<CallInst>(I))
25     return CI->getCallingConv();
26   else
27     return cast<InvokeInst>(I)->getCallingConv();
28 }
29 void CallSite::setCallingConv(unsigned CC) {
30   if (CallInst *CI = dyn_cast<CallInst>(I))
31     CI->setCallingConv(CC);
32   else
33     cast<InvokeInst>(I)->setCallingConv(CC);
34 }
35
36
37 //===----------------------------------------------------------------------===//
38 //                            TerminatorInst Class
39 //===----------------------------------------------------------------------===//
40
41 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
42                                Use *Ops, unsigned NumOps, Instruction *IB)
43   : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IB) {
44 }
45
46 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
47                                Use *Ops, unsigned NumOps, BasicBlock *IAE)
48   : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IAE) {
49 }
50
51
52
53 //===----------------------------------------------------------------------===//
54 //                               PHINode Class
55 //===----------------------------------------------------------------------===//
56
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);
65   }
66 }
67
68 PHINode::~PHINode() {
69   delete [] OperandList;
70 }
71
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];
79
80   // Move everything after this operand down.
81   //
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) {
86     OL[i-2] = OL[i];
87     OL[i-2+1] = OL[i+1];
88   }
89
90   // Nuke the last value.
91   OL[NumOps-2].set(0);
92   OL[NumOps-2+1].set(0);
93   NumOperands = NumOps-2;
94
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()));
99     eraseFromParent();
100   }
101   return Removed;
102 }
103
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.
110 ///
111 void PHINode::resizeOperands(unsigned NumOps) {
112   if (NumOps == 0) {
113     NumOps = (getNumOperands())*3/2;
114     if (NumOps < 4) NumOps = 4;      // 4 op PHI nodes are VERY common.
115   } else if (NumOps*2 > NumOperands) {
116     // No resize needed.
117     if (ReservedSpace >= NumOps) return;
118   } else if (NumOps == NumOperands) {
119     if (ReservedSpace == NumOps) return;
120   } else {
121     return;
122   }
123
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);
129       OldOps[i].set(0);
130   }
131   delete [] OldOps;
132   OperandList = NewOps;
133 }
134
135 /// hasConstantValue - If the specified PHI node always merges together the same
136 /// value, return the value, otherwise return null.
137 ///
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);
142   
143   // Otherwise if all of the incoming values are the same for the PHI, replace
144   // the PHI node with the incoming value.
145   //
146   Value *InVal = 0;
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.
154       else
155         InVal = getIncomingValue(i);
156   
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.
160   //
161   if (InVal == 0) InVal = UndefValue::get(getType());
162   
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.
172
173   // All of the incoming values are the same, return the value now.
174   return InVal;
175 }
176
177
178 //===----------------------------------------------------------------------===//
179 //                        CallInst Implementation
180 //===----------------------------------------------------------------------===//
181
182 CallInst::~CallInst() {
183   delete [] OperandList;
184 }
185
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);
190
191   const FunctionType *FTy =
192     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
193
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);
199 }
200
201 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
202   NumOperands = 3;
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);
207
208   const FunctionType *FTy =
209     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
210
211   assert((FTy->getNumParams() == 2 ||
212           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
213          "Calling a function with bad signature");
214 }
215
216 void CallInst::init(Value *Func, Value *Actual) {
217   NumOperands = 2;
218   Use *OL = OperandList = new Use[2];
219   OL[0].init(Func, this);
220   OL[1].init(Actual, this);
221
222   const FunctionType *FTy =
223     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
224
225   assert((FTy->getNumParams() == 1 ||
226           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
227          "Calling a function with bad signature");
228 }
229
230 void CallInst::init(Value *Func) {
231   NumOperands = 1;
232   Use *OL = OperandList = new Use[1];
233   OL[0].init(Func, this);
234
235   const FunctionType *MTy =
236     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
237
238   assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
239 }
240
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) {
246   init(Func, Params);
247 }
248
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) {
254   init(Func, Params);
255 }
256
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);
263 }
264
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);
271 }
272
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) {
278   init(Func, Actual);
279 }
280
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) {
286   init(Func, Actual);
287 }
288
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) {
294   init(Func);
295 }
296
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) {
302   init(Func);
303 }
304
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);
313 }
314
315
316 //===----------------------------------------------------------------------===//
317 //                        InvokeInst Implementation
318 //===----------------------------------------------------------------------===//
319
320 InvokeInst::~InvokeInst() {
321   delete [] OperandList;
322 }
323
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());
333
334   assert((Params.size() == FTy->getNumParams()) ||
335          (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
336          "Calling a function with bad signature");
337
338   for (unsigned i = 0, e = Params.size(); i != e; i++)
339     OL[i+3].init(Params[i], this);
340 }
341
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);
350 }
351
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);
360 }
361
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);
369 }
370
371 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
372   return getSuccessor(idx);
373 }
374 unsigned InvokeInst::getNumSuccessorsV() const {
375   return getNumSuccessors();
376 }
377 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
378   return setSuccessor(idx, B);
379 }
380
381
382 //===----------------------------------------------------------------------===//
383 //                        ReturnInst Implementation
384 //===----------------------------------------------------------------------===//
385
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");
390     NumOperands = 1;
391     RetVal.init(retVal, this);
392   }
393 }
394
395 unsigned ReturnInst::getNumSuccessorsV() const {
396   return getNumSuccessors();
397 }
398
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!");
403 }
404
405 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
406   assert(0 && "ReturnInst has no successors!");
407   abort();
408   return 0;
409 }
410
411
412 //===----------------------------------------------------------------------===//
413 //                        UnwindInst Implementation
414 //===----------------------------------------------------------------------===//
415
416 unsigned UnwindInst::getNumSuccessorsV() const {
417   return getNumSuccessors();
418 }
419
420 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
421   assert(0 && "UnwindInst has no successors!");
422 }
423
424 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
425   assert(0 && "UnwindInst has no successors!");
426   abort();
427   return 0;
428 }
429
430 //===----------------------------------------------------------------------===//
431 //                      UnreachableInst Implementation
432 //===----------------------------------------------------------------------===//
433
434 unsigned UnreachableInst::getNumSuccessorsV() const {
435   return getNumSuccessors();
436 }
437
438 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
439   assert(0 && "UnwindInst has no successors!");
440 }
441
442 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
443   assert(0 && "UnwindInst has no successors!");
444   abort();
445   return 0;
446 }
447
448 //===----------------------------------------------------------------------===//
449 //                        BranchInst Implementation
450 //===----------------------------------------------------------------------===//
451
452 void BranchInst::AssertOK() {
453   if (isConditional())
454     assert(getCondition()->getType() == Type::BoolTy &&
455            "May only branch on boolean predicates!");
456 }
457
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);
465   }
466 }
467
468 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
469   return getSuccessor(idx);
470 }
471 unsigned BranchInst::getNumSuccessorsV() const {
472   return getNumSuccessors();
473 }
474 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
475   setSuccessor(idx, B);
476 }
477
478
479 //===----------------------------------------------------------------------===//
480 //                        AllocationInst Implementation
481 //===----------------------------------------------------------------------===//
482
483 static Value *getAISize(Value *Amt) {
484   if (!Amt)
485     Amt = ConstantUInt::get(Type::UIntTy, 1);
486   else
487     assert(Amt->getType() == Type::UIntTy &&
488            "Malloc/Allocation array size != UIntTy!");
489   return Amt;
490 }
491
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!");
498 }
499
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),
504                      Name, InsertAtEnd) {
505   assert(Ty != Type::VoidTy && "Cannot allocate void!");
506 }
507
508 bool AllocationInst::isArrayAllocation() const {
509   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(getOperand(0)))
510     return CUI->getValue() != 1;
511   return true;
512 }
513
514 const Type *AllocationInst::getAllocatedType() const {
515   return getType()->getElementType();
516 }
517
518 AllocaInst::AllocaInst(const AllocaInst &AI)
519   : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
520                    Instruction::Alloca) {
521 }
522
523 MallocInst::MallocInst(const MallocInst &MI)
524   : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
525                    Instruction::Malloc) {
526 }
527
528 //===----------------------------------------------------------------------===//
529 //                             FreeInst Implementation
530 //===----------------------------------------------------------------------===//
531
532 void FreeInst::AssertOK() {
533   assert(isa<PointerType>(getOperand(0)->getType()) &&
534          "Can not free something of nonpointer type!");
535 }
536
537 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
538   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
539   AssertOK();
540 }
541
542 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
543   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
544   AssertOK();
545 }
546
547
548 //===----------------------------------------------------------------------===//
549 //                           LoadInst Implementation
550 //===----------------------------------------------------------------------===//
551
552 void LoadInst::AssertOK() {
553   assert(isa<PointerType>(getOperand(0)->getType()) &&
554          "Ptr must have pointer type.");
555 }
556
557 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
558   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
559                      Load, Ptr, Name, InsertBef) {
560   setVolatile(false);
561   AssertOK();
562 }
563
564 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
565   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
566                      Load, Ptr, Name, InsertAE) {
567   setVolatile(false);
568   AssertOK();
569 }
570
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);
576   AssertOK();
577 }
578
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);
584   AssertOK();
585 }
586
587
588 //===----------------------------------------------------------------------===//
589 //                           StoreInst Implementation
590 //===----------------------------------------------------------------------===//
591
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!");
598 }
599
600
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);
605   setVolatile(false);
606   AssertOK();
607 }
608
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);
613   setVolatile(false);
614   AssertOK();
615 }
616
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);
623   AssertOK();
624 }
625
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);
632   AssertOK();
633 }
634
635 //===----------------------------------------------------------------------===//
636 //                       GetElementPtrInst Implementation
637 //===----------------------------------------------------------------------===//
638
639 // checkType - Simple wrapper function to give a better assertion failure
640 // message on bad indexes for a gep instruction.
641 //
642 static inline const Type *checkType(const Type *Ty) {
643   assert(Ty && "Invalid indices for type!");
644   return Ty;
645 }
646
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);
651
652   for (unsigned i = 0, e = Idx.size(); i != e; ++i)
653     OL[i+1].init(Idx[i], this);
654 }
655
656 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
657   NumOperands = 3;
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);
662 }
663
664 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
665   NumOperands = 2;
666   Use *OL = OperandList = new Use[2];
667   OL[0].init(Ptr, this);
668   OL[1].init(Idx, this);
669 }
670
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(),
674                                                           Idx, true))),
675                 GetElementPtr, 0, 0, Name, InBe) {
676   init(Ptr, Idx);
677 }
678
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(),
682                                                           Idx, true))),
683                 GetElementPtr, 0, 0, Name, IAE) {
684   init(Ptr, Idx);
685 }
686
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) {
691   init(Ptr, Idx);
692 }
693
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) {
698   init(Ptr, Idx);
699 }
700
701 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
702                                      const std::string &Name, Instruction *InBe)
703   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
704                                                           Idx0, Idx1, true))),
705                 GetElementPtr, 0, 0, Name, InBe) {
706   init(Ptr, Idx0, Idx1);
707 }
708
709 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
710                                      const std::string &Name, BasicBlock *IAE)
711   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
712                                                           Idx0, Idx1, true))),
713                 GetElementPtr, 0, 0, Name, IAE) {
714   init(Ptr, Idx0, Idx1);
715 }
716
717 GetElementPtrInst::~GetElementPtrInst() {
718   delete[] OperandList;
719 }
720
721 // getIndexedType - Returns the type of the element that would be loaded with
722 // a load instruction with the specified parameters.
723 //
724 // A null type is returned if the indices are invalid for the specified
725 // pointer type.
726 //
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!
731
732   // Handle the special case of the empty set index set...
733   if (Idx.empty())
734     if (AllowCompositeLeaf ||
735         cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
736       return cast<PointerType>(Ptr)->getElementType();
737     else
738       return 0;
739
740   unsigned CurIdx = 0;
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!?!?
745     }
746
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);
752
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
756     // type.
757     if (const Type * Ty = Ptr->getForwardedType()) {
758       Ptr = Ty;
759     }
760   }
761   return CurIdx == Idx.size() ? Ptr : 0;
762 }
763
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!
769
770   // Check the pointer index.
771   if (!PTy->indexValid(Idx0)) return 0;
772
773   const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
774   if (!CT || !CT->indexValid(Idx1)) return 0;
775
776   const Type *ElTy = CT->getTypeAtIndex(Idx1);
777   if (AllowCompositeLeaf || ElTy->isFirstClassType())
778     return ElTy;
779   return 0;
780 }
781
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!
785
786   // Check the pointer index.
787   if (!PTy->indexValid(Idx)) return 0;
788
789   return PTy->getElementType();
790 }
791
792 //===----------------------------------------------------------------------===//
793 //                             BinaryOperator Class
794 //===----------------------------------------------------------------------===//
795
796 void BinaryOperator::init(BinaryOps iType)
797 {
798   Value *LHS = getOperand(0), *RHS = getOperand(1);
799   assert(LHS->getType() == RHS->getType() &&
800          "Binary operator operand types must match!");
801 #ifndef NDEBUG
802   switch (iType) {
803   case Add: case Sub:
804   case Mul: case Div:
805   case Rem:
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!");
812     break;
813   case And: case Or:
814   case Xor:
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!");
819     break;
820   case SetLT: case SetGT: case SetLE:
821   case SetGE: case SetEQ: case SetNE:
822     assert(getType() == Type::BoolTy && "Setcc must return bool!");
823   default:
824     break;
825   }
826 #endif
827 }
828
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!");
834   switch (Op) {
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);
839
840   default:
841     return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
842   }
843 }
844
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);
850   return Res;
851 }
852
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);
859   else
860     return new BinaryOperator(Instruction::Sub,
861                               ConstantFP::get(Op->getType(), -0.0), Op,
862                               Op->getType(), Name, InsertBefore);
863 }
864
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);
871   else
872     return new BinaryOperator(Instruction::Sub,
873                               ConstantFP::get(Op->getType(), -0.0), Op,
874                               Op->getType(), Name, InsertAtEnd);
875 }
876
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);
882 }
883
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);
889 }
890
891
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();
895 }
896
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());
902       else
903         return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
904   return false;
905 }
906
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))));
912   return false;
913 }
914
915 Value *BinaryOperator::getNegArgument(Value *BinOp) {
916   assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
917   return cast<BinaryOperator>(BinOp)->getOperand(1);
918 }
919
920 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
921   return getNegArgument(const_cast<Value*>(BinOp));
922 }
923
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;
930
931   assert(isConstantAllOnes(Op1));
932   return Op0;
933 }
934
935 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
936   return getNotArgument(const_cast<Value*>(BinOp));
937 }
938
939
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.
944 //
945 bool BinaryOperator::swapOperands() {
946   if (isCommutative())
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());
951   else
952     return true;   // Can't commute operands
953
954   std::swap(Ops[0], Ops[1]);
955   return false;
956 }
957
958
959 //===----------------------------------------------------------------------===//
960 //                             SetCondInst Class
961 //===----------------------------------------------------------------------===//
962
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) {
966
967   // Make sure it's a valid type... getInverseCondition will assert out if not.
968   assert(getInverseCondition(Opcode));
969 }
970
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) {
974
975   // Make sure it's a valid type... getInverseCondition will assert out if not.
976   assert(getInverseCondition(Opcode));
977 }
978
979 // getInverseCondition - Return the inverse of the current condition opcode.
980 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
981 //
982 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
983   switch (Opcode) {
984   default:
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;
992   }
993 }
994
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.
998 //
999 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
1000   switch (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;
1007   }
1008 }
1009
1010 //===----------------------------------------------------------------------===//
1011 //                        SwitchInst Implementation
1012 //===----------------------------------------------------------------------===//
1013
1014 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
1015   assert(Value && Default);
1016   ReservedSpace = 2+NumCases*2;
1017   NumOperands = 2;
1018   OperandList = new Use[ReservedSpace];
1019
1020   OperandList[0].init(Value, this);
1021   OperandList[1].init(Default, this);
1022 }
1023
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);
1031   }
1032 }
1033
1034 SwitchInst::~SwitchInst() {
1035   delete [] OperandList;
1036 }
1037
1038
1039 /// addCase - Add an entry to the switch instruction...
1040 ///
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);
1050 }
1051
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).
1055 ///
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!!!");
1059
1060   unsigned NumOps = getNumOperands();
1061   Use *OL = OperandList;
1062
1063   // Move everything after this operand down.
1064   //
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) {
1069     OL[i-2] = OL[i];
1070     OL[i-2+1] = OL[i+1];
1071   }
1072
1073   // Nuke the last value.
1074   OL[NumOps-2].set(0);
1075   OL[NumOps-2+1].set(0);
1076   NumOperands = NumOps-2;
1077 }
1078
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.
1085 ///
1086 void SwitchInst::resizeOperands(unsigned NumOps) {
1087   if (NumOps == 0) {
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;
1094   } else {
1095     return;
1096   }
1097
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);
1103       OldOps[i].set(0);
1104   }
1105   delete [] OldOps;
1106   OperandList = NewOps;
1107 }
1108
1109
1110 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
1111   return getSuccessor(idx);
1112 }
1113 unsigned SwitchInst::getNumSuccessorsV() const {
1114   return getNumSuccessors();
1115 }
1116 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1117   setSuccessor(idx, B);
1118 }
1119
1120
1121 // Define these methods here so vtables don't get emitted into every translation
1122 // unit that uses these classes.
1123
1124 GetElementPtrInst *GetElementPtrInst::clone() const {
1125   return new GetElementPtrInst(*this);
1126 }
1127
1128 BinaryOperator *BinaryOperator::clone() const {
1129   return create(getOpcode(), Ops[0], Ops[1]);
1130 }
1131
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();}