Add assertions that verify that the actual arguments to a call or invoke match
[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     if (getIncomingValue(0) != this)   // not  X = phi X
142       return getIncomingValue(0);
143     else
144       return UndefValue::get(getType());  // Self cycle is dead.
145       
146   // Otherwise if all of the incoming values are the same for the PHI, replace
147   // the PHI node with the incoming value.
148   //
149   Value *InVal = 0;
150   bool HasUndefInput = false;
151   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
152     if (isa<UndefValue>(getIncomingValue(i)))
153       HasUndefInput = true;
154     else if (getIncomingValue(i) != this)  // Not the PHI node itself...
155       if (InVal && getIncomingValue(i) != InVal)
156         return 0;  // Not the same, bail out.
157       else
158         InVal = getIncomingValue(i);
159   
160   // The only case that could cause InVal to be null is if we have a PHI node
161   // that only has entries for itself.  In this case, there is no entry into the
162   // loop, so kill the PHI.
163   //
164   if (InVal == 0) InVal = UndefValue::get(getType());
165   
166   // If we have a PHI node like phi(X, undef, X), where X is defined by some
167   // instruction, we cannot always return X as the result of the PHI node.  Only
168   // do this if X is not an instruction (thus it must dominate the PHI block),
169   // or if the client is prepared to deal with this possibility.
170   if (HasUndefInput && !AllowNonDominatingInstruction)
171     if (Instruction *IV = dyn_cast<Instruction>(InVal))
172       // If it's in the entry block, it dominates everything.
173       if (IV->getParent() != &IV->getParent()->getParent()->front() ||
174           isa<InvokeInst>(IV))
175         return 0;   // Cannot guarantee that InVal dominates this PHINode.
176
177   // All of the incoming values are the same, return the value now.
178   return InVal;
179 }
180
181
182 //===----------------------------------------------------------------------===//
183 //                        CallInst Implementation
184 //===----------------------------------------------------------------------===//
185
186 CallInst::~CallInst() {
187   delete [] OperandList;
188 }
189
190 void CallInst::init(Value *Func, const std::vector<Value*> &Params) {
191   NumOperands = Params.size()+1;
192   Use *OL = OperandList = new Use[Params.size()+1];
193   OL[0].init(Func, this);
194
195   const FunctionType *FTy =
196     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
197
198   assert((Params.size() == FTy->getNumParams() ||
199           (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
200          "Calling a function with bad signature!");
201   for (unsigned i = 0, e = Params.size(); i != e; ++i) {
202     assert((i >= FTy->getNumParams() || 
203             FTy->getParamType(i) == Params[i]->getType()) &&
204            "Calling a function with a bad signature!");
205     OL[i+1].init(Params[i], this);
206   }
207 }
208
209 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
210   NumOperands = 3;
211   Use *OL = OperandList = new Use[3];
212   OL[0].init(Func, this);
213   OL[1].init(Actual1, this);
214   OL[2].init(Actual2, this);
215
216   const FunctionType *FTy =
217     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
218
219   assert((FTy->getNumParams() == 2 ||
220           (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
221          "Calling a function with bad signature");
222   assert((0 >= FTy->getNumParams() || 
223           FTy->getParamType(0) == Actual1->getType()) &&
224          "Calling a function with a bad signature!");
225   assert((1 >= FTy->getNumParams() || 
226           FTy->getParamType(1) == Actual2->getType()) &&
227          "Calling a function with a bad signature!");
228 }
229
230 void CallInst::init(Value *Func, Value *Actual) {
231   NumOperands = 2;
232   Use *OL = OperandList = new Use[2];
233   OL[0].init(Func, this);
234   OL[1].init(Actual, this);
235
236   const FunctionType *FTy =
237     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
238
239   assert((FTy->getNumParams() == 1 ||
240           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
241          "Calling a function with bad signature");
242   assert((0 == FTy->getNumParams() || 
243           FTy->getParamType(0) == Actual->getType()) &&
244          "Calling a function with a bad signature!");
245 }
246
247 void CallInst::init(Value *Func) {
248   NumOperands = 1;
249   Use *OL = OperandList = new Use[1];
250   OL[0].init(Func, this);
251
252   const FunctionType *MTy =
253     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
254
255   assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
256 }
257
258 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
259                    const std::string &Name, Instruction *InsertBefore)
260   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
261                                  ->getElementType())->getReturnType(),
262                 Instruction::Call, 0, 0, Name, InsertBefore) {
263   init(Func, Params);
264 }
265
266 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
267                    const std::string &Name, BasicBlock *InsertAtEnd)
268   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
269                                  ->getElementType())->getReturnType(),
270                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
271   init(Func, Params);
272 }
273
274 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
275                    const std::string &Name, Instruction  *InsertBefore)
276   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
277                                    ->getElementType())->getReturnType(),
278                 Instruction::Call, 0, 0, Name, InsertBefore) {
279   init(Func, Actual1, Actual2);
280 }
281
282 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
283                    const std::string &Name, BasicBlock  *InsertAtEnd)
284   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
285                                    ->getElementType())->getReturnType(),
286                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
287   init(Func, Actual1, Actual2);
288 }
289
290 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
291                    Instruction  *InsertBefore)
292   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
293                                    ->getElementType())->getReturnType(),
294                 Instruction::Call, 0, 0, Name, InsertBefore) {
295   init(Func, Actual);
296 }
297
298 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
299                    BasicBlock  *InsertAtEnd)
300   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
301                                    ->getElementType())->getReturnType(),
302                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
303   init(Func, Actual);
304 }
305
306 CallInst::CallInst(Value *Func, const std::string &Name,
307                    Instruction *InsertBefore)
308   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
309                                    ->getElementType())->getReturnType(),
310                 Instruction::Call, 0, 0, Name, InsertBefore) {
311   init(Func);
312 }
313
314 CallInst::CallInst(Value *Func, const std::string &Name,
315                    BasicBlock *InsertAtEnd)
316   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
317                                    ->getElementType())->getReturnType(),
318                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
319   init(Func);
320 }
321
322 CallInst::CallInst(const CallInst &CI)
323   : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
324                 CI.getNumOperands()) {
325   SubclassData = CI.SubclassData;
326   Use *OL = OperandList;
327   Use *InOL = CI.OperandList;
328   for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
329     OL[i].init(InOL[i], this);
330 }
331
332
333 //===----------------------------------------------------------------------===//
334 //                        InvokeInst Implementation
335 //===----------------------------------------------------------------------===//
336
337 InvokeInst::~InvokeInst() {
338   delete [] OperandList;
339 }
340
341 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
342                       const std::vector<Value*> &Params) {
343   NumOperands = 3+Params.size();
344   Use *OL = OperandList = new Use[3+Params.size()];
345   OL[0].init(Fn, this);
346   OL[1].init(IfNormal, this);
347   OL[2].init(IfException, this);
348   const FunctionType *FTy =
349     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
350
351   assert((Params.size() == FTy->getNumParams()) ||
352          (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
353          "Calling a function with bad signature");
354
355   for (unsigned i = 0, e = Params.size(); i != e; i++) {
356     assert((i >= FTy->getNumParams() || 
357             FTy->getParamType(i) == Params[i]->getType()) &&
358            "Invoking a function with a bad signature!");
359     
360     OL[i+3].init(Params[i], this);
361   }
362 }
363
364 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
365                        BasicBlock *IfException,
366                        const std::vector<Value*> &Params,
367                        const std::string &Name, Instruction *InsertBefore)
368   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
369                                     ->getElementType())->getReturnType(),
370                    Instruction::Invoke, 0, 0, Name, InsertBefore) {
371   init(Fn, IfNormal, IfException, Params);
372 }
373
374 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
375                        BasicBlock *IfException,
376                        const std::vector<Value*> &Params,
377                        const std::string &Name, BasicBlock *InsertAtEnd)
378   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
379                                     ->getElementType())->getReturnType(),
380                    Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
381   init(Fn, IfNormal, IfException, Params);
382 }
383
384 InvokeInst::InvokeInst(const InvokeInst &II)
385   : TerminatorInst(II.getType(), Instruction::Invoke,
386                    new Use[II.getNumOperands()], II.getNumOperands()) {
387   SubclassData = II.SubclassData;
388   Use *OL = OperandList, *InOL = II.OperandList;
389   for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
390     OL[i].init(InOL[i], this);
391 }
392
393 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
394   return getSuccessor(idx);
395 }
396 unsigned InvokeInst::getNumSuccessorsV() const {
397   return getNumSuccessors();
398 }
399 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
400   return setSuccessor(idx, B);
401 }
402
403
404 //===----------------------------------------------------------------------===//
405 //                        ReturnInst Implementation
406 //===----------------------------------------------------------------------===//
407
408 void ReturnInst::init(Value *retVal) {
409   if (retVal && retVal->getType() != Type::VoidTy) {
410     assert(!isa<BasicBlock>(retVal) &&
411            "Cannot return basic block.  Probably using the incorrect ctor");
412     NumOperands = 1;
413     RetVal.init(retVal, this);
414   }
415 }
416
417 unsigned ReturnInst::getNumSuccessorsV() const {
418   return getNumSuccessors();
419 }
420
421 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
422 // emit the vtable for the class in this translation unit.
423 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
424   assert(0 && "ReturnInst has no successors!");
425 }
426
427 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
428   assert(0 && "ReturnInst has no successors!");
429   abort();
430   return 0;
431 }
432
433
434 //===----------------------------------------------------------------------===//
435 //                        UnwindInst Implementation
436 //===----------------------------------------------------------------------===//
437
438 unsigned UnwindInst::getNumSuccessorsV() const {
439   return getNumSuccessors();
440 }
441
442 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
443   assert(0 && "UnwindInst has no successors!");
444 }
445
446 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
447   assert(0 && "UnwindInst has no successors!");
448   abort();
449   return 0;
450 }
451
452 //===----------------------------------------------------------------------===//
453 //                      UnreachableInst Implementation
454 //===----------------------------------------------------------------------===//
455
456 unsigned UnreachableInst::getNumSuccessorsV() const {
457   return getNumSuccessors();
458 }
459
460 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
461   assert(0 && "UnwindInst has no successors!");
462 }
463
464 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
465   assert(0 && "UnwindInst has no successors!");
466   abort();
467   return 0;
468 }
469
470 //===----------------------------------------------------------------------===//
471 //                        BranchInst Implementation
472 //===----------------------------------------------------------------------===//
473
474 void BranchInst::AssertOK() {
475   if (isConditional())
476     assert(getCondition()->getType() == Type::BoolTy &&
477            "May only branch on boolean predicates!");
478 }
479
480 BranchInst::BranchInst(const BranchInst &BI) :
481   TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
482   OperandList[0].init(BI.getOperand(0), this);
483   if (BI.getNumOperands() != 1) {
484     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
485     OperandList[1].init(BI.getOperand(1), this);
486     OperandList[2].init(BI.getOperand(2), this);
487   }
488 }
489
490 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
491   return getSuccessor(idx);
492 }
493 unsigned BranchInst::getNumSuccessorsV() const {
494   return getNumSuccessors();
495 }
496 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
497   setSuccessor(idx, B);
498 }
499
500
501 //===----------------------------------------------------------------------===//
502 //                        AllocationInst Implementation
503 //===----------------------------------------------------------------------===//
504
505 static Value *getAISize(Value *Amt) {
506   if (!Amt)
507     Amt = ConstantUInt::get(Type::UIntTy, 1);
508   else
509     assert(Amt->getType() == Type::UIntTy &&
510            "Malloc/Allocation array size != UIntTy!");
511   return Amt;
512 }
513
514 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
515                                unsigned Align, const std::string &Name,
516                                Instruction *InsertBefore)
517   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
518                      Name, InsertBefore), Alignment(Align) {
519   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
520   assert(Ty != Type::VoidTy && "Cannot allocate void!");
521 }
522
523 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
524                                unsigned Align, const std::string &Name,
525                                BasicBlock *InsertAtEnd)
526   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
527                      Name, InsertAtEnd), Alignment(Align) {
528   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
529   assert(Ty != Type::VoidTy && "Cannot allocate void!");
530 }
531
532 bool AllocationInst::isArrayAllocation() const {
533   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(getOperand(0)))
534     return CUI->getValue() != 1;
535   return true;
536 }
537
538 const Type *AllocationInst::getAllocatedType() const {
539   return getType()->getElementType();
540 }
541
542 AllocaInst::AllocaInst(const AllocaInst &AI)
543   : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
544                    Instruction::Alloca, AI.getAlignment()) {
545 }
546
547 MallocInst::MallocInst(const MallocInst &MI)
548   : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
549                    Instruction::Malloc, MI.getAlignment()) {
550 }
551
552 //===----------------------------------------------------------------------===//
553 //                             FreeInst Implementation
554 //===----------------------------------------------------------------------===//
555
556 void FreeInst::AssertOK() {
557   assert(isa<PointerType>(getOperand(0)->getType()) &&
558          "Can not free something of nonpointer type!");
559 }
560
561 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
562   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
563   AssertOK();
564 }
565
566 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
567   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
568   AssertOK();
569 }
570
571
572 //===----------------------------------------------------------------------===//
573 //                           LoadInst Implementation
574 //===----------------------------------------------------------------------===//
575
576 void LoadInst::AssertOK() {
577   assert(isa<PointerType>(getOperand(0)->getType()) &&
578          "Ptr must have pointer type.");
579 }
580
581 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
582   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
583                      Load, Ptr, Name, InsertBef) {
584   setVolatile(false);
585   AssertOK();
586 }
587
588 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
589   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
590                      Load, Ptr, Name, InsertAE) {
591   setVolatile(false);
592   AssertOK();
593 }
594
595 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
596                    Instruction *InsertBef)
597   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
598                      Load, Ptr, Name, InsertBef) {
599   setVolatile(isVolatile);
600   AssertOK();
601 }
602
603 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
604                    BasicBlock *InsertAE)
605   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
606                      Load, Ptr, Name, InsertAE) {
607   setVolatile(isVolatile);
608   AssertOK();
609 }
610
611
612 //===----------------------------------------------------------------------===//
613 //                           StoreInst Implementation
614 //===----------------------------------------------------------------------===//
615
616 void StoreInst::AssertOK() {
617   assert(isa<PointerType>(getOperand(1)->getType()) &&
618          "Ptr must have pointer type!");
619   assert(getOperand(0)->getType() ==
620                  cast<PointerType>(getOperand(1)->getType())->getElementType()
621          && "Ptr must be a pointer to Val type!");
622 }
623
624
625 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
626   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
627   Ops[0].init(val, this);
628   Ops[1].init(addr, this);
629   setVolatile(false);
630   AssertOK();
631 }
632
633 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
634   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
635   Ops[0].init(val, this);
636   Ops[1].init(addr, this);
637   setVolatile(false);
638   AssertOK();
639 }
640
641 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
642                      Instruction *InsertBefore)
643   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
644   Ops[0].init(val, this);
645   Ops[1].init(addr, this);
646   setVolatile(isVolatile);
647   AssertOK();
648 }
649
650 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
651                      BasicBlock *InsertAtEnd)
652   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
653   Ops[0].init(val, this);
654   Ops[1].init(addr, this);
655   setVolatile(isVolatile);
656   AssertOK();
657 }
658
659 //===----------------------------------------------------------------------===//
660 //                       GetElementPtrInst Implementation
661 //===----------------------------------------------------------------------===//
662
663 // checkType - Simple wrapper function to give a better assertion failure
664 // message on bad indexes for a gep instruction.
665 //
666 static inline const Type *checkType(const Type *Ty) {
667   assert(Ty && "Invalid indices for type!");
668   return Ty;
669 }
670
671 void GetElementPtrInst::init(Value *Ptr, const std::vector<Value*> &Idx) {
672   NumOperands = 1+Idx.size();
673   Use *OL = OperandList = new Use[NumOperands];
674   OL[0].init(Ptr, this);
675
676   for (unsigned i = 0, e = Idx.size(); i != e; ++i)
677     OL[i+1].init(Idx[i], this);
678 }
679
680 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
681   NumOperands = 3;
682   Use *OL = OperandList = new Use[3];
683   OL[0].init(Ptr, this);
684   OL[1].init(Idx0, this);
685   OL[2].init(Idx1, this);
686 }
687
688 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
689   NumOperands = 2;
690   Use *OL = OperandList = new Use[2];
691   OL[0].init(Ptr, this);
692   OL[1].init(Idx, this);
693 }
694
695 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
696                                      const std::string &Name, Instruction *InBe)
697   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
698                                                           Idx, true))),
699                 GetElementPtr, 0, 0, Name, InBe) {
700   init(Ptr, Idx);
701 }
702
703 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
704                                      const std::string &Name, BasicBlock *IAE)
705   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
706                                                           Idx, true))),
707                 GetElementPtr, 0, 0, Name, IAE) {
708   init(Ptr, Idx);
709 }
710
711 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
712                                      const std::string &Name, Instruction *InBe)
713   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
714                 GetElementPtr, 0, 0, Name, InBe) {
715   init(Ptr, Idx);
716 }
717
718 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
719                                      const std::string &Name, BasicBlock *IAE)
720   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
721                 GetElementPtr, 0, 0, Name, IAE) {
722   init(Ptr, Idx);
723 }
724
725 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
726                                      const std::string &Name, Instruction *InBe)
727   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
728                                                           Idx0, Idx1, true))),
729                 GetElementPtr, 0, 0, Name, InBe) {
730   init(Ptr, Idx0, Idx1);
731 }
732
733 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
734                                      const std::string &Name, BasicBlock *IAE)
735   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
736                                                           Idx0, Idx1, true))),
737                 GetElementPtr, 0, 0, Name, IAE) {
738   init(Ptr, Idx0, Idx1);
739 }
740
741 GetElementPtrInst::~GetElementPtrInst() {
742   delete[] OperandList;
743 }
744
745 // getIndexedType - Returns the type of the element that would be loaded with
746 // a load instruction with the specified parameters.
747 //
748 // A null type is returned if the indices are invalid for the specified
749 // pointer type.
750 //
751 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
752                                               const std::vector<Value*> &Idx,
753                                               bool AllowCompositeLeaf) {
754   if (!isa<PointerType>(Ptr)) return 0;   // Type isn't a pointer type!
755
756   // Handle the special case of the empty set index set...
757   if (Idx.empty())
758     if (AllowCompositeLeaf ||
759         cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
760       return cast<PointerType>(Ptr)->getElementType();
761     else
762       return 0;
763
764   unsigned CurIdx = 0;
765   while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
766     if (Idx.size() == CurIdx) {
767       if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
768       return 0;   // Can't load a whole structure or array!?!?
769     }
770
771     Value *Index = Idx[CurIdx++];
772     if (isa<PointerType>(CT) && CurIdx != 1)
773       return 0;  // Can only index into pointer types at the first index!
774     if (!CT->indexValid(Index)) return 0;
775     Ptr = CT->getTypeAtIndex(Index);
776
777     // If the new type forwards to another type, then it is in the middle
778     // of being refined to another type (and hence, may have dropped all
779     // references to what it was using before).  So, use the new forwarded
780     // type.
781     if (const Type * Ty = Ptr->getForwardedType()) {
782       Ptr = Ty;
783     }
784   }
785   return CurIdx == Idx.size() ? Ptr : 0;
786 }
787
788 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
789                                               Value *Idx0, Value *Idx1,
790                                               bool AllowCompositeLeaf) {
791   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
792   if (!PTy) return 0;   // Type isn't a pointer type!
793
794   // Check the pointer index.
795   if (!PTy->indexValid(Idx0)) return 0;
796
797   const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
798   if (!CT || !CT->indexValid(Idx1)) return 0;
799
800   const Type *ElTy = CT->getTypeAtIndex(Idx1);
801   if (AllowCompositeLeaf || ElTy->isFirstClassType())
802     return ElTy;
803   return 0;
804 }
805
806 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
807   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
808   if (!PTy) return 0;   // Type isn't a pointer type!
809
810   // Check the pointer index.
811   if (!PTy->indexValid(Idx)) return 0;
812
813   return PTy->getElementType();
814 }
815
816 //===----------------------------------------------------------------------===//
817 //                           ExtractElementInst Implementation
818 //===----------------------------------------------------------------------===//
819
820 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
821                                        const std::string &Name,
822                                        Instruction *InsertBef)
823   : Instruction(cast<PackedType>(Val->getType())->getElementType(),
824                 ExtractElement, Ops, 2, Name, InsertBef) {
825   assert(isValidOperands(Val, Index) &&
826          "Invalid extractelement instruction operands!");
827   Ops[0].init(Val, this);
828   Ops[1].init(Index, this);
829 }
830
831 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
832                                        const std::string &Name,
833                                        BasicBlock *InsertAE)
834   : Instruction(cast<PackedType>(Val->getType())->getElementType(),
835                 ExtractElement, Ops, 2, Name, InsertAE) {
836   assert(isValidOperands(Val, Index) &&
837          "Invalid extractelement instruction operands!");
838
839   Ops[0].init(Val, this);
840   Ops[1].init(Index, this);
841 }
842
843 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
844   if (!isa<PackedType>(Val->getType()) || Index->getType() != Type::UIntTy)
845     return false;
846   return true;
847 }
848
849
850 //===----------------------------------------------------------------------===//
851 //                           InsertElementInst Implementation
852 //===----------------------------------------------------------------------===//
853
854 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
855     : Instruction(IE.getType(), InsertElement, Ops, 3) {
856   Ops[0].init(IE.Ops[0], this);
857   Ops[1].init(IE.Ops[1], this);
858   Ops[2].init(IE.Ops[2], this);
859 }
860 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
861                                      const std::string &Name,
862                                      Instruction *InsertBef)
863   : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
864   assert(isValidOperands(Vec, Elt, Index) &&
865          "Invalid insertelement instruction operands!");
866   Ops[0].init(Vec, this);
867   Ops[1].init(Elt, this);
868   Ops[2].init(Index, this);
869 }
870
871 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
872                                      const std::string &Name,
873                                      BasicBlock *InsertAE)
874   : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
875   assert(isValidOperands(Vec, Elt, Index) &&
876          "Invalid insertelement instruction operands!");
877
878   Ops[0].init(Vec, this);
879   Ops[1].init(Elt, this);
880   Ops[2].init(Index, this);
881 }
882
883 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
884                                         const Value *Index) {
885   if (!isa<PackedType>(Vec->getType()))
886     return false;   // First operand of insertelement must be packed type.
887   
888   if (Elt->getType() != cast<PackedType>(Vec->getType())->getElementType())
889     return false;// Second operand of insertelement must be packed element type.
890     
891   if (Index->getType() != Type::UIntTy)
892     return false;  // Third operand of insertelement must be uint.
893   return true;
894 }
895
896
897 //===----------------------------------------------------------------------===//
898 //                      ShuffleVectorInst Implementation
899 //===----------------------------------------------------------------------===//
900
901 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV) 
902     : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
903   Ops[0].init(SV.Ops[0], this);
904   Ops[1].init(SV.Ops[1], this);
905   Ops[2].init(SV.Ops[2], this);
906 }
907
908 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
909                                      const std::string &Name,
910                                      Instruction *InsertBefore)
911   : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertBefore) {
912   assert(isValidOperands(V1, V2, Mask) &&
913          "Invalid shuffle vector instruction operands!");
914   Ops[0].init(V1, this);
915   Ops[1].init(V2, this);
916   Ops[2].init(Mask, this);
917 }
918
919 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
920                                      const std::string &Name, 
921                                      BasicBlock *InsertAtEnd)
922   : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertAtEnd) {
923   assert(isValidOperands(V1, V2, Mask) &&
924          "Invalid shuffle vector instruction operands!");
925
926   Ops[0].init(V1, this);
927   Ops[1].init(V2, this);
928   Ops[2].init(Mask, this);
929 }
930
931 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 
932                                         const Value *Mask) {
933   if (!isa<PackedType>(V1->getType())) return false;
934   if (V1->getType() != V2->getType()) return false;
935   if (!isa<PackedType>(Mask->getType()) ||
936          cast<PackedType>(Mask->getType())->getElementType() != Type::UIntTy ||
937          cast<PackedType>(Mask->getType())->getNumElements() !=
938          cast<PackedType>(V1->getType())->getNumElements())
939     return false;
940   return true;
941 }
942
943
944 //===----------------------------------------------------------------------===//
945 //                             BinaryOperator Class
946 //===----------------------------------------------------------------------===//
947
948 void BinaryOperator::init(BinaryOps iType)
949 {
950   Value *LHS = getOperand(0), *RHS = getOperand(1);
951   assert(LHS->getType() == RHS->getType() &&
952          "Binary operator operand types must match!");
953 #ifndef NDEBUG
954   switch (iType) {
955   case Add: case Sub:
956   case Mul: case Div:
957   case Rem:
958     assert(getType() == LHS->getType() &&
959            "Arithmetic operation should return same type as operands!");
960     assert((getType()->isInteger() || getType()->isFloatingPoint() ||
961             isa<PackedType>(getType())) &&
962           "Tried to create an arithmetic operation on a non-arithmetic type!");
963     break;
964   case And: case Or:
965   case Xor:
966     assert(getType() == LHS->getType() &&
967            "Logical operation should return same type as operands!");
968     assert((getType()->isIntegral() ||
969             (isa<PackedType>(getType()) && 
970              cast<PackedType>(getType())->getElementType()->isIntegral())) &&
971            "Tried to create a logical operation on a non-integral type!");
972     break;
973   case SetLT: case SetGT: case SetLE:
974   case SetGE: case SetEQ: case SetNE:
975     assert(getType() == Type::BoolTy && "Setcc must return bool!");
976   default:
977     break;
978   }
979 #endif
980 }
981
982 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
983                                        const std::string &Name,
984                                        Instruction *InsertBefore) {
985   assert(S1->getType() == S2->getType() &&
986          "Cannot create binary operator with two operands of differing type!");
987   switch (Op) {
988   // Binary comparison operators...
989   case SetLT: case SetGT: case SetLE:
990   case SetGE: case SetEQ: case SetNE:
991     return new SetCondInst(Op, S1, S2, Name, InsertBefore);
992
993   default:
994     return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
995   }
996 }
997
998 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
999                                        const std::string &Name,
1000                                        BasicBlock *InsertAtEnd) {
1001   BinaryOperator *Res = create(Op, S1, S2, Name);
1002   InsertAtEnd->getInstList().push_back(Res);
1003   return Res;
1004 }
1005
1006 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1007                                           Instruction *InsertBefore) {
1008   if (!Op->getType()->isFloatingPoint())
1009     return new BinaryOperator(Instruction::Sub,
1010                               Constant::getNullValue(Op->getType()), Op,
1011                               Op->getType(), Name, InsertBefore);
1012   else
1013     return new BinaryOperator(Instruction::Sub,
1014                               ConstantFP::get(Op->getType(), -0.0), Op,
1015                               Op->getType(), Name, InsertBefore);
1016 }
1017
1018 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1019                                           BasicBlock *InsertAtEnd) {
1020   if (!Op->getType()->isFloatingPoint())
1021     return new BinaryOperator(Instruction::Sub,
1022                               Constant::getNullValue(Op->getType()), Op,
1023                               Op->getType(), Name, InsertAtEnd);
1024   else
1025     return new BinaryOperator(Instruction::Sub,
1026                               ConstantFP::get(Op->getType(), -0.0), Op,
1027                               Op->getType(), Name, InsertAtEnd);
1028 }
1029
1030 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1031                                           Instruction *InsertBefore) {
1032   Constant *C;
1033   if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
1034     C = ConstantIntegral::getAllOnesValue(PTy->getElementType());
1035     C = ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), C));
1036   } else {
1037     C = ConstantIntegral::getAllOnesValue(Op->getType());
1038   }
1039   
1040   return new BinaryOperator(Instruction::Xor, Op, C,
1041                             Op->getType(), Name, InsertBefore);
1042 }
1043
1044 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1045                                           BasicBlock *InsertAtEnd) {
1046   Constant *AllOnes;
1047   if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
1048     // Create a vector of all ones values.
1049     Constant *Elt = ConstantIntegral::getAllOnesValue(PTy->getElementType());
1050     AllOnes = 
1051       ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1052   } else {
1053     AllOnes = ConstantIntegral::getAllOnesValue(Op->getType());
1054   }
1055   
1056   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1057                             Op->getType(), Name, InsertAtEnd);
1058 }
1059
1060
1061 // isConstantAllOnes - Helper function for several functions below
1062 static inline bool isConstantAllOnes(const Value *V) {
1063   return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
1064 }
1065
1066 bool BinaryOperator::isNeg(const Value *V) {
1067   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1068     if (Bop->getOpcode() == Instruction::Sub)
1069       if (!V->getType()->isFloatingPoint())
1070         return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
1071       else
1072         return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
1073   return false;
1074 }
1075
1076 bool BinaryOperator::isNot(const Value *V) {
1077   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1078     return (Bop->getOpcode() == Instruction::Xor &&
1079             (isConstantAllOnes(Bop->getOperand(1)) ||
1080              isConstantAllOnes(Bop->getOperand(0))));
1081   return false;
1082 }
1083
1084 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1085   assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1086   return cast<BinaryOperator>(BinOp)->getOperand(1);
1087 }
1088
1089 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1090   return getNegArgument(const_cast<Value*>(BinOp));
1091 }
1092
1093 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1094   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1095   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1096   Value *Op0 = BO->getOperand(0);
1097   Value *Op1 = BO->getOperand(1);
1098   if (isConstantAllOnes(Op0)) return Op1;
1099
1100   assert(isConstantAllOnes(Op1));
1101   return Op0;
1102 }
1103
1104 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1105   return getNotArgument(const_cast<Value*>(BinOp));
1106 }
1107
1108
1109 // swapOperands - Exchange the two operands to this instruction.  This
1110 // instruction is safe to use on any binary instruction and does not
1111 // modify the semantics of the instruction.  If the instruction is
1112 // order dependent (SetLT f.e.) the opcode is changed.
1113 //
1114 bool BinaryOperator::swapOperands() {
1115   if (isCommutative())
1116     ;  // If the instruction is commutative, it is safe to swap the operands
1117   else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
1118     /// FIXME: SetCC instructions shouldn't all have different opcodes.
1119     setOpcode(SCI->getSwappedCondition());
1120   else
1121     return true;   // Can't commute operands
1122
1123   std::swap(Ops[0], Ops[1]);
1124   return false;
1125 }
1126
1127
1128 //===----------------------------------------------------------------------===//
1129 //                             SetCondInst Class
1130 //===----------------------------------------------------------------------===//
1131
1132 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
1133                          const std::string &Name, Instruction *InsertBefore)
1134   : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
1135
1136   // Make sure it's a valid type... getInverseCondition will assert out if not.
1137   assert(getInverseCondition(Opcode));
1138 }
1139
1140 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
1141                          const std::string &Name, BasicBlock *InsertAtEnd)
1142   : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertAtEnd) {
1143
1144   // Make sure it's a valid type... getInverseCondition will assert out if not.
1145   assert(getInverseCondition(Opcode));
1146 }
1147
1148 // getInverseCondition - Return the inverse of the current condition opcode.
1149 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
1150 //
1151 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
1152   switch (Opcode) {
1153   default:
1154     assert(0 && "Unknown setcc opcode!");
1155   case SetEQ: return SetNE;
1156   case SetNE: return SetEQ;
1157   case SetGT: return SetLE;
1158   case SetLT: return SetGE;
1159   case SetGE: return SetLT;
1160   case SetLE: return SetGT;
1161   }
1162 }
1163
1164 // getSwappedCondition - Return the condition opcode that would be the result
1165 // of exchanging the two operands of the setcc instruction without changing
1166 // the result produced.  Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
1167 //
1168 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
1169   switch (Opcode) {
1170   default: assert(0 && "Unknown setcc instruction!");
1171   case SetEQ: case SetNE: return Opcode;
1172   case SetGT: return SetLT;
1173   case SetLT: return SetGT;
1174   case SetGE: return SetLE;
1175   case SetLE: return SetGE;
1176   }
1177 }
1178
1179 //===----------------------------------------------------------------------===//
1180 //                        SwitchInst Implementation
1181 //===----------------------------------------------------------------------===//
1182
1183 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
1184   assert(Value && Default);
1185   ReservedSpace = 2+NumCases*2;
1186   NumOperands = 2;
1187   OperandList = new Use[ReservedSpace];
1188
1189   OperandList[0].init(Value, this);
1190   OperandList[1].init(Default, this);
1191 }
1192
1193 SwitchInst::SwitchInst(const SwitchInst &SI)
1194   : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
1195                    SI.getNumOperands()) {
1196   Use *OL = OperandList, *InOL = SI.OperandList;
1197   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
1198     OL[i].init(InOL[i], this);
1199     OL[i+1].init(InOL[i+1], this);
1200   }
1201 }
1202
1203 SwitchInst::~SwitchInst() {
1204   delete [] OperandList;
1205 }
1206
1207
1208 /// addCase - Add an entry to the switch instruction...
1209 ///
1210 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
1211   unsigned OpNo = NumOperands;
1212   if (OpNo+2 > ReservedSpace)
1213     resizeOperands(0);  // Get more space!
1214   // Initialize some new operands.
1215   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
1216   NumOperands = OpNo+2;
1217   OperandList[OpNo].init(OnVal, this);
1218   OperandList[OpNo+1].init(Dest, this);
1219 }
1220
1221 /// removeCase - This method removes the specified successor from the switch
1222 /// instruction.  Note that this cannot be used to remove the default
1223 /// destination (successor #0).
1224 ///
1225 void SwitchInst::removeCase(unsigned idx) {
1226   assert(idx != 0 && "Cannot remove the default case!");
1227   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
1228
1229   unsigned NumOps = getNumOperands();
1230   Use *OL = OperandList;
1231
1232   // Move everything after this operand down.
1233   //
1234   // FIXME: we could just swap with the end of the list, then erase.  However,
1235   // client might not expect this to happen.  The code as it is thrashes the
1236   // use/def lists, which is kinda lame.
1237   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
1238     OL[i-2] = OL[i];
1239     OL[i-2+1] = OL[i+1];
1240   }
1241
1242   // Nuke the last value.
1243   OL[NumOps-2].set(0);
1244   OL[NumOps-2+1].set(0);
1245   NumOperands = NumOps-2;
1246 }
1247
1248 /// resizeOperands - resize operands - This adjusts the length of the operands
1249 /// list according to the following behavior:
1250 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
1251 ///      of operation.  This grows the number of ops by 1.5 times.
1252 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
1253 ///   3. If NumOps == NumOperands, trim the reserved space.
1254 ///
1255 void SwitchInst::resizeOperands(unsigned NumOps) {
1256   if (NumOps == 0) {
1257     NumOps = getNumOperands()/2*6;
1258   } else if (NumOps*2 > NumOperands) {
1259     // No resize needed.
1260     if (ReservedSpace >= NumOps) return;
1261   } else if (NumOps == NumOperands) {
1262     if (ReservedSpace == NumOps) return;
1263   } else {
1264     return;
1265   }
1266
1267   ReservedSpace = NumOps;
1268   Use *NewOps = new Use[NumOps];
1269   Use *OldOps = OperandList;
1270   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1271       NewOps[i].init(OldOps[i], this);
1272       OldOps[i].set(0);
1273   }
1274   delete [] OldOps;
1275   OperandList = NewOps;
1276 }
1277
1278
1279 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
1280   return getSuccessor(idx);
1281 }
1282 unsigned SwitchInst::getNumSuccessorsV() const {
1283   return getNumSuccessors();
1284 }
1285 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1286   setSuccessor(idx, B);
1287 }
1288
1289
1290 // Define these methods here so vtables don't get emitted into every translation
1291 // unit that uses these classes.
1292
1293 GetElementPtrInst *GetElementPtrInst::clone() const {
1294   return new GetElementPtrInst(*this);
1295 }
1296
1297 BinaryOperator *BinaryOperator::clone() const {
1298   return create(getOpcode(), Ops[0], Ops[1]);
1299 }
1300
1301 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
1302 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
1303 FreeInst   *FreeInst::clone()   const { return new FreeInst(getOperand(0)); }
1304 LoadInst   *LoadInst::clone()   const { return new LoadInst(*this); }
1305 StoreInst  *StoreInst::clone()  const { return new StoreInst(*this); }
1306 CastInst   *CastInst::clone()   const { return new CastInst(*this); }
1307 CallInst   *CallInst::clone()   const { return new CallInst(*this); }
1308 ShiftInst  *ShiftInst::clone()  const { return new ShiftInst(*this); }
1309 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
1310 VAArgInst  *VAArgInst::clone()  const { return new VAArgInst(*this); }
1311 ExtractElementInst *ExtractElementInst::clone() const {
1312   return new ExtractElementInst(*this);
1313 }
1314 InsertElementInst *InsertElementInst::clone() const {
1315   return new InsertElementInst(*this);
1316 }
1317 ShuffleVectorInst *ShuffleVectorInst::clone() const {
1318   return new ShuffleVectorInst(*this);
1319 }
1320 PHINode    *PHINode::clone()    const { return new PHINode(*this); }
1321 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
1322 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
1323 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
1324 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
1325 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
1326 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}