Taken into account Duncan's comments for r149481 dated by 2nd Feb 2012:
[oota-llvm.git] / lib / VMCore / Instructions.cpp
1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/MathExtras.h"
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 //                            CallSite Class
30 //===----------------------------------------------------------------------===//
31
32 User::op_iterator CallSite::getCallee() const {
33   Instruction *II(getInstruction());
34   return isCall()
35     ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
36     : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
37 }
38
39 //===----------------------------------------------------------------------===//
40 //                            TerminatorInst Class
41 //===----------------------------------------------------------------------===//
42
43 // Out of line virtual method, so the vtable, etc has a home.
44 TerminatorInst::~TerminatorInst() {
45 }
46
47 //===----------------------------------------------------------------------===//
48 //                           UnaryInstruction Class
49 //===----------------------------------------------------------------------===//
50
51 // Out of line virtual method, so the vtable, etc has a home.
52 UnaryInstruction::~UnaryInstruction() {
53 }
54
55 //===----------------------------------------------------------------------===//
56 //                              SelectInst Class
57 //===----------------------------------------------------------------------===//
58
59 /// areInvalidOperands - Return a string if the specified operands are invalid
60 /// for a select operation, otherwise return null.
61 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
62   if (Op1->getType() != Op2->getType())
63     return "both values to select must have same type";
64   
65   if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
66     // Vector select.
67     if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
68       return "vector select condition element type must be i1";
69     VectorType *ET = dyn_cast<VectorType>(Op1->getType());
70     if (ET == 0)
71       return "selected values for vector select must be vectors";
72     if (ET->getNumElements() != VT->getNumElements())
73       return "vector select requires selected vectors to have "
74                    "the same vector length as select condition";
75   } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
76     return "select condition must be i1 or <n x i1>";
77   }
78   return 0;
79 }
80
81
82 //===----------------------------------------------------------------------===//
83 //                               PHINode Class
84 //===----------------------------------------------------------------------===//
85
86 PHINode::PHINode(const PHINode &PN)
87   : Instruction(PN.getType(), Instruction::PHI,
88                 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
89     ReservedSpace(PN.getNumOperands()) {
90   std::copy(PN.op_begin(), PN.op_end(), op_begin());
91   std::copy(PN.block_begin(), PN.block_end(), block_begin());
92   SubclassOptionalData = PN.SubclassOptionalData;
93 }
94
95 PHINode::~PHINode() {
96   dropHungoffUses();
97 }
98
99 Use *PHINode::allocHungoffUses(unsigned N) const {
100   // Allocate the array of Uses of the incoming values, followed by a pointer
101   // (with bottom bit set) to the User, followed by the array of pointers to
102   // the incoming basic blocks.
103   size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
104     + N * sizeof(BasicBlock*);
105   Use *Begin = static_cast<Use*>(::operator new(size));
106   Use *End = Begin + N;
107   (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
108   return Use::initTags(Begin, End);
109 }
110
111 // removeIncomingValue - Remove an incoming value.  This is useful if a
112 // predecessor basic block is deleted.
113 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
114   Value *Removed = getIncomingValue(Idx);
115
116   // Move everything after this operand down.
117   //
118   // FIXME: we could just swap with the end of the list, then erase.  However,
119   // clients might not expect this to happen.  The code as it is thrashes the
120   // use/def lists, which is kinda lame.
121   std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
122   std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
123
124   // Nuke the last value.
125   Op<-1>().set(0);
126   --NumOperands;
127
128   // If the PHI node is dead, because it has zero entries, nuke it now.
129   if (getNumOperands() == 0 && DeletePHIIfEmpty) {
130     // If anyone is using this PHI, make them use a dummy value instead...
131     replaceAllUsesWith(UndefValue::get(getType()));
132     eraseFromParent();
133   }
134   return Removed;
135 }
136
137 /// growOperands - grow operands - This grows the operand list in response
138 /// to a push_back style of operation.  This grows the number of ops by 1.5
139 /// times.
140 ///
141 void PHINode::growOperands() {
142   unsigned e = getNumOperands();
143   unsigned NumOps = e + e / 2;
144   if (NumOps < 2) NumOps = 2;      // 2 op PHI nodes are VERY common.
145
146   Use *OldOps = op_begin();
147   BasicBlock **OldBlocks = block_begin();
148
149   ReservedSpace = NumOps;
150   OperandList = allocHungoffUses(ReservedSpace);
151
152   std::copy(OldOps, OldOps + e, op_begin());
153   std::copy(OldBlocks, OldBlocks + e, block_begin());
154
155   Use::zap(OldOps, OldOps + e, true);
156 }
157
158 /// hasConstantValue - If the specified PHI node always merges together the same
159 /// value, return the value, otherwise return null.
160 Value *PHINode::hasConstantValue() const {
161   // Exploit the fact that phi nodes always have at least one entry.
162   Value *ConstantValue = getIncomingValue(0);
163   for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
164     if (getIncomingValue(i) != ConstantValue)
165       return 0; // Incoming values not all the same.
166   return ConstantValue;
167 }
168
169 //===----------------------------------------------------------------------===//
170 //                       LandingPadInst Implementation
171 //===----------------------------------------------------------------------===//
172
173 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
174                                unsigned NumReservedValues, const Twine &NameStr,
175                                Instruction *InsertBefore)
176   : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
177   init(PersonalityFn, 1 + NumReservedValues, NameStr);
178 }
179
180 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
181                                unsigned NumReservedValues, const Twine &NameStr,
182                                BasicBlock *InsertAtEnd)
183   : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
184   init(PersonalityFn, 1 + NumReservedValues, NameStr);
185 }
186
187 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
188   : Instruction(LP.getType(), Instruction::LandingPad,
189                 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
190     ReservedSpace(LP.getNumOperands()) {
191   Use *OL = OperandList, *InOL = LP.OperandList;
192   for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
193     OL[I] = InOL[I];
194
195   setCleanup(LP.isCleanup());
196 }
197
198 LandingPadInst::~LandingPadInst() {
199   dropHungoffUses();
200 }
201
202 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
203                                        unsigned NumReservedClauses,
204                                        const Twine &NameStr,
205                                        Instruction *InsertBefore) {
206   return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
207                             InsertBefore);
208 }
209
210 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
211                                        unsigned NumReservedClauses,
212                                        const Twine &NameStr,
213                                        BasicBlock *InsertAtEnd) {
214   return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
215                             InsertAtEnd);
216 }
217
218 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
219                           const Twine &NameStr) {
220   ReservedSpace = NumReservedValues;
221   NumOperands = 1;
222   OperandList = allocHungoffUses(ReservedSpace);
223   OperandList[0] = PersFn;
224   setName(NameStr);
225   setCleanup(false);
226 }
227
228 /// growOperands - grow operands - This grows the operand list in response to a
229 /// push_back style of operation. This grows the number of ops by 2 times.
230 void LandingPadInst::growOperands(unsigned Size) {
231   unsigned e = getNumOperands();
232   if (ReservedSpace >= e + Size) return;
233   ReservedSpace = (e + Size / 2) * 2;
234
235   Use *NewOps = allocHungoffUses(ReservedSpace);
236   Use *OldOps = OperandList;
237   for (unsigned i = 0; i != e; ++i)
238       NewOps[i] = OldOps[i];
239
240   OperandList = NewOps;
241   Use::zap(OldOps, OldOps + e, true);
242 }
243
244 void LandingPadInst::addClause(Value *Val) {
245   unsigned OpNo = getNumOperands();
246   growOperands(1);
247   assert(OpNo < ReservedSpace && "Growing didn't work!");
248   ++NumOperands;
249   OperandList[OpNo] = Val;
250 }
251
252 //===----------------------------------------------------------------------===//
253 //                        CallInst Implementation
254 //===----------------------------------------------------------------------===//
255
256 CallInst::~CallInst() {
257 }
258
259 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
260   assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
261   Op<-1>() = Func;
262
263 #ifndef NDEBUG
264   FunctionType *FTy =
265     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
266
267   assert((Args.size() == FTy->getNumParams() ||
268           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
269          "Calling a function with bad signature!");
270
271   for (unsigned i = 0; i != Args.size(); ++i)
272     assert((i >= FTy->getNumParams() || 
273             FTy->getParamType(i) == Args[i]->getType()) &&
274            "Calling a function with a bad signature!");
275 #endif
276
277   std::copy(Args.begin(), Args.end(), op_begin());
278   setName(NameStr);
279 }
280
281 void CallInst::init(Value *Func, const Twine &NameStr) {
282   assert(NumOperands == 1 && "NumOperands not set up?");
283   Op<-1>() = Func;
284
285 #ifndef NDEBUG
286   FunctionType *FTy =
287     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
288
289   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
290 #endif
291
292   setName(NameStr);
293 }
294
295 CallInst::CallInst(Value *Func, const Twine &Name,
296                    Instruction *InsertBefore)
297   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
298                                    ->getElementType())->getReturnType(),
299                 Instruction::Call,
300                 OperandTraits<CallInst>::op_end(this) - 1,
301                 1, InsertBefore) {
302   init(Func, Name);
303 }
304
305 CallInst::CallInst(Value *Func, const Twine &Name,
306                    BasicBlock *InsertAtEnd)
307   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
308                                    ->getElementType())->getReturnType(),
309                 Instruction::Call,
310                 OperandTraits<CallInst>::op_end(this) - 1,
311                 1, InsertAtEnd) {
312   init(Func, Name);
313 }
314
315 CallInst::CallInst(const CallInst &CI)
316   : Instruction(CI.getType(), Instruction::Call,
317                 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
318                 CI.getNumOperands()) {
319   setAttributes(CI.getAttributes());
320   setTailCall(CI.isTailCall());
321   setCallingConv(CI.getCallingConv());
322     
323   std::copy(CI.op_begin(), CI.op_end(), op_begin());
324   SubclassOptionalData = CI.SubclassOptionalData;
325 }
326
327 void CallInst::addAttribute(unsigned i, Attributes attr) {
328   AttrListPtr PAL = getAttributes();
329   PAL = PAL.addAttr(i, attr);
330   setAttributes(PAL);
331 }
332
333 void CallInst::removeAttribute(unsigned i, Attributes attr) {
334   AttrListPtr PAL = getAttributes();
335   PAL = PAL.removeAttr(i, attr);
336   setAttributes(PAL);
337 }
338
339 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
340   if (AttributeList.paramHasAttr(i, attr))
341     return true;
342   if (const Function *F = getCalledFunction())
343     return F->paramHasAttr(i, attr);
344   return false;
345 }
346
347 /// IsConstantOne - Return true only if val is constant int 1
348 static bool IsConstantOne(Value *val) {
349   assert(val && "IsConstantOne does not work with NULL val");
350   return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
351 }
352
353 static Instruction *createMalloc(Instruction *InsertBefore,
354                                  BasicBlock *InsertAtEnd, Type *IntPtrTy,
355                                  Type *AllocTy, Value *AllocSize, 
356                                  Value *ArraySize, Function *MallocF,
357                                  const Twine &Name) {
358   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
359          "createMalloc needs either InsertBefore or InsertAtEnd");
360
361   // malloc(type) becomes: 
362   //       bitcast (i8* malloc(typeSize)) to type*
363   // malloc(type, arraySize) becomes:
364   //       bitcast (i8 *malloc(typeSize*arraySize)) to type*
365   if (!ArraySize)
366     ArraySize = ConstantInt::get(IntPtrTy, 1);
367   else if (ArraySize->getType() != IntPtrTy) {
368     if (InsertBefore)
369       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
370                                               "", InsertBefore);
371     else
372       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
373                                               "", InsertAtEnd);
374   }
375
376   if (!IsConstantOne(ArraySize)) {
377     if (IsConstantOne(AllocSize)) {
378       AllocSize = ArraySize;         // Operand * 1 = Operand
379     } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
380       Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
381                                                      false /*ZExt*/);
382       // Malloc arg is constant product of type size and array size
383       AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
384     } else {
385       // Multiply type size by the array size...
386       if (InsertBefore)
387         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
388                                               "mallocsize", InsertBefore);
389       else
390         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
391                                               "mallocsize", InsertAtEnd);
392     }
393   }
394
395   assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
396   // Create the call to Malloc.
397   BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
398   Module* M = BB->getParent()->getParent();
399   Type *BPTy = Type::getInt8PtrTy(BB->getContext());
400   Value *MallocFunc = MallocF;
401   if (!MallocFunc)
402     // prototype malloc as "void *malloc(size_t)"
403     MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
404   PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
405   CallInst *MCall = NULL;
406   Instruction *Result = NULL;
407   if (InsertBefore) {
408     MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
409     Result = MCall;
410     if (Result->getType() != AllocPtrType)
411       // Create a cast instruction to convert to the right type...
412       Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
413   } else {
414     MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
415     Result = MCall;
416     if (Result->getType() != AllocPtrType) {
417       InsertAtEnd->getInstList().push_back(MCall);
418       // Create a cast instruction to convert to the right type...
419       Result = new BitCastInst(MCall, AllocPtrType, Name);
420     }
421   }
422   MCall->setTailCall();
423   if (Function *F = dyn_cast<Function>(MallocFunc)) {
424     MCall->setCallingConv(F->getCallingConv());
425     if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
426   }
427   assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
428
429   return Result;
430 }
431
432 /// CreateMalloc - Generate the IR for a call to malloc:
433 /// 1. Compute the malloc call's argument as the specified type's size,
434 ///    possibly multiplied by the array size if the array size is not
435 ///    constant 1.
436 /// 2. Call malloc with that argument.
437 /// 3. Bitcast the result of the malloc call to the specified type.
438 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
439                                     Type *IntPtrTy, Type *AllocTy,
440                                     Value *AllocSize, Value *ArraySize,
441                                     Function * MallocF,
442                                     const Twine &Name) {
443   return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
444                       ArraySize, MallocF, Name);
445 }
446
447 /// CreateMalloc - Generate the IR for a call to malloc:
448 /// 1. Compute the malloc call's argument as the specified type's size,
449 ///    possibly multiplied by the array size if the array size is not
450 ///    constant 1.
451 /// 2. Call malloc with that argument.
452 /// 3. Bitcast the result of the malloc call to the specified type.
453 /// Note: This function does not add the bitcast to the basic block, that is the
454 /// responsibility of the caller.
455 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
456                                     Type *IntPtrTy, Type *AllocTy,
457                                     Value *AllocSize, Value *ArraySize, 
458                                     Function *MallocF, const Twine &Name) {
459   return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
460                       ArraySize, MallocF, Name);
461 }
462
463 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
464                                BasicBlock *InsertAtEnd) {
465   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
466          "createFree needs either InsertBefore or InsertAtEnd");
467   assert(Source->getType()->isPointerTy() &&
468          "Can not free something of nonpointer type!");
469
470   BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
471   Module* M = BB->getParent()->getParent();
472
473   Type *VoidTy = Type::getVoidTy(M->getContext());
474   Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
475   // prototype free as "void free(void*)"
476   Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
477   CallInst* Result = NULL;
478   Value *PtrCast = Source;
479   if (InsertBefore) {
480     if (Source->getType() != IntPtrTy)
481       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
482     Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
483   } else {
484     if (Source->getType() != IntPtrTy)
485       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
486     Result = CallInst::Create(FreeFunc, PtrCast, "");
487   }
488   Result->setTailCall();
489   if (Function *F = dyn_cast<Function>(FreeFunc))
490     Result->setCallingConv(F->getCallingConv());
491
492   return Result;
493 }
494
495 /// CreateFree - Generate the IR for a call to the builtin free function.
496 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
497   return createFree(Source, InsertBefore, NULL);
498 }
499
500 /// CreateFree - Generate the IR for a call to the builtin free function.
501 /// Note: This function does not add the call to the basic block, that is the
502 /// responsibility of the caller.
503 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
504   Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
505   assert(FreeCall && "CreateFree did not create a CallInst");
506   return FreeCall;
507 }
508
509 //===----------------------------------------------------------------------===//
510 //                        InvokeInst Implementation
511 //===----------------------------------------------------------------------===//
512
513 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
514                       ArrayRef<Value *> Args, const Twine &NameStr) {
515   assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
516   Op<-3>() = Fn;
517   Op<-2>() = IfNormal;
518   Op<-1>() = IfException;
519
520 #ifndef NDEBUG
521   FunctionType *FTy =
522     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
523
524   assert(((Args.size() == FTy->getNumParams()) ||
525           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
526          "Invoking a function with bad signature");
527
528   for (unsigned i = 0, e = Args.size(); i != e; i++)
529     assert((i >= FTy->getNumParams() || 
530             FTy->getParamType(i) == Args[i]->getType()) &&
531            "Invoking a function with a bad signature!");
532 #endif
533
534   std::copy(Args.begin(), Args.end(), op_begin());
535   setName(NameStr);
536 }
537
538 InvokeInst::InvokeInst(const InvokeInst &II)
539   : TerminatorInst(II.getType(), Instruction::Invoke,
540                    OperandTraits<InvokeInst>::op_end(this)
541                    - II.getNumOperands(),
542                    II.getNumOperands()) {
543   setAttributes(II.getAttributes());
544   setCallingConv(II.getCallingConv());
545   std::copy(II.op_begin(), II.op_end(), op_begin());
546   SubclassOptionalData = II.SubclassOptionalData;
547 }
548
549 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
550   return getSuccessor(idx);
551 }
552 unsigned InvokeInst::getNumSuccessorsV() const {
553   return getNumSuccessors();
554 }
555 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
556   return setSuccessor(idx, B);
557 }
558
559 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
560   if (AttributeList.paramHasAttr(i, attr))
561     return true;
562   if (const Function *F = getCalledFunction())
563     return F->paramHasAttr(i, attr);
564   return false;
565 }
566
567 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
568   AttrListPtr PAL = getAttributes();
569   PAL = PAL.addAttr(i, attr);
570   setAttributes(PAL);
571 }
572
573 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
574   AttrListPtr PAL = getAttributes();
575   PAL = PAL.removeAttr(i, attr);
576   setAttributes(PAL);
577 }
578
579 LandingPadInst *InvokeInst::getLandingPadInst() const {
580   return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
581 }
582
583 //===----------------------------------------------------------------------===//
584 //                        ReturnInst Implementation
585 //===----------------------------------------------------------------------===//
586
587 ReturnInst::ReturnInst(const ReturnInst &RI)
588   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
589                    OperandTraits<ReturnInst>::op_end(this) -
590                      RI.getNumOperands(),
591                    RI.getNumOperands()) {
592   if (RI.getNumOperands())
593     Op<0>() = RI.Op<0>();
594   SubclassOptionalData = RI.SubclassOptionalData;
595 }
596
597 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
598   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
599                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
600                    InsertBefore) {
601   if (retVal)
602     Op<0>() = retVal;
603 }
604 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
605   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
606                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
607                    InsertAtEnd) {
608   if (retVal)
609     Op<0>() = retVal;
610 }
611 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
612   : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
613                    OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
614 }
615
616 unsigned ReturnInst::getNumSuccessorsV() const {
617   return getNumSuccessors();
618 }
619
620 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
621 /// emit the vtable for the class in this translation unit.
622 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
623   llvm_unreachable("ReturnInst has no successors!");
624 }
625
626 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
627   llvm_unreachable("ReturnInst has no successors!");
628 }
629
630 ReturnInst::~ReturnInst() {
631 }
632
633 //===----------------------------------------------------------------------===//
634 //                        ResumeInst Implementation
635 //===----------------------------------------------------------------------===//
636
637 ResumeInst::ResumeInst(const ResumeInst &RI)
638   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
639                    OperandTraits<ResumeInst>::op_begin(this), 1) {
640   Op<0>() = RI.Op<0>();
641 }
642
643 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
644   : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
645                    OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
646   Op<0>() = Exn;
647 }
648
649 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
650   : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
651                    OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
652   Op<0>() = Exn;
653 }
654
655 unsigned ResumeInst::getNumSuccessorsV() const {
656   return getNumSuccessors();
657 }
658
659 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
660   llvm_unreachable("ResumeInst has no successors!");
661 }
662
663 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
664   llvm_unreachable("ResumeInst has no successors!");
665 }
666
667 //===----------------------------------------------------------------------===//
668 //                      UnreachableInst Implementation
669 //===----------------------------------------------------------------------===//
670
671 UnreachableInst::UnreachableInst(LLVMContext &Context, 
672                                  Instruction *InsertBefore)
673   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
674                    0, 0, InsertBefore) {
675 }
676 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
677   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
678                    0, 0, InsertAtEnd) {
679 }
680
681 unsigned UnreachableInst::getNumSuccessorsV() const {
682   return getNumSuccessors();
683 }
684
685 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
686   llvm_unreachable("UnreachableInst has no successors!");
687 }
688
689 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
690   llvm_unreachable("UnreachableInst has no successors!");
691 }
692
693 //===----------------------------------------------------------------------===//
694 //                        BranchInst Implementation
695 //===----------------------------------------------------------------------===//
696
697 void BranchInst::AssertOK() {
698   if (isConditional())
699     assert(getCondition()->getType()->isIntegerTy(1) &&
700            "May only branch on boolean predicates!");
701 }
702
703 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
704   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
705                    OperandTraits<BranchInst>::op_end(this) - 1,
706                    1, InsertBefore) {
707   assert(IfTrue != 0 && "Branch destination may not be null!");
708   Op<-1>() = IfTrue;
709 }
710 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
711                        Instruction *InsertBefore)
712   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
713                    OperandTraits<BranchInst>::op_end(this) - 3,
714                    3, InsertBefore) {
715   Op<-1>() = IfTrue;
716   Op<-2>() = IfFalse;
717   Op<-3>() = Cond;
718 #ifndef NDEBUG
719   AssertOK();
720 #endif
721 }
722
723 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
724   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
725                    OperandTraits<BranchInst>::op_end(this) - 1,
726                    1, InsertAtEnd) {
727   assert(IfTrue != 0 && "Branch destination may not be null!");
728   Op<-1>() = IfTrue;
729 }
730
731 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
732            BasicBlock *InsertAtEnd)
733   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
734                    OperandTraits<BranchInst>::op_end(this) - 3,
735                    3, InsertAtEnd) {
736   Op<-1>() = IfTrue;
737   Op<-2>() = IfFalse;
738   Op<-3>() = Cond;
739 #ifndef NDEBUG
740   AssertOK();
741 #endif
742 }
743
744
745 BranchInst::BranchInst(const BranchInst &BI) :
746   TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
747                  OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
748                  BI.getNumOperands()) {
749   Op<-1>() = BI.Op<-1>();
750   if (BI.getNumOperands() != 1) {
751     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
752     Op<-3>() = BI.Op<-3>();
753     Op<-2>() = BI.Op<-2>();
754   }
755   SubclassOptionalData = BI.SubclassOptionalData;
756 }
757
758 void BranchInst::swapSuccessors() {
759   assert(isConditional() &&
760          "Cannot swap successors of an unconditional branch");
761   Op<-1>().swap(Op<-2>());
762
763   // Update profile metadata if present and it matches our structural
764   // expectations.
765   MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
766   if (!ProfileData || ProfileData->getNumOperands() != 3)
767     return;
768
769   // The first operand is the name. Fetch them backwards and build a new one.
770   Value *Ops[] = {
771     ProfileData->getOperand(0),
772     ProfileData->getOperand(2),
773     ProfileData->getOperand(1)
774   };
775   setMetadata(LLVMContext::MD_prof,
776               MDNode::get(ProfileData->getContext(), Ops));
777 }
778
779 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
780   return getSuccessor(idx);
781 }
782 unsigned BranchInst::getNumSuccessorsV() const {
783   return getNumSuccessors();
784 }
785 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
786   setSuccessor(idx, B);
787 }
788
789
790 //===----------------------------------------------------------------------===//
791 //                        AllocaInst Implementation
792 //===----------------------------------------------------------------------===//
793
794 static Value *getAISize(LLVMContext &Context, Value *Amt) {
795   if (!Amt)
796     Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
797   else {
798     assert(!isa<BasicBlock>(Amt) &&
799            "Passed basic block into allocation size parameter! Use other ctor");
800     assert(Amt->getType()->isIntegerTy() &&
801            "Allocation array size is not an integer!");
802   }
803   return Amt;
804 }
805
806 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
807                        const Twine &Name, Instruction *InsertBefore)
808   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
809                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
810   setAlignment(0);
811   assert(!Ty->isVoidTy() && "Cannot allocate void!");
812   setName(Name);
813 }
814
815 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
816                        const Twine &Name, BasicBlock *InsertAtEnd)
817   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
818                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
819   setAlignment(0);
820   assert(!Ty->isVoidTy() && "Cannot allocate void!");
821   setName(Name);
822 }
823
824 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
825                        Instruction *InsertBefore)
826   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
827                      getAISize(Ty->getContext(), 0), InsertBefore) {
828   setAlignment(0);
829   assert(!Ty->isVoidTy() && "Cannot allocate void!");
830   setName(Name);
831 }
832
833 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
834                        BasicBlock *InsertAtEnd)
835   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
836                      getAISize(Ty->getContext(), 0), InsertAtEnd) {
837   setAlignment(0);
838   assert(!Ty->isVoidTy() && "Cannot allocate void!");
839   setName(Name);
840 }
841
842 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
843                        const Twine &Name, Instruction *InsertBefore)
844   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
845                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
846   setAlignment(Align);
847   assert(!Ty->isVoidTy() && "Cannot allocate void!");
848   setName(Name);
849 }
850
851 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
852                        const Twine &Name, BasicBlock *InsertAtEnd)
853   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
854                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
855   setAlignment(Align);
856   assert(!Ty->isVoidTy() && "Cannot allocate void!");
857   setName(Name);
858 }
859
860 // Out of line virtual method, so the vtable, etc has a home.
861 AllocaInst::~AllocaInst() {
862 }
863
864 void AllocaInst::setAlignment(unsigned Align) {
865   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
866   assert(Align <= MaximumAlignment &&
867          "Alignment is greater than MaximumAlignment!");
868   setInstructionSubclassData(Log2_32(Align) + 1);
869   assert(getAlignment() == Align && "Alignment representation error!");
870 }
871
872 bool AllocaInst::isArrayAllocation() const {
873   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
874     return !CI->isOne();
875   return true;
876 }
877
878 Type *AllocaInst::getAllocatedType() const {
879   return getType()->getElementType();
880 }
881
882 /// isStaticAlloca - Return true if this alloca is in the entry block of the
883 /// function and is a constant size.  If so, the code generator will fold it
884 /// into the prolog/epilog code, so it is basically free.
885 bool AllocaInst::isStaticAlloca() const {
886   // Must be constant size.
887   if (!isa<ConstantInt>(getArraySize())) return false;
888   
889   // Must be in the entry block.
890   const BasicBlock *Parent = getParent();
891   return Parent == &Parent->getParent()->front();
892 }
893
894 //===----------------------------------------------------------------------===//
895 //                           LoadInst Implementation
896 //===----------------------------------------------------------------------===//
897
898 void LoadInst::AssertOK() {
899   assert(getOperand(0)->getType()->isPointerTy() &&
900          "Ptr must have pointer type.");
901   assert(!(isAtomic() && getAlignment() == 0) &&
902          "Alignment required for atomic load");
903 }
904
905 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
906   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
907                      Load, Ptr, InsertBef) {
908   setVolatile(false);
909   setAlignment(0);
910   setAtomic(NotAtomic);
911   AssertOK();
912   setName(Name);
913 }
914
915 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
916   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
917                      Load, Ptr, InsertAE) {
918   setVolatile(false);
919   setAlignment(0);
920   setAtomic(NotAtomic);
921   AssertOK();
922   setName(Name);
923 }
924
925 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
926                    Instruction *InsertBef)
927   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
928                      Load, Ptr, InsertBef) {
929   setVolatile(isVolatile);
930   setAlignment(0);
931   setAtomic(NotAtomic);
932   AssertOK();
933   setName(Name);
934 }
935
936 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
937                    BasicBlock *InsertAE)
938   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
939                      Load, Ptr, InsertAE) {
940   setVolatile(isVolatile);
941   setAlignment(0);
942   setAtomic(NotAtomic);
943   AssertOK();
944   setName(Name);
945 }
946
947 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
948                    unsigned Align, Instruction *InsertBef)
949   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
950                      Load, Ptr, InsertBef) {
951   setVolatile(isVolatile);
952   setAlignment(Align);
953   setAtomic(NotAtomic);
954   AssertOK();
955   setName(Name);
956 }
957
958 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
959                    unsigned Align, BasicBlock *InsertAE)
960   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
961                      Load, Ptr, InsertAE) {
962   setVolatile(isVolatile);
963   setAlignment(Align);
964   setAtomic(NotAtomic);
965   AssertOK();
966   setName(Name);
967 }
968
969 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
970                    unsigned Align, AtomicOrdering Order,
971                    SynchronizationScope SynchScope,
972                    Instruction *InsertBef)
973   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
974                      Load, Ptr, InsertBef) {
975   setVolatile(isVolatile);
976   setAlignment(Align);
977   setAtomic(Order, SynchScope);
978   AssertOK();
979   setName(Name);
980 }
981
982 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
983                    unsigned Align, AtomicOrdering Order,
984                    SynchronizationScope SynchScope,
985                    BasicBlock *InsertAE)
986   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
987                      Load, Ptr, InsertAE) {
988   setVolatile(isVolatile);
989   setAlignment(Align);
990   setAtomic(Order, SynchScope);
991   AssertOK();
992   setName(Name);
993 }
994
995 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
996   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
997                      Load, Ptr, InsertBef) {
998   setVolatile(false);
999   setAlignment(0);
1000   setAtomic(NotAtomic);
1001   AssertOK();
1002   if (Name && Name[0]) setName(Name);
1003 }
1004
1005 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1006   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1007                      Load, Ptr, InsertAE) {
1008   setVolatile(false);
1009   setAlignment(0);
1010   setAtomic(NotAtomic);
1011   AssertOK();
1012   if (Name && Name[0]) setName(Name);
1013 }
1014
1015 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1016                    Instruction *InsertBef)
1017 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1018                    Load, Ptr, InsertBef) {
1019   setVolatile(isVolatile);
1020   setAlignment(0);
1021   setAtomic(NotAtomic);
1022   AssertOK();
1023   if (Name && Name[0]) setName(Name);
1024 }
1025
1026 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1027                    BasicBlock *InsertAE)
1028   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1029                      Load, Ptr, InsertAE) {
1030   setVolatile(isVolatile);
1031   setAlignment(0);
1032   setAtomic(NotAtomic);
1033   AssertOK();
1034   if (Name && Name[0]) setName(Name);
1035 }
1036
1037 void LoadInst::setAlignment(unsigned Align) {
1038   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1039   assert(Align <= MaximumAlignment &&
1040          "Alignment is greater than MaximumAlignment!");
1041   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1042                              ((Log2_32(Align)+1)<<1));
1043   assert(getAlignment() == Align && "Alignment representation error!");
1044 }
1045
1046 //===----------------------------------------------------------------------===//
1047 //                           StoreInst Implementation
1048 //===----------------------------------------------------------------------===//
1049
1050 void StoreInst::AssertOK() {
1051   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1052   assert(getOperand(1)->getType()->isPointerTy() &&
1053          "Ptr must have pointer type!");
1054   assert(getOperand(0)->getType() ==
1055                  cast<PointerType>(getOperand(1)->getType())->getElementType()
1056          && "Ptr must be a pointer to Val type!");
1057   assert(!(isAtomic() && getAlignment() == 0) &&
1058          "Alignment required for atomic load");
1059 }
1060
1061
1062 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1063   : Instruction(Type::getVoidTy(val->getContext()), Store,
1064                 OperandTraits<StoreInst>::op_begin(this),
1065                 OperandTraits<StoreInst>::operands(this),
1066                 InsertBefore) {
1067   Op<0>() = val;
1068   Op<1>() = addr;
1069   setVolatile(false);
1070   setAlignment(0);
1071   setAtomic(NotAtomic);
1072   AssertOK();
1073 }
1074
1075 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1076   : Instruction(Type::getVoidTy(val->getContext()), Store,
1077                 OperandTraits<StoreInst>::op_begin(this),
1078                 OperandTraits<StoreInst>::operands(this),
1079                 InsertAtEnd) {
1080   Op<0>() = val;
1081   Op<1>() = addr;
1082   setVolatile(false);
1083   setAlignment(0);
1084   setAtomic(NotAtomic);
1085   AssertOK();
1086 }
1087
1088 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1089                      Instruction *InsertBefore)
1090   : Instruction(Type::getVoidTy(val->getContext()), Store,
1091                 OperandTraits<StoreInst>::op_begin(this),
1092                 OperandTraits<StoreInst>::operands(this),
1093                 InsertBefore) {
1094   Op<0>() = val;
1095   Op<1>() = addr;
1096   setVolatile(isVolatile);
1097   setAlignment(0);
1098   setAtomic(NotAtomic);
1099   AssertOK();
1100 }
1101
1102 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1103                      unsigned Align, Instruction *InsertBefore)
1104   : Instruction(Type::getVoidTy(val->getContext()), Store,
1105                 OperandTraits<StoreInst>::op_begin(this),
1106                 OperandTraits<StoreInst>::operands(this),
1107                 InsertBefore) {
1108   Op<0>() = val;
1109   Op<1>() = addr;
1110   setVolatile(isVolatile);
1111   setAlignment(Align);
1112   setAtomic(NotAtomic);
1113   AssertOK();
1114 }
1115
1116 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1117                      unsigned Align, AtomicOrdering Order,
1118                      SynchronizationScope SynchScope,
1119                      Instruction *InsertBefore)
1120   : Instruction(Type::getVoidTy(val->getContext()), Store,
1121                 OperandTraits<StoreInst>::op_begin(this),
1122                 OperandTraits<StoreInst>::operands(this),
1123                 InsertBefore) {
1124   Op<0>() = val;
1125   Op<1>() = addr;
1126   setVolatile(isVolatile);
1127   setAlignment(Align);
1128   setAtomic(Order, SynchScope);
1129   AssertOK();
1130 }
1131
1132 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1133                      BasicBlock *InsertAtEnd)
1134   : Instruction(Type::getVoidTy(val->getContext()), Store,
1135                 OperandTraits<StoreInst>::op_begin(this),
1136                 OperandTraits<StoreInst>::operands(this),
1137                 InsertAtEnd) {
1138   Op<0>() = val;
1139   Op<1>() = addr;
1140   setVolatile(isVolatile);
1141   setAlignment(0);
1142   setAtomic(NotAtomic);
1143   AssertOK();
1144 }
1145
1146 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1147                      unsigned Align, BasicBlock *InsertAtEnd)
1148   : Instruction(Type::getVoidTy(val->getContext()), Store,
1149                 OperandTraits<StoreInst>::op_begin(this),
1150                 OperandTraits<StoreInst>::operands(this),
1151                 InsertAtEnd) {
1152   Op<0>() = val;
1153   Op<1>() = addr;
1154   setVolatile(isVolatile);
1155   setAlignment(Align);
1156   setAtomic(NotAtomic);
1157   AssertOK();
1158 }
1159
1160 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1161                      unsigned Align, AtomicOrdering Order,
1162                      SynchronizationScope SynchScope,
1163                      BasicBlock *InsertAtEnd)
1164   : Instruction(Type::getVoidTy(val->getContext()), Store,
1165                 OperandTraits<StoreInst>::op_begin(this),
1166                 OperandTraits<StoreInst>::operands(this),
1167                 InsertAtEnd) {
1168   Op<0>() = val;
1169   Op<1>() = addr;
1170   setVolatile(isVolatile);
1171   setAlignment(Align);
1172   setAtomic(Order, SynchScope);
1173   AssertOK();
1174 }
1175
1176 void StoreInst::setAlignment(unsigned Align) {
1177   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1178   assert(Align <= MaximumAlignment &&
1179          "Alignment is greater than MaximumAlignment!");
1180   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1181                              ((Log2_32(Align)+1) << 1));
1182   assert(getAlignment() == Align && "Alignment representation error!");
1183 }
1184
1185 //===----------------------------------------------------------------------===//
1186 //                       AtomicCmpXchgInst Implementation
1187 //===----------------------------------------------------------------------===//
1188
1189 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1190                              AtomicOrdering Ordering,
1191                              SynchronizationScope SynchScope) {
1192   Op<0>() = Ptr;
1193   Op<1>() = Cmp;
1194   Op<2>() = NewVal;
1195   setOrdering(Ordering);
1196   setSynchScope(SynchScope);
1197
1198   assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1199          "All operands must be non-null!");
1200   assert(getOperand(0)->getType()->isPointerTy() &&
1201          "Ptr must have pointer type!");
1202   assert(getOperand(1)->getType() ==
1203                  cast<PointerType>(getOperand(0)->getType())->getElementType()
1204          && "Ptr must be a pointer to Cmp type!");
1205   assert(getOperand(2)->getType() ==
1206                  cast<PointerType>(getOperand(0)->getType())->getElementType()
1207          && "Ptr must be a pointer to NewVal type!");
1208   assert(Ordering != NotAtomic &&
1209          "AtomicCmpXchg instructions must be atomic!");
1210 }
1211
1212 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1213                                      AtomicOrdering Ordering,
1214                                      SynchronizationScope SynchScope,
1215                                      Instruction *InsertBefore)
1216   : Instruction(Cmp->getType(), AtomicCmpXchg,
1217                 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1218                 OperandTraits<AtomicCmpXchgInst>::operands(this),
1219                 InsertBefore) {
1220   Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1221 }
1222
1223 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1224                                      AtomicOrdering Ordering,
1225                                      SynchronizationScope SynchScope,
1226                                      BasicBlock *InsertAtEnd)
1227   : Instruction(Cmp->getType(), AtomicCmpXchg,
1228                 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1229                 OperandTraits<AtomicCmpXchgInst>::operands(this),
1230                 InsertAtEnd) {
1231   Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1232 }
1233  
1234 //===----------------------------------------------------------------------===//
1235 //                       AtomicRMWInst Implementation
1236 //===----------------------------------------------------------------------===//
1237
1238 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1239                          AtomicOrdering Ordering,
1240                          SynchronizationScope SynchScope) {
1241   Op<0>() = Ptr;
1242   Op<1>() = Val;
1243   setOperation(Operation);
1244   setOrdering(Ordering);
1245   setSynchScope(SynchScope);
1246
1247   assert(getOperand(0) && getOperand(1) &&
1248          "All operands must be non-null!");
1249   assert(getOperand(0)->getType()->isPointerTy() &&
1250          "Ptr must have pointer type!");
1251   assert(getOperand(1)->getType() ==
1252          cast<PointerType>(getOperand(0)->getType())->getElementType()
1253          && "Ptr must be a pointer to Val type!");
1254   assert(Ordering != NotAtomic &&
1255          "AtomicRMW instructions must be atomic!");
1256 }
1257
1258 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1259                              AtomicOrdering Ordering,
1260                              SynchronizationScope SynchScope,
1261                              Instruction *InsertBefore)
1262   : Instruction(Val->getType(), AtomicRMW,
1263                 OperandTraits<AtomicRMWInst>::op_begin(this),
1264                 OperandTraits<AtomicRMWInst>::operands(this),
1265                 InsertBefore) {
1266   Init(Operation, Ptr, Val, Ordering, SynchScope);
1267 }
1268
1269 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1270                              AtomicOrdering Ordering,
1271                              SynchronizationScope SynchScope,
1272                              BasicBlock *InsertAtEnd)
1273   : Instruction(Val->getType(), AtomicRMW,
1274                 OperandTraits<AtomicRMWInst>::op_begin(this),
1275                 OperandTraits<AtomicRMWInst>::operands(this),
1276                 InsertAtEnd) {
1277   Init(Operation, Ptr, Val, Ordering, SynchScope);
1278 }
1279
1280 //===----------------------------------------------------------------------===//
1281 //                       FenceInst Implementation
1282 //===----------------------------------------------------------------------===//
1283
1284 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
1285                      SynchronizationScope SynchScope,
1286                      Instruction *InsertBefore)
1287   : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1288   setOrdering(Ordering);
1289   setSynchScope(SynchScope);
1290 }
1291
1292 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
1293                      SynchronizationScope SynchScope,
1294                      BasicBlock *InsertAtEnd)
1295   : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1296   setOrdering(Ordering);
1297   setSynchScope(SynchScope);
1298 }
1299
1300 //===----------------------------------------------------------------------===//
1301 //                       GetElementPtrInst Implementation
1302 //===----------------------------------------------------------------------===//
1303
1304 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1305                              const Twine &Name) {
1306   assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1307   OperandList[0] = Ptr;
1308   std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1309   setName(Name);
1310 }
1311
1312 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1313   : Instruction(GEPI.getType(), GetElementPtr,
1314                 OperandTraits<GetElementPtrInst>::op_end(this)
1315                 - GEPI.getNumOperands(),
1316                 GEPI.getNumOperands()) {
1317   std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1318   SubclassOptionalData = GEPI.SubclassOptionalData;
1319 }
1320
1321 /// getIndexedType - Returns the type of the element that would be accessed with
1322 /// a gep instruction with the specified parameters.
1323 ///
1324 /// The Idxs pointer should point to a continuous piece of memory containing the
1325 /// indices, either as Value* or uint64_t.
1326 ///
1327 /// A null type is returned if the indices are invalid for the specified
1328 /// pointer type.
1329 ///
1330 template <typename IndexTy>
1331 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1332   if (Ptr->isVectorTy()) {
1333     assert(IdxList.size() == 1 &&
1334       "GEP with vector pointers must have a single index");
1335     PointerType *PTy = dyn_cast<PointerType>(
1336         cast<VectorType>(Ptr)->getElementType());
1337     assert(PTy && "Gep with invalid vector pointer found");
1338     return PTy->getElementType();
1339   }
1340
1341   PointerType *PTy = dyn_cast<PointerType>(Ptr);
1342   if (!PTy) return 0;   // Type isn't a pointer type!
1343   Type *Agg = PTy->getElementType();
1344
1345   // Handle the special case of the empty set index set, which is always valid.
1346   if (IdxList.empty())
1347     return Agg;
1348
1349   // If there is at least one index, the top level type must be sized, otherwise
1350   // it cannot be 'stepped over'.
1351   if (!Agg->isSized())
1352     return 0;
1353
1354   unsigned CurIdx = 1;
1355   for (; CurIdx != IdxList.size(); ++CurIdx) {
1356     CompositeType *CT = dyn_cast<CompositeType>(Agg);
1357     if (!CT || CT->isPointerTy()) return 0;
1358     IndexTy Index = IdxList[CurIdx];
1359     if (!CT->indexValid(Index)) return 0;
1360     Agg = CT->getTypeAtIndex(Index);
1361   }
1362   return CurIdx == IdxList.size() ? Agg : 0;
1363 }
1364
1365 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1366   return getIndexedTypeInternal(Ptr, IdxList);
1367 }
1368
1369 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1370                                         ArrayRef<Constant *> IdxList) {
1371   return getIndexedTypeInternal(Ptr, IdxList);
1372 }
1373
1374 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1375   return getIndexedTypeInternal(Ptr, IdxList);
1376 }
1377
1378 unsigned GetElementPtrInst::getAddressSpace(Value *Ptr) {
1379   Type *Ty = Ptr->getType();
1380
1381   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1382     Ty = VTy->getElementType();
1383
1384   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1385     return PTy->getAddressSpace();
1386
1387   llvm_unreachable("Invalid GEP pointer type");
1388 }
1389
1390 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1391 /// zeros.  If so, the result pointer and the first operand have the same
1392 /// value, just potentially different types.
1393 bool GetElementPtrInst::hasAllZeroIndices() const {
1394   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1395     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1396       if (!CI->isZero()) return false;
1397     } else {
1398       return false;
1399     }
1400   }
1401   return true;
1402 }
1403
1404 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1405 /// constant integers.  If so, the result pointer and the first operand have
1406 /// a constant offset between them.
1407 bool GetElementPtrInst::hasAllConstantIndices() const {
1408   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1409     if (!isa<ConstantInt>(getOperand(i)))
1410       return false;
1411   }
1412   return true;
1413 }
1414
1415 void GetElementPtrInst::setIsInBounds(bool B) {
1416   cast<GEPOperator>(this)->setIsInBounds(B);
1417 }
1418
1419 bool GetElementPtrInst::isInBounds() const {
1420   return cast<GEPOperator>(this)->isInBounds();
1421 }
1422
1423 //===----------------------------------------------------------------------===//
1424 //                           ExtractElementInst Implementation
1425 //===----------------------------------------------------------------------===//
1426
1427 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1428                                        const Twine &Name,
1429                                        Instruction *InsertBef)
1430   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1431                 ExtractElement,
1432                 OperandTraits<ExtractElementInst>::op_begin(this),
1433                 2, InsertBef) {
1434   assert(isValidOperands(Val, Index) &&
1435          "Invalid extractelement instruction operands!");
1436   Op<0>() = Val;
1437   Op<1>() = Index;
1438   setName(Name);
1439 }
1440
1441 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1442                                        const Twine &Name,
1443                                        BasicBlock *InsertAE)
1444   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1445                 ExtractElement,
1446                 OperandTraits<ExtractElementInst>::op_begin(this),
1447                 2, InsertAE) {
1448   assert(isValidOperands(Val, Index) &&
1449          "Invalid extractelement instruction operands!");
1450
1451   Op<0>() = Val;
1452   Op<1>() = Index;
1453   setName(Name);
1454 }
1455
1456
1457 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1458   if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1459     return false;
1460   return true;
1461 }
1462
1463
1464 //===----------------------------------------------------------------------===//
1465 //                           InsertElementInst Implementation
1466 //===----------------------------------------------------------------------===//
1467
1468 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1469                                      const Twine &Name,
1470                                      Instruction *InsertBef)
1471   : Instruction(Vec->getType(), InsertElement,
1472                 OperandTraits<InsertElementInst>::op_begin(this),
1473                 3, InsertBef) {
1474   assert(isValidOperands(Vec, Elt, Index) &&
1475          "Invalid insertelement instruction operands!");
1476   Op<0>() = Vec;
1477   Op<1>() = Elt;
1478   Op<2>() = Index;
1479   setName(Name);
1480 }
1481
1482 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1483                                      const Twine &Name,
1484                                      BasicBlock *InsertAE)
1485   : Instruction(Vec->getType(), InsertElement,
1486                 OperandTraits<InsertElementInst>::op_begin(this),
1487                 3, InsertAE) {
1488   assert(isValidOperands(Vec, Elt, Index) &&
1489          "Invalid insertelement instruction operands!");
1490
1491   Op<0>() = Vec;
1492   Op<1>() = Elt;
1493   Op<2>() = Index;
1494   setName(Name);
1495 }
1496
1497 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
1498                                         const Value *Index) {
1499   if (!Vec->getType()->isVectorTy())
1500     return false;   // First operand of insertelement must be vector type.
1501   
1502   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1503     return false;// Second operand of insertelement must be vector element type.
1504     
1505   if (!Index->getType()->isIntegerTy(32))
1506     return false;  // Third operand of insertelement must be i32.
1507   return true;
1508 }
1509
1510
1511 //===----------------------------------------------------------------------===//
1512 //                      ShuffleVectorInst Implementation
1513 //===----------------------------------------------------------------------===//
1514
1515 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1516                                      const Twine &Name,
1517                                      Instruction *InsertBefore)
1518 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1519                 cast<VectorType>(Mask->getType())->getNumElements()),
1520               ShuffleVector,
1521               OperandTraits<ShuffleVectorInst>::op_begin(this),
1522               OperandTraits<ShuffleVectorInst>::operands(this),
1523               InsertBefore) {
1524   assert(isValidOperands(V1, V2, Mask) &&
1525          "Invalid shuffle vector instruction operands!");
1526   Op<0>() = V1;
1527   Op<1>() = V2;
1528   Op<2>() = Mask;
1529   setName(Name);
1530 }
1531
1532 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1533                                      const Twine &Name,
1534                                      BasicBlock *InsertAtEnd)
1535 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1536                 cast<VectorType>(Mask->getType())->getNumElements()),
1537               ShuffleVector,
1538               OperandTraits<ShuffleVectorInst>::op_begin(this),
1539               OperandTraits<ShuffleVectorInst>::operands(this),
1540               InsertAtEnd) {
1541   assert(isValidOperands(V1, V2, Mask) &&
1542          "Invalid shuffle vector instruction operands!");
1543
1544   Op<0>() = V1;
1545   Op<1>() = V2;
1546   Op<2>() = Mask;
1547   setName(Name);
1548 }
1549
1550 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1551                                         const Value *Mask) {
1552   // V1 and V2 must be vectors of the same type.
1553   if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1554     return false;
1555   
1556   // Mask must be vector of i32.
1557   VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1558   if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1559     return false;
1560
1561   // Check to see if Mask is valid.
1562   if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1563     return true;
1564
1565   if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1566     unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1567     for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1568       if (ConstantInt *CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1569         if (CI->uge(V1Size*2))
1570           return false;
1571       } else if (!isa<UndefValue>(MV->getOperand(i))) {
1572         return false;
1573       }
1574     }
1575     return true;
1576   }
1577   
1578   if (const ConstantDataSequential *CDS =
1579         dyn_cast<ConstantDataSequential>(Mask)) {
1580     unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1581     for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1582       if (CDS->getElementAsInteger(i) >= V1Size*2)
1583         return false;
1584     return true;
1585   }
1586   
1587   // The bitcode reader can create a place holder for a forward reference
1588   // used as the shuffle mask. When this occurs, the shuffle mask will
1589   // fall into this case and fail. To avoid this error, do this bit of
1590   // ugliness to allow such a mask pass.
1591   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1592     if (CE->getOpcode() == Instruction::UserOp1)
1593       return true;
1594
1595   return false;
1596 }
1597
1598 /// getMaskValue - Return the index from the shuffle mask for the specified
1599 /// output result.  This is either -1 if the element is undef or a number less
1600 /// than 2*numelements.
1601 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1602   assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1603   if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1604     return CDS->getElementAsInteger(i);
1605   Constant *C = Mask->getAggregateElement(i);
1606   if (isa<UndefValue>(C))
1607     return -1;
1608   return cast<ConstantInt>(C)->getZExtValue();
1609 }
1610
1611 /// getShuffleMask - Return the full mask for this instruction, where each
1612 /// element is the element number and undef's are returned as -1.
1613 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1614                                        SmallVectorImpl<int> &Result) {
1615   unsigned NumElts = Mask->getType()->getVectorNumElements();
1616   
1617   if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1618     for (unsigned i = 0; i != NumElts; ++i)
1619       Result.push_back(CDS->getElementAsInteger(i));
1620     return;
1621   }    
1622   for (unsigned i = 0; i != NumElts; ++i) {
1623     Constant *C = Mask->getAggregateElement(i);
1624     Result.push_back(isa<UndefValue>(C) ? -1 :
1625                      cast<ConstantInt>(C)->getZExtValue());
1626   }
1627 }
1628
1629
1630 //===----------------------------------------------------------------------===//
1631 //                             InsertValueInst Class
1632 //===----------------------------------------------------------------------===//
1633
1634 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 
1635                            const Twine &Name) {
1636   assert(NumOperands == 2 && "NumOperands not initialized?");
1637
1638   // There's no fundamental reason why we require at least one index
1639   // (other than weirdness with &*IdxBegin being invalid; see
1640   // getelementptr's init routine for example). But there's no
1641   // present need to support it.
1642   assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1643
1644   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1645          Val->getType() && "Inserted value must match indexed type!");
1646   Op<0>() = Agg;
1647   Op<1>() = Val;
1648
1649   Indices.append(Idxs.begin(), Idxs.end());
1650   setName(Name);
1651 }
1652
1653 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1654   : Instruction(IVI.getType(), InsertValue,
1655                 OperandTraits<InsertValueInst>::op_begin(this), 2),
1656     Indices(IVI.Indices) {
1657   Op<0>() = IVI.getOperand(0);
1658   Op<1>() = IVI.getOperand(1);
1659   SubclassOptionalData = IVI.SubclassOptionalData;
1660 }
1661
1662 //===----------------------------------------------------------------------===//
1663 //                             ExtractValueInst Class
1664 //===----------------------------------------------------------------------===//
1665
1666 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1667   assert(NumOperands == 1 && "NumOperands not initialized?");
1668
1669   // There's no fundamental reason why we require at least one index.
1670   // But there's no present need to support it.
1671   assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1672
1673   Indices.append(Idxs.begin(), Idxs.end());
1674   setName(Name);
1675 }
1676
1677 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1678   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1679     Indices(EVI.Indices) {
1680   SubclassOptionalData = EVI.SubclassOptionalData;
1681 }
1682
1683 // getIndexedType - Returns the type of the element that would be extracted
1684 // with an extractvalue instruction with the specified parameters.
1685 //
1686 // A null type is returned if the indices are invalid for the specified
1687 // pointer type.
1688 //
1689 Type *ExtractValueInst::getIndexedType(Type *Agg,
1690                                        ArrayRef<unsigned> Idxs) {
1691   for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1692     unsigned Index = Idxs[CurIdx];
1693     // We can't use CompositeType::indexValid(Index) here.
1694     // indexValid() always returns true for arrays because getelementptr allows
1695     // out-of-bounds indices. Since we don't allow those for extractvalue and
1696     // insertvalue we need to check array indexing manually.
1697     // Since the only other types we can index into are struct types it's just
1698     // as easy to check those manually as well.
1699     if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1700       if (Index >= AT->getNumElements())
1701         return 0;
1702     } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1703       if (Index >= ST->getNumElements())
1704         return 0;
1705     } else {
1706       // Not a valid type to index into.
1707       return 0;
1708     }
1709
1710     Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1711   }
1712   return const_cast<Type*>(Agg);
1713 }
1714
1715 //===----------------------------------------------------------------------===//
1716 //                             BinaryOperator Class
1717 //===----------------------------------------------------------------------===//
1718
1719 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1720                                Type *Ty, const Twine &Name,
1721                                Instruction *InsertBefore)
1722   : Instruction(Ty, iType,
1723                 OperandTraits<BinaryOperator>::op_begin(this),
1724                 OperandTraits<BinaryOperator>::operands(this),
1725                 InsertBefore) {
1726   Op<0>() = S1;
1727   Op<1>() = S2;
1728   init(iType);
1729   setName(Name);
1730 }
1731
1732 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
1733                                Type *Ty, const Twine &Name,
1734                                BasicBlock *InsertAtEnd)
1735   : Instruction(Ty, iType,
1736                 OperandTraits<BinaryOperator>::op_begin(this),
1737                 OperandTraits<BinaryOperator>::operands(this),
1738                 InsertAtEnd) {
1739   Op<0>() = S1;
1740   Op<1>() = S2;
1741   init(iType);
1742   setName(Name);
1743 }
1744
1745
1746 void BinaryOperator::init(BinaryOps iType) {
1747   Value *LHS = getOperand(0), *RHS = getOperand(1);
1748   (void)LHS; (void)RHS; // Silence warnings.
1749   assert(LHS->getType() == RHS->getType() &&
1750          "Binary operator operand types must match!");
1751 #ifndef NDEBUG
1752   switch (iType) {
1753   case Add: case Sub:
1754   case Mul:
1755     assert(getType() == LHS->getType() &&
1756            "Arithmetic operation should return same type as operands!");
1757     assert(getType()->isIntOrIntVectorTy() &&
1758            "Tried to create an integer operation on a non-integer type!");
1759     break;
1760   case FAdd: case FSub:
1761   case FMul:
1762     assert(getType() == LHS->getType() &&
1763            "Arithmetic operation should return same type as operands!");
1764     assert(getType()->isFPOrFPVectorTy() &&
1765            "Tried to create a floating-point operation on a "
1766            "non-floating-point type!");
1767     break;
1768   case UDiv: 
1769   case SDiv: 
1770     assert(getType() == LHS->getType() &&
1771            "Arithmetic operation should return same type as operands!");
1772     assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 
1773             cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1774            "Incorrect operand type (not integer) for S/UDIV");
1775     break;
1776   case FDiv:
1777     assert(getType() == LHS->getType() &&
1778            "Arithmetic operation should return same type as operands!");
1779     assert(getType()->isFPOrFPVectorTy() &&
1780            "Incorrect operand type (not floating point) for FDIV");
1781     break;
1782   case URem: 
1783   case SRem: 
1784     assert(getType() == LHS->getType() &&
1785            "Arithmetic operation should return same type as operands!");
1786     assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 
1787             cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1788            "Incorrect operand type (not integer) for S/UREM");
1789     break;
1790   case FRem:
1791     assert(getType() == LHS->getType() &&
1792            "Arithmetic operation should return same type as operands!");
1793     assert(getType()->isFPOrFPVectorTy() &&
1794            "Incorrect operand type (not floating point) for FREM");
1795     break;
1796   case Shl:
1797   case LShr:
1798   case AShr:
1799     assert(getType() == LHS->getType() &&
1800            "Shift operation should return same type as operands!");
1801     assert((getType()->isIntegerTy() ||
1802             (getType()->isVectorTy() && 
1803              cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1804            "Tried to create a shift operation on a non-integral type!");
1805     break;
1806   case And: case Or:
1807   case Xor:
1808     assert(getType() == LHS->getType() &&
1809            "Logical operation should return same type as operands!");
1810     assert((getType()->isIntegerTy() ||
1811             (getType()->isVectorTy() && 
1812              cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1813            "Tried to create a logical operation on a non-integral type!");
1814     break;
1815   default:
1816     break;
1817   }
1818 #endif
1819 }
1820
1821 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1822                                        const Twine &Name,
1823                                        Instruction *InsertBefore) {
1824   assert(S1->getType() == S2->getType() &&
1825          "Cannot create binary operator with two operands of differing type!");
1826   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1827 }
1828
1829 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1830                                        const Twine &Name,
1831                                        BasicBlock *InsertAtEnd) {
1832   BinaryOperator *Res = Create(Op, S1, S2, Name);
1833   InsertAtEnd->getInstList().push_back(Res);
1834   return Res;
1835 }
1836
1837 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1838                                           Instruction *InsertBefore) {
1839   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1840   return new BinaryOperator(Instruction::Sub,
1841                             zero, Op,
1842                             Op->getType(), Name, InsertBefore);
1843 }
1844
1845 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1846                                           BasicBlock *InsertAtEnd) {
1847   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1848   return new BinaryOperator(Instruction::Sub,
1849                             zero, Op,
1850                             Op->getType(), Name, InsertAtEnd);
1851 }
1852
1853 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1854                                              Instruction *InsertBefore) {
1855   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1856   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1857 }
1858
1859 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1860                                              BasicBlock *InsertAtEnd) {
1861   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1862   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1863 }
1864
1865 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1866                                              Instruction *InsertBefore) {
1867   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1868   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1869 }
1870
1871 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1872                                              BasicBlock *InsertAtEnd) {
1873   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1874   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1875 }
1876
1877 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1878                                            Instruction *InsertBefore) {
1879   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1880   return new BinaryOperator(Instruction::FSub, zero, Op,
1881                             Op->getType(), Name, InsertBefore);
1882 }
1883
1884 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1885                                            BasicBlock *InsertAtEnd) {
1886   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1887   return new BinaryOperator(Instruction::FSub, zero, Op,
1888                             Op->getType(), Name, InsertAtEnd);
1889 }
1890
1891 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1892                                           Instruction *InsertBefore) {
1893   Constant *C = Constant::getAllOnesValue(Op->getType());
1894   return new BinaryOperator(Instruction::Xor, Op, C,
1895                             Op->getType(), Name, InsertBefore);
1896 }
1897
1898 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1899                                           BasicBlock *InsertAtEnd) {
1900   Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
1901   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1902                             Op->getType(), Name, InsertAtEnd);
1903 }
1904
1905
1906 // isConstantAllOnes - Helper function for several functions below
1907 static inline bool isConstantAllOnes(const Value *V) {
1908   if (const Constant *C = dyn_cast<Constant>(V))
1909     return C->isAllOnesValue();
1910   return false;
1911 }
1912
1913 bool BinaryOperator::isNeg(const Value *V) {
1914   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1915     if (Bop->getOpcode() == Instruction::Sub)
1916       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1917         return C->isNegativeZeroValue();
1918   return false;
1919 }
1920
1921 bool BinaryOperator::isFNeg(const Value *V) {
1922   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1923     if (Bop->getOpcode() == Instruction::FSub)
1924       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1925         return C->isNegativeZeroValue();
1926   return false;
1927 }
1928
1929 bool BinaryOperator::isNot(const Value *V) {
1930   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1931     return (Bop->getOpcode() == Instruction::Xor &&
1932             (isConstantAllOnes(Bop->getOperand(1)) ||
1933              isConstantAllOnes(Bop->getOperand(0))));
1934   return false;
1935 }
1936
1937 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1938   return cast<BinaryOperator>(BinOp)->getOperand(1);
1939 }
1940
1941 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1942   return getNegArgument(const_cast<Value*>(BinOp));
1943 }
1944
1945 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1946   return cast<BinaryOperator>(BinOp)->getOperand(1);
1947 }
1948
1949 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1950   return getFNegArgument(const_cast<Value*>(BinOp));
1951 }
1952
1953 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1954   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1955   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1956   Value *Op0 = BO->getOperand(0);
1957   Value *Op1 = BO->getOperand(1);
1958   if (isConstantAllOnes(Op0)) return Op1;
1959
1960   assert(isConstantAllOnes(Op1));
1961   return Op0;
1962 }
1963
1964 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1965   return getNotArgument(const_cast<Value*>(BinOp));
1966 }
1967
1968
1969 // swapOperands - Exchange the two operands to this instruction.  This
1970 // instruction is safe to use on any binary instruction and does not
1971 // modify the semantics of the instruction.  If the instruction is
1972 // order dependent (SetLT f.e.) the opcode is changed.
1973 //
1974 bool BinaryOperator::swapOperands() {
1975   if (!isCommutative())
1976     return true; // Can't commute operands
1977   Op<0>().swap(Op<1>());
1978   return false;
1979 }
1980
1981 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1982   cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1983 }
1984
1985 void BinaryOperator::setHasNoSignedWrap(bool b) {
1986   cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1987 }
1988
1989 void BinaryOperator::setIsExact(bool b) {
1990   cast<PossiblyExactOperator>(this)->setIsExact(b);
1991 }
1992
1993 bool BinaryOperator::hasNoUnsignedWrap() const {
1994   return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1995 }
1996
1997 bool BinaryOperator::hasNoSignedWrap() const {
1998   return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1999 }
2000
2001 bool BinaryOperator::isExact() const {
2002   return cast<PossiblyExactOperator>(this)->isExact();
2003 }
2004
2005 //===----------------------------------------------------------------------===//
2006 //                                CastInst Class
2007 //===----------------------------------------------------------------------===//
2008
2009 void CastInst::anchor() {}
2010
2011 // Just determine if this cast only deals with integral->integral conversion.
2012 bool CastInst::isIntegerCast() const {
2013   switch (getOpcode()) {
2014     default: return false;
2015     case Instruction::ZExt:
2016     case Instruction::SExt:
2017     case Instruction::Trunc:
2018       return true;
2019     case Instruction::BitCast:
2020       return getOperand(0)->getType()->isIntegerTy() &&
2021         getType()->isIntegerTy();
2022   }
2023 }
2024
2025 bool CastInst::isLosslessCast() const {
2026   // Only BitCast can be lossless, exit fast if we're not BitCast
2027   if (getOpcode() != Instruction::BitCast)
2028     return false;
2029
2030   // Identity cast is always lossless
2031   Type* SrcTy = getOperand(0)->getType();
2032   Type* DstTy = getType();
2033   if (SrcTy == DstTy)
2034     return true;
2035   
2036   // Pointer to pointer is always lossless.
2037   if (SrcTy->isPointerTy())
2038     return DstTy->isPointerTy();
2039   return false;  // Other types have no identity values
2040 }
2041
2042 /// This function determines if the CastInst does not require any bits to be
2043 /// changed in order to effect the cast. Essentially, it identifies cases where
2044 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
2045 /// example, the following are all no-op casts:
2046 /// # bitcast i32* %x to i8*
2047 /// # bitcast <2 x i32> %x to <4 x i16> 
2048 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
2049 /// @brief Determine if the described cast is a no-op.
2050 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2051                           Type *SrcTy,
2052                           Type *DestTy,
2053                           Type *IntPtrTy) {
2054   switch (Opcode) {
2055     default: llvm_unreachable("Invalid CastOp");
2056     case Instruction::Trunc:
2057     case Instruction::ZExt:
2058     case Instruction::SExt: 
2059     case Instruction::FPTrunc:
2060     case Instruction::FPExt:
2061     case Instruction::UIToFP:
2062     case Instruction::SIToFP:
2063     case Instruction::FPToUI:
2064     case Instruction::FPToSI:
2065       return false; // These always modify bits
2066     case Instruction::BitCast:
2067       return true;  // BitCast never modifies bits.
2068     case Instruction::PtrToInt:
2069       return IntPtrTy->getScalarSizeInBits() ==
2070              DestTy->getScalarSizeInBits();
2071     case Instruction::IntToPtr:
2072       return IntPtrTy->getScalarSizeInBits() ==
2073              SrcTy->getScalarSizeInBits();
2074   }
2075 }
2076
2077 /// @brief Determine if a cast is a no-op.
2078 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2079   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2080 }
2081
2082 /// This function determines if a pair of casts can be eliminated and what 
2083 /// opcode should be used in the elimination. This assumes that there are two 
2084 /// instructions like this:
2085 /// *  %F = firstOpcode SrcTy %x to MidTy
2086 /// *  %S = secondOpcode MidTy %F to DstTy
2087 /// The function returns a resultOpcode so these two casts can be replaced with:
2088 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
2089 /// If no such cast is permited, the function returns 0.
2090 unsigned CastInst::isEliminableCastPair(
2091   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2092   Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy) {
2093   // Define the 144 possibilities for these two cast instructions. The values
2094   // in this matrix determine what to do in a given situation and select the
2095   // case in the switch below.  The rows correspond to firstOp, the columns 
2096   // correspond to secondOp.  In looking at the table below, keep in  mind
2097   // the following cast properties:
2098   //
2099   //          Size Compare       Source               Destination
2100   // Operator  Src ? Size   Type       Sign         Type       Sign
2101   // -------- ------------ -------------------   ---------------------
2102   // TRUNC         >       Integer      Any        Integral     Any
2103   // ZEXT          <       Integral   Unsigned     Integer      Any
2104   // SEXT          <       Integral    Signed      Integer      Any
2105   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
2106   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed 
2107   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a   
2108   // SITOFP       n/a      Integral    Signed      FloatPt      n/a   
2109   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a   
2110   // FPEXT         <       FloatPt      n/a        FloatPt      n/a   
2111   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
2112   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
2113   // BITCAST       =       FirstClass   n/a       FirstClass    n/a   
2114   //
2115   // NOTE: some transforms are safe, but we consider them to be non-profitable.
2116   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2117   // into "fptoui double to i64", but this loses information about the range
2118   // of the produced value (we no longer know the top-part is all zeros). 
2119   // Further this conversion is often much more expensive for typical hardware,
2120   // and causes issues when building libgcc.  We disallow fptosi+sext for the 
2121   // same reason.
2122   const unsigned numCastOps = 
2123     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2124   static const uint8_t CastResults[numCastOps][numCastOps] = {
2125     // T        F  F  U  S  F  F  P  I  B   -+
2126     // R  Z  S  P  P  I  I  T  P  2  N  T    |
2127     // U  E  E  2  2  2  2  R  E  I  T  C    +- secondOp
2128     // N  X  X  U  S  F  F  N  X  N  2  V    |
2129     // C  T  T  I  I  P  P  C  T  T  P  T   -+
2130     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc      -+
2131     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt        |
2132     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt        |
2133     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI      |
2134     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI      |
2135     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP      +- firstOp
2136     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP      |
2137     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc     |
2138     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt       |
2139     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt    |
2140     { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr    |
2141     {  5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast    -+
2142   };
2143   
2144   // If either of the casts are a bitcast from scalar to vector, disallow the
2145   // merging. However, bitcast of A->B->A are allowed.
2146   bool isFirstBitcast  = (firstOp == Instruction::BitCast);
2147   bool isSecondBitcast = (secondOp == Instruction::BitCast);
2148   bool chainedBitcast  = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2149
2150   // Check if any of the bitcasts convert scalars<->vectors.
2151   if ((isFirstBitcast  && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2152       (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2153     // Unless we are bitcasing to the original type, disallow optimizations.
2154     if (!chainedBitcast) return 0;
2155
2156   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2157                             [secondOp-Instruction::CastOpsBegin];
2158   switch (ElimCase) {
2159     case 0: 
2160       // categorically disallowed
2161       return 0;
2162     case 1: 
2163       // allowed, use first cast's opcode
2164       return firstOp;
2165     case 2: 
2166       // allowed, use second cast's opcode
2167       return secondOp;
2168     case 3: 
2169       // no-op cast in second op implies firstOp as long as the DestTy 
2170       // is integer and we are not converting between a vector and a
2171       // non vector type.
2172       if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2173         return firstOp;
2174       return 0;
2175     case 4:
2176       // no-op cast in second op implies firstOp as long as the DestTy
2177       // is floating point.
2178       if (DstTy->isFloatingPointTy())
2179         return firstOp;
2180       return 0;
2181     case 5: 
2182       // no-op cast in first op implies secondOp as long as the SrcTy
2183       // is an integer.
2184       if (SrcTy->isIntegerTy())
2185         return secondOp;
2186       return 0;
2187     case 6:
2188       // no-op cast in first op implies secondOp as long as the SrcTy
2189       // is a floating point.
2190       if (SrcTy->isFloatingPointTy())
2191         return secondOp;
2192       return 0;
2193     case 7: { 
2194       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2195       if (!IntPtrTy)
2196         return 0;
2197       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2198       unsigned MidSize = MidTy->getScalarSizeInBits();
2199       if (MidSize >= PtrSize)
2200         return Instruction::BitCast;
2201       return 0;
2202     }
2203     case 8: {
2204       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
2205       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
2206       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
2207       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2208       unsigned DstSize = DstTy->getScalarSizeInBits();
2209       if (SrcSize == DstSize)
2210         return Instruction::BitCast;
2211       else if (SrcSize < DstSize)
2212         return firstOp;
2213       return secondOp;
2214     }
2215     case 9: // zext, sext -> zext, because sext can't sign extend after zext
2216       return Instruction::ZExt;
2217     case 10:
2218       // fpext followed by ftrunc is allowed if the bit size returned to is
2219       // the same as the original, in which case its just a bitcast
2220       if (SrcTy == DstTy)
2221         return Instruction::BitCast;
2222       return 0; // If the types are not the same we can't eliminate it.
2223     case 11:
2224       // bitcast followed by ptrtoint is allowed as long as the bitcast
2225       // is a pointer to pointer cast.
2226       if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2227         return secondOp;
2228       return 0;
2229     case 12:
2230       // inttoptr, bitcast -> intptr  if bitcast is a ptr to ptr cast
2231       if (MidTy->isPointerTy() && DstTy->isPointerTy())
2232         return firstOp;
2233       return 0;
2234     case 13: {
2235       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2236       if (!IntPtrTy)
2237         return 0;
2238       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2239       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2240       unsigned DstSize = DstTy->getScalarSizeInBits();
2241       if (SrcSize <= PtrSize && SrcSize == DstSize)
2242         return Instruction::BitCast;
2243       return 0;
2244     }
2245     case 99: 
2246       // cast combination can't happen (error in input). This is for all cases
2247       // where the MidTy is not the same for the two cast instructions.
2248       llvm_unreachable("Invalid Cast Combination");
2249     default:
2250       llvm_unreachable("Error in CastResults table!!!");
2251   }
2252 }
2253
2254 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 
2255   const Twine &Name, Instruction *InsertBefore) {
2256   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2257   // Construct and return the appropriate CastInst subclass
2258   switch (op) {
2259     case Trunc:    return new TruncInst    (S, Ty, Name, InsertBefore);
2260     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertBefore);
2261     case SExt:     return new SExtInst     (S, Ty, Name, InsertBefore);
2262     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertBefore);
2263     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertBefore);
2264     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertBefore);
2265     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertBefore);
2266     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertBefore);
2267     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertBefore);
2268     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2269     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2270     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertBefore);
2271     default: llvm_unreachable("Invalid opcode provided");
2272   }
2273 }
2274
2275 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2276   const Twine &Name, BasicBlock *InsertAtEnd) {
2277   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2278   // Construct and return the appropriate CastInst subclass
2279   switch (op) {
2280     case Trunc:    return new TruncInst    (S, Ty, Name, InsertAtEnd);
2281     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertAtEnd);
2282     case SExt:     return new SExtInst     (S, Ty, Name, InsertAtEnd);
2283     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertAtEnd);
2284     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertAtEnd);
2285     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertAtEnd);
2286     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertAtEnd);
2287     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertAtEnd);
2288     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertAtEnd);
2289     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2290     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2291     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertAtEnd);
2292     default: llvm_unreachable("Invalid opcode provided");
2293   }
2294 }
2295
2296 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
2297                                         const Twine &Name,
2298                                         Instruction *InsertBefore) {
2299   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2300     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2301   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2302 }
2303
2304 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
2305                                         const Twine &Name,
2306                                         BasicBlock *InsertAtEnd) {
2307   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2308     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2309   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2310 }
2311
2312 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
2313                                         const Twine &Name,
2314                                         Instruction *InsertBefore) {
2315   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2316     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2317   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2318 }
2319
2320 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
2321                                         const Twine &Name,
2322                                         BasicBlock *InsertAtEnd) {
2323   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2324     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2325   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2326 }
2327
2328 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2329                                          const Twine &Name,
2330                                          Instruction *InsertBefore) {
2331   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2332     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2333   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2334 }
2335
2336 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2337                                          const Twine &Name, 
2338                                          BasicBlock *InsertAtEnd) {
2339   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2340     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2341   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2342 }
2343
2344 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2345                                       const Twine &Name,
2346                                       BasicBlock *InsertAtEnd) {
2347   assert(S->getType()->isPointerTy() && "Invalid cast");
2348   assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2349          "Invalid cast");
2350
2351   if (Ty->isIntegerTy())
2352     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2353   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2354 }
2355
2356 /// @brief Create a BitCast or a PtrToInt cast instruction
2357 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 
2358                                       const Twine &Name, 
2359                                       Instruction *InsertBefore) {
2360   assert(S->getType()->isPointerTy() && "Invalid cast");
2361   assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2362          "Invalid cast");
2363
2364   if (Ty->isIntegerTy())
2365     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2366   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2367 }
2368
2369 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 
2370                                       bool isSigned, const Twine &Name,
2371                                       Instruction *InsertBefore) {
2372   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2373          "Invalid integer cast");
2374   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2375   unsigned DstBits = Ty->getScalarSizeInBits();
2376   Instruction::CastOps opcode =
2377     (SrcBits == DstBits ? Instruction::BitCast :
2378      (SrcBits > DstBits ? Instruction::Trunc :
2379       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2380   return Create(opcode, C, Ty, Name, InsertBefore);
2381 }
2382
2383 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 
2384                                       bool isSigned, const Twine &Name,
2385                                       BasicBlock *InsertAtEnd) {
2386   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2387          "Invalid cast");
2388   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2389   unsigned DstBits = Ty->getScalarSizeInBits();
2390   Instruction::CastOps opcode =
2391     (SrcBits == DstBits ? Instruction::BitCast :
2392      (SrcBits > DstBits ? Instruction::Trunc :
2393       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2394   return Create(opcode, C, Ty, Name, InsertAtEnd);
2395 }
2396
2397 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
2398                                  const Twine &Name, 
2399                                  Instruction *InsertBefore) {
2400   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2401          "Invalid cast");
2402   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2403   unsigned DstBits = Ty->getScalarSizeInBits();
2404   Instruction::CastOps opcode =
2405     (SrcBits == DstBits ? Instruction::BitCast :
2406      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2407   return Create(opcode, C, Ty, Name, InsertBefore);
2408 }
2409
2410 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
2411                                  const Twine &Name, 
2412                                  BasicBlock *InsertAtEnd) {
2413   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2414          "Invalid cast");
2415   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2416   unsigned DstBits = Ty->getScalarSizeInBits();
2417   Instruction::CastOps opcode =
2418     (SrcBits == DstBits ? Instruction::BitCast :
2419      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2420   return Create(opcode, C, Ty, Name, InsertAtEnd);
2421 }
2422
2423 // Check whether it is valid to call getCastOpcode for these types.
2424 // This routine must be kept in sync with getCastOpcode.
2425 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2426   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2427     return false;
2428
2429   if (SrcTy == DestTy)
2430     return true;
2431
2432   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2433     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2434       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2435         // An element by element cast.  Valid if casting the elements is valid.
2436         SrcTy = SrcVecTy->getElementType();
2437         DestTy = DestVecTy->getElementType();
2438       }
2439
2440   // Get the bit sizes, we'll need these
2441   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2442   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2443
2444   // Run through the possibilities ...
2445   if (DestTy->isIntegerTy()) {               // Casting to integral
2446     if (SrcTy->isIntegerTy()) {                // Casting from integral
2447         return true;
2448     } else if (SrcTy->isFloatingPointTy()) {   // Casting from floating pt
2449       return true;
2450     } else if (SrcTy->isVectorTy()) {          // Casting from vector
2451       return DestBits == SrcBits;
2452     } else {                                   // Casting from something else
2453       return SrcTy->isPointerTy();
2454     }
2455   } else if (DestTy->isFloatingPointTy()) {  // Casting to floating pt
2456     if (SrcTy->isIntegerTy()) {                // Casting from integral
2457       return true;
2458     } else if (SrcTy->isFloatingPointTy()) {   // Casting from floating pt
2459       return true;
2460     } else if (SrcTy->isVectorTy()) {          // Casting from vector
2461       return DestBits == SrcBits;
2462     } else {                                   // Casting from something else
2463       return false;
2464     }
2465   } else if (DestTy->isVectorTy()) {         // Casting to vector
2466     return DestBits == SrcBits;
2467   } else if (DestTy->isPointerTy()) {        // Casting to pointer
2468     if (SrcTy->isPointerTy()) {                // Casting from pointer
2469       return true;
2470     } else if (SrcTy->isIntegerTy()) {         // Casting from integral
2471       return true;
2472     } else {                                   // Casting from something else
2473       return false;
2474     }
2475   } else if (DestTy->isX86_MMXTy()) {
2476     if (SrcTy->isVectorTy()) {
2477       return DestBits == SrcBits;       // 64-bit vector to MMX
2478     } else {
2479       return false;
2480     }
2481   } else {                                   // Casting to something else
2482     return false;
2483   }
2484 }
2485
2486 // Provide a way to get a "cast" where the cast opcode is inferred from the 
2487 // types and size of the operand. This, basically, is a parallel of the 
2488 // logic in the castIsValid function below.  This axiom should hold:
2489 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2490 // should not assert in castIsValid. In other words, this produces a "correct"
2491 // casting opcode for the arguments passed to it.
2492 // This routine must be kept in sync with isCastable.
2493 Instruction::CastOps
2494 CastInst::getCastOpcode(
2495   const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2496   Type *SrcTy = Src->getType();
2497
2498   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2499          "Only first class types are castable!");
2500
2501   if (SrcTy == DestTy)
2502     return BitCast;
2503
2504   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2505     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2506       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2507         // An element by element cast.  Find the appropriate opcode based on the
2508         // element types.
2509         SrcTy = SrcVecTy->getElementType();
2510         DestTy = DestVecTy->getElementType();
2511       }
2512
2513   // Get the bit sizes, we'll need these
2514   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2515   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2516
2517   // Run through the possibilities ...
2518   if (DestTy->isIntegerTy()) {                      // Casting to integral
2519     if (SrcTy->isIntegerTy()) {                     // Casting from integral
2520       if (DestBits < SrcBits)
2521         return Trunc;                               // int -> smaller int
2522       else if (DestBits > SrcBits) {                // its an extension
2523         if (SrcIsSigned)
2524           return SExt;                              // signed -> SEXT
2525         else
2526           return ZExt;                              // unsigned -> ZEXT
2527       } else {
2528         return BitCast;                             // Same size, No-op cast
2529       }
2530     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
2531       if (DestIsSigned) 
2532         return FPToSI;                              // FP -> sint
2533       else
2534         return FPToUI;                              // FP -> uint 
2535     } else if (SrcTy->isVectorTy()) {
2536       assert(DestBits == SrcBits &&
2537              "Casting vector to integer of different width");
2538       return BitCast;                             // Same size, no-op cast
2539     } else {
2540       assert(SrcTy->isPointerTy() &&
2541              "Casting from a value that is not first-class type");
2542       return PtrToInt;                              // ptr -> int
2543     }
2544   } else if (DestTy->isFloatingPointTy()) {         // Casting to floating pt
2545     if (SrcTy->isIntegerTy()) {                     // Casting from integral
2546       if (SrcIsSigned)
2547         return SIToFP;                              // sint -> FP
2548       else
2549         return UIToFP;                              // uint -> FP
2550     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
2551       if (DestBits < SrcBits) {
2552         return FPTrunc;                             // FP -> smaller FP
2553       } else if (DestBits > SrcBits) {
2554         return FPExt;                               // FP -> larger FP
2555       } else  {
2556         return BitCast;                             // same size, no-op cast
2557       }
2558     } else if (SrcTy->isVectorTy()) {
2559       assert(DestBits == SrcBits &&
2560              "Casting vector to floating point of different width");
2561       return BitCast;                             // same size, no-op cast
2562     }
2563     llvm_unreachable("Casting pointer or non-first class to float");
2564   } else if (DestTy->isVectorTy()) {
2565     assert(DestBits == SrcBits &&
2566            "Illegal cast to vector (wrong type or size)");
2567     return BitCast;
2568   } else if (DestTy->isPointerTy()) {
2569     if (SrcTy->isPointerTy()) {
2570       return BitCast;                               // ptr -> ptr
2571     } else if (SrcTy->isIntegerTy()) {
2572       return IntToPtr;                              // int -> ptr
2573     }
2574     llvm_unreachable("Casting pointer to other than pointer or int");
2575   } else if (DestTy->isX86_MMXTy()) {
2576     if (SrcTy->isVectorTy()) {
2577       assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2578       return BitCast;                               // 64-bit vector to MMX
2579     }
2580     llvm_unreachable("Illegal cast to X86_MMX");
2581   }
2582   llvm_unreachable("Casting to type that is not first-class");
2583 }
2584
2585 //===----------------------------------------------------------------------===//
2586 //                    CastInst SubClass Constructors
2587 //===----------------------------------------------------------------------===//
2588
2589 /// Check that the construction parameters for a CastInst are correct. This
2590 /// could be broken out into the separate constructors but it is useful to have
2591 /// it in one place and to eliminate the redundant code for getting the sizes
2592 /// of the types involved.
2593 bool 
2594 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2595
2596   // Check for type sanity on the arguments
2597   Type *SrcTy = S->getType();
2598   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2599       SrcTy->isAggregateType() || DstTy->isAggregateType())
2600     return false;
2601
2602   // Get the size of the types in bits, we'll need this later
2603   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2604   unsigned DstBitSize = DstTy->getScalarSizeInBits();
2605
2606   // If these are vector types, get the lengths of the vectors (using zero for
2607   // scalar types means that checking that vector lengths match also checks that
2608   // scalars are not being converted to vectors or vectors to scalars).
2609   unsigned SrcLength = SrcTy->isVectorTy() ?
2610     cast<VectorType>(SrcTy)->getNumElements() : 0;
2611   unsigned DstLength = DstTy->isVectorTy() ?
2612     cast<VectorType>(DstTy)->getNumElements() : 0;
2613
2614   // Switch on the opcode provided
2615   switch (op) {
2616   default: return false; // This is an input error
2617   case Instruction::Trunc:
2618     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2619       SrcLength == DstLength && SrcBitSize > DstBitSize;
2620   case Instruction::ZExt:
2621     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2622       SrcLength == DstLength && SrcBitSize < DstBitSize;
2623   case Instruction::SExt: 
2624     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2625       SrcLength == DstLength && SrcBitSize < DstBitSize;
2626   case Instruction::FPTrunc:
2627     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2628       SrcLength == DstLength && SrcBitSize > DstBitSize;
2629   case Instruction::FPExt:
2630     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2631       SrcLength == DstLength && SrcBitSize < DstBitSize;
2632   case Instruction::UIToFP:
2633   case Instruction::SIToFP:
2634     return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2635       SrcLength == DstLength;
2636   case Instruction::FPToUI:
2637   case Instruction::FPToSI:
2638     return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2639       SrcLength == DstLength;
2640   case Instruction::PtrToInt:
2641     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2642       return false;
2643     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2644       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2645         return false;
2646     return SrcTy->getScalarType()->isPointerTy() &&
2647            DstTy->getScalarType()->isIntegerTy();
2648   case Instruction::IntToPtr:
2649     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2650       return false;
2651     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2652       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2653         return false;
2654     return SrcTy->getScalarType()->isIntegerTy() &&
2655            DstTy->getScalarType()->isPointerTy();
2656   case Instruction::BitCast:
2657     // BitCast implies a no-op cast of type only. No bits change.
2658     // However, you can't cast pointers to anything but pointers.
2659     if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2660       return false;
2661
2662     // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2663     // these cases, the cast is okay if the source and destination bit widths
2664     // are identical.
2665     return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2666   }
2667 }
2668
2669 TruncInst::TruncInst(
2670   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2671 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2672   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2673 }
2674
2675 TruncInst::TruncInst(
2676   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2677 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
2678   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2679 }
2680
2681 ZExtInst::ZExtInst(
2682   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2683 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
2684   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2685 }
2686
2687 ZExtInst::ZExtInst(
2688   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2689 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
2690   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2691 }
2692 SExtInst::SExtInst(
2693   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2694 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
2695   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2696 }
2697
2698 SExtInst::SExtInst(
2699   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2700 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
2701   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2702 }
2703
2704 FPTruncInst::FPTruncInst(
2705   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2706 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
2707   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2708 }
2709
2710 FPTruncInst::FPTruncInst(
2711   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2712 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
2713   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2714 }
2715
2716 FPExtInst::FPExtInst(
2717   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2718 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
2719   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2720 }
2721
2722 FPExtInst::FPExtInst(
2723   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2724 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
2725   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2726 }
2727
2728 UIToFPInst::UIToFPInst(
2729   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2730 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
2731   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2732 }
2733
2734 UIToFPInst::UIToFPInst(
2735   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2736 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
2737   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2738 }
2739
2740 SIToFPInst::SIToFPInst(
2741   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2742 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
2743   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2744 }
2745
2746 SIToFPInst::SIToFPInst(
2747   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2748 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
2749   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2750 }
2751
2752 FPToUIInst::FPToUIInst(
2753   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2754 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
2755   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2756 }
2757
2758 FPToUIInst::FPToUIInst(
2759   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2760 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
2761   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2762 }
2763
2764 FPToSIInst::FPToSIInst(
2765   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2766 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
2767   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2768 }
2769
2770 FPToSIInst::FPToSIInst(
2771   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2772 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
2773   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2774 }
2775
2776 PtrToIntInst::PtrToIntInst(
2777   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2778 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
2779   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2780 }
2781
2782 PtrToIntInst::PtrToIntInst(
2783   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2784 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
2785   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2786 }
2787
2788 IntToPtrInst::IntToPtrInst(
2789   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2790 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
2791   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2792 }
2793
2794 IntToPtrInst::IntToPtrInst(
2795   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2796 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
2797   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2798 }
2799
2800 BitCastInst::BitCastInst(
2801   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2802 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
2803   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2804 }
2805
2806 BitCastInst::BitCastInst(
2807   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2808 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
2809   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2810 }
2811
2812 //===----------------------------------------------------------------------===//
2813 //                               CmpInst Classes
2814 //===----------------------------------------------------------------------===//
2815
2816 void CmpInst::Anchor() const {}
2817
2818 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2819                  Value *LHS, Value *RHS, const Twine &Name,
2820                  Instruction *InsertBefore)
2821   : Instruction(ty, op,
2822                 OperandTraits<CmpInst>::op_begin(this),
2823                 OperandTraits<CmpInst>::operands(this),
2824                 InsertBefore) {
2825     Op<0>() = LHS;
2826     Op<1>() = RHS;
2827   setPredicate((Predicate)predicate);
2828   setName(Name);
2829 }
2830
2831 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2832                  Value *LHS, Value *RHS, const Twine &Name,
2833                  BasicBlock *InsertAtEnd)
2834   : Instruction(ty, op,
2835                 OperandTraits<CmpInst>::op_begin(this),
2836                 OperandTraits<CmpInst>::operands(this),
2837                 InsertAtEnd) {
2838   Op<0>() = LHS;
2839   Op<1>() = RHS;
2840   setPredicate((Predicate)predicate);
2841   setName(Name);
2842 }
2843
2844 CmpInst *
2845 CmpInst::Create(OtherOps Op, unsigned short predicate,
2846                 Value *S1, Value *S2, 
2847                 const Twine &Name, Instruction *InsertBefore) {
2848   if (Op == Instruction::ICmp) {
2849     if (InsertBefore)
2850       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2851                           S1, S2, Name);
2852     else
2853       return new ICmpInst(CmpInst::Predicate(predicate),
2854                           S1, S2, Name);
2855   }
2856   
2857   if (InsertBefore)
2858     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2859                         S1, S2, Name);
2860   else
2861     return new FCmpInst(CmpInst::Predicate(predicate),
2862                         S1, S2, Name);
2863 }
2864
2865 CmpInst *
2866 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
2867                 const Twine &Name, BasicBlock *InsertAtEnd) {
2868   if (Op == Instruction::ICmp) {
2869     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2870                         S1, S2, Name);
2871   }
2872   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2873                       S1, S2, Name);
2874 }
2875
2876 void CmpInst::swapOperands() {
2877   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2878     IC->swapOperands();
2879   else
2880     cast<FCmpInst>(this)->swapOperands();
2881 }
2882
2883 bool CmpInst::isCommutative() const {
2884   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2885     return IC->isCommutative();
2886   return cast<FCmpInst>(this)->isCommutative();
2887 }
2888
2889 bool CmpInst::isEquality() const {
2890   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2891     return IC->isEquality();
2892   return cast<FCmpInst>(this)->isEquality();
2893 }
2894
2895
2896 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2897   switch (pred) {
2898     default: llvm_unreachable("Unknown cmp predicate!");
2899     case ICMP_EQ: return ICMP_NE;
2900     case ICMP_NE: return ICMP_EQ;
2901     case ICMP_UGT: return ICMP_ULE;
2902     case ICMP_ULT: return ICMP_UGE;
2903     case ICMP_UGE: return ICMP_ULT;
2904     case ICMP_ULE: return ICMP_UGT;
2905     case ICMP_SGT: return ICMP_SLE;
2906     case ICMP_SLT: return ICMP_SGE;
2907     case ICMP_SGE: return ICMP_SLT;
2908     case ICMP_SLE: return ICMP_SGT;
2909
2910     case FCMP_OEQ: return FCMP_UNE;
2911     case FCMP_ONE: return FCMP_UEQ;
2912     case FCMP_OGT: return FCMP_ULE;
2913     case FCMP_OLT: return FCMP_UGE;
2914     case FCMP_OGE: return FCMP_ULT;
2915     case FCMP_OLE: return FCMP_UGT;
2916     case FCMP_UEQ: return FCMP_ONE;
2917     case FCMP_UNE: return FCMP_OEQ;
2918     case FCMP_UGT: return FCMP_OLE;
2919     case FCMP_ULT: return FCMP_OGE;
2920     case FCMP_UGE: return FCMP_OLT;
2921     case FCMP_ULE: return FCMP_OGT;
2922     case FCMP_ORD: return FCMP_UNO;
2923     case FCMP_UNO: return FCMP_ORD;
2924     case FCMP_TRUE: return FCMP_FALSE;
2925     case FCMP_FALSE: return FCMP_TRUE;
2926   }
2927 }
2928
2929 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2930   switch (pred) {
2931     default: llvm_unreachable("Unknown icmp predicate!");
2932     case ICMP_EQ: case ICMP_NE: 
2933     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2934        return pred;
2935     case ICMP_UGT: return ICMP_SGT;
2936     case ICMP_ULT: return ICMP_SLT;
2937     case ICMP_UGE: return ICMP_SGE;
2938     case ICMP_ULE: return ICMP_SLE;
2939   }
2940 }
2941
2942 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2943   switch (pred) {
2944     default: llvm_unreachable("Unknown icmp predicate!");
2945     case ICMP_EQ: case ICMP_NE: 
2946     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 
2947        return pred;
2948     case ICMP_SGT: return ICMP_UGT;
2949     case ICMP_SLT: return ICMP_ULT;
2950     case ICMP_SGE: return ICMP_UGE;
2951     case ICMP_SLE: return ICMP_ULE;
2952   }
2953 }
2954
2955 /// Initialize a set of values that all satisfy the condition with C.
2956 ///
2957 ConstantRange 
2958 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2959   APInt Lower(C);
2960   APInt Upper(C);
2961   uint32_t BitWidth = C.getBitWidth();
2962   switch (pred) {
2963   default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2964   case ICmpInst::ICMP_EQ: Upper++; break;
2965   case ICmpInst::ICMP_NE: Lower++; break;
2966   case ICmpInst::ICMP_ULT:
2967     Lower = APInt::getMinValue(BitWidth);
2968     // Check for an empty-set condition.
2969     if (Lower == Upper)
2970       return ConstantRange(BitWidth, /*isFullSet=*/false);
2971     break;
2972   case ICmpInst::ICMP_SLT:
2973     Lower = APInt::getSignedMinValue(BitWidth);
2974     // Check for an empty-set condition.
2975     if (Lower == Upper)
2976       return ConstantRange(BitWidth, /*isFullSet=*/false);
2977     break;
2978   case ICmpInst::ICMP_UGT: 
2979     Lower++; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2980     // Check for an empty-set condition.
2981     if (Lower == Upper)
2982       return ConstantRange(BitWidth, /*isFullSet=*/false);
2983     break;
2984   case ICmpInst::ICMP_SGT:
2985     Lower++; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2986     // Check for an empty-set condition.
2987     if (Lower == Upper)
2988       return ConstantRange(BitWidth, /*isFullSet=*/false);
2989     break;
2990   case ICmpInst::ICMP_ULE: 
2991     Lower = APInt::getMinValue(BitWidth); Upper++; 
2992     // Check for a full-set condition.
2993     if (Lower == Upper)
2994       return ConstantRange(BitWidth, /*isFullSet=*/true);
2995     break;
2996   case ICmpInst::ICMP_SLE: 
2997     Lower = APInt::getSignedMinValue(BitWidth); Upper++; 
2998     // Check for a full-set condition.
2999     if (Lower == Upper)
3000       return ConstantRange(BitWidth, /*isFullSet=*/true);
3001     break;
3002   case ICmpInst::ICMP_UGE:
3003     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
3004     // Check for a full-set condition.
3005     if (Lower == Upper)
3006       return ConstantRange(BitWidth, /*isFullSet=*/true);
3007     break;
3008   case ICmpInst::ICMP_SGE:
3009     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
3010     // Check for a full-set condition.
3011     if (Lower == Upper)
3012       return ConstantRange(BitWidth, /*isFullSet=*/true);
3013     break;
3014   }
3015   return ConstantRange(Lower, Upper);
3016 }
3017
3018 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3019   switch (pred) {
3020     default: llvm_unreachable("Unknown cmp predicate!");
3021     case ICMP_EQ: case ICMP_NE:
3022       return pred;
3023     case ICMP_SGT: return ICMP_SLT;
3024     case ICMP_SLT: return ICMP_SGT;
3025     case ICMP_SGE: return ICMP_SLE;
3026     case ICMP_SLE: return ICMP_SGE;
3027     case ICMP_UGT: return ICMP_ULT;
3028     case ICMP_ULT: return ICMP_UGT;
3029     case ICMP_UGE: return ICMP_ULE;
3030     case ICMP_ULE: return ICMP_UGE;
3031   
3032     case FCMP_FALSE: case FCMP_TRUE:
3033     case FCMP_OEQ: case FCMP_ONE:
3034     case FCMP_UEQ: case FCMP_UNE:
3035     case FCMP_ORD: case FCMP_UNO:
3036       return pred;
3037     case FCMP_OGT: return FCMP_OLT;
3038     case FCMP_OLT: return FCMP_OGT;
3039     case FCMP_OGE: return FCMP_OLE;
3040     case FCMP_OLE: return FCMP_OGE;
3041     case FCMP_UGT: return FCMP_ULT;
3042     case FCMP_ULT: return FCMP_UGT;
3043     case FCMP_UGE: return FCMP_ULE;
3044     case FCMP_ULE: return FCMP_UGE;
3045   }
3046 }
3047
3048 bool CmpInst::isUnsigned(unsigned short predicate) {
3049   switch (predicate) {
3050     default: return false;
3051     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
3052     case ICmpInst::ICMP_UGE: return true;
3053   }
3054 }
3055
3056 bool CmpInst::isSigned(unsigned short predicate) {
3057   switch (predicate) {
3058     default: return false;
3059     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
3060     case ICmpInst::ICMP_SGE: return true;
3061   }
3062 }
3063
3064 bool CmpInst::isOrdered(unsigned short predicate) {
3065   switch (predicate) {
3066     default: return false;
3067     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
3068     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
3069     case FCmpInst::FCMP_ORD: return true;
3070   }
3071 }
3072       
3073 bool CmpInst::isUnordered(unsigned short predicate) {
3074   switch (predicate) {
3075     default: return false;
3076     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
3077     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
3078     case FCmpInst::FCMP_UNO: return true;
3079   }
3080 }
3081
3082 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3083   switch(predicate) {
3084     default: return false;
3085     case ICMP_EQ:   case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3086     case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3087   }
3088 }
3089
3090 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3091   switch(predicate) {
3092   case ICMP_NE:    case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3093   case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3094   default: return false;
3095   }
3096 }
3097
3098
3099 //===----------------------------------------------------------------------===//
3100 //                        SwitchInst Implementation
3101 //===----------------------------------------------------------------------===//
3102
3103 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3104   assert(Value && Default && NumReserved);
3105   ReservedSpace = NumReserved;
3106   NumOperands = 2;
3107   OperandList = allocHungoffUses(ReservedSpace);
3108
3109   OperandList[0] = Value;
3110   OperandList[1] = Default;
3111 }
3112
3113 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3114 /// switch on and a default destination.  The number of additional cases can
3115 /// be specified here to make memory allocation more efficient.  This
3116 /// constructor can also autoinsert before another instruction.
3117 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3118                        Instruction *InsertBefore)
3119   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3120                    0, 0, InsertBefore) {
3121   init(Value, Default, 2+NumCases*2);
3122 }
3123
3124 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3125 /// switch on and a default destination.  The number of additional cases can
3126 /// be specified here to make memory allocation more efficient.  This
3127 /// constructor also autoinserts at the end of the specified BasicBlock.
3128 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3129                        BasicBlock *InsertAtEnd)
3130   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3131                    0, 0, InsertAtEnd) {
3132   init(Value, Default, 2+NumCases*2);
3133 }
3134
3135 SwitchInst::SwitchInst(const SwitchInst &SI)
3136   : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3137   init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3138   NumOperands = SI.getNumOperands();
3139   Use *OL = OperandList, *InOL = SI.OperandList;
3140   for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3141     OL[i] = InOL[i];
3142     OL[i+1] = InOL[i+1];
3143   }
3144   SubclassOptionalData = SI.SubclassOptionalData;
3145 }
3146
3147 SwitchInst::~SwitchInst() {
3148   dropHungoffUses();
3149 }
3150
3151
3152 /// addCase - Add an entry to the switch instruction...
3153 ///
3154 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3155   unsigned NewCaseIdx = getNumCases(); 
3156   unsigned OpNo = NumOperands;
3157   if (OpNo+2 > ReservedSpace)
3158     growOperands();  // Get more space!
3159   // Initialize some new operands.
3160   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3161   NumOperands = OpNo+2;
3162   CaseIt Case(this, NewCaseIdx);
3163   Case.setValue(OnVal);
3164   Case.setSuccessor(Dest);
3165 }
3166
3167 /// removeCase - This method removes the specified case and its successor
3168 /// from the switch instruction.
3169 void SwitchInst::removeCase(CaseIt i) {
3170   unsigned idx = i.getCaseIndex();
3171   
3172   assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3173
3174   unsigned NumOps = getNumOperands();
3175   Use *OL = OperandList;
3176
3177   // Overwrite this case with the end of the list.
3178   if (2 + (idx + 1) * 2 != NumOps) {
3179     OL[2 + idx * 2] = OL[NumOps - 2];
3180     OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3181   }
3182
3183   // Nuke the last value.
3184   OL[NumOps-2].set(0);
3185   OL[NumOps-2+1].set(0);
3186   NumOperands = NumOps-2;
3187 }
3188
3189 /// growOperands - grow operands - This grows the operand list in response
3190 /// to a push_back style of operation.  This grows the number of ops by 3 times.
3191 ///
3192 void SwitchInst::growOperands() {
3193   unsigned e = getNumOperands();
3194   unsigned NumOps = e*3;
3195
3196   ReservedSpace = NumOps;
3197   Use *NewOps = allocHungoffUses(NumOps);
3198   Use *OldOps = OperandList;
3199   for (unsigned i = 0; i != e; ++i) {
3200       NewOps[i] = OldOps[i];
3201   }
3202   OperandList = NewOps;
3203   Use::zap(OldOps, OldOps + e, true);
3204 }
3205
3206
3207 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3208   return getSuccessor(idx);
3209 }
3210 unsigned SwitchInst::getNumSuccessorsV() const {
3211   return getNumSuccessors();
3212 }
3213 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3214   setSuccessor(idx, B);
3215 }
3216
3217 //===----------------------------------------------------------------------===//
3218 //                        IndirectBrInst Implementation
3219 //===----------------------------------------------------------------------===//
3220
3221 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3222   assert(Address && Address->getType()->isPointerTy() &&
3223          "Address of indirectbr must be a pointer");
3224   ReservedSpace = 1+NumDests;
3225   NumOperands = 1;
3226   OperandList = allocHungoffUses(ReservedSpace);
3227   
3228   OperandList[0] = Address;
3229 }
3230
3231
3232 /// growOperands - grow operands - This grows the operand list in response
3233 /// to a push_back style of operation.  This grows the number of ops by 2 times.
3234 ///
3235 void IndirectBrInst::growOperands() {
3236   unsigned e = getNumOperands();
3237   unsigned NumOps = e*2;
3238   
3239   ReservedSpace = NumOps;
3240   Use *NewOps = allocHungoffUses(NumOps);
3241   Use *OldOps = OperandList;
3242   for (unsigned i = 0; i != e; ++i)
3243     NewOps[i] = OldOps[i];
3244   OperandList = NewOps;
3245   Use::zap(OldOps, OldOps + e, true);
3246 }
3247
3248 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3249                                Instruction *InsertBefore)
3250 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3251                  0, 0, InsertBefore) {
3252   init(Address, NumCases);
3253 }
3254
3255 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3256                                BasicBlock *InsertAtEnd)
3257 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3258                  0, 0, InsertAtEnd) {
3259   init(Address, NumCases);
3260 }
3261
3262 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3263   : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3264                    allocHungoffUses(IBI.getNumOperands()),
3265                    IBI.getNumOperands()) {
3266   Use *OL = OperandList, *InOL = IBI.OperandList;
3267   for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3268     OL[i] = InOL[i];
3269   SubclassOptionalData = IBI.SubclassOptionalData;
3270 }
3271
3272 IndirectBrInst::~IndirectBrInst() {
3273   dropHungoffUses();
3274 }
3275
3276 /// addDestination - Add a destination.
3277 ///
3278 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3279   unsigned OpNo = NumOperands;
3280   if (OpNo+1 > ReservedSpace)
3281     growOperands();  // Get more space!
3282   // Initialize some new operands.
3283   assert(OpNo < ReservedSpace && "Growing didn't work!");
3284   NumOperands = OpNo+1;
3285   OperandList[OpNo] = DestBB;
3286 }
3287
3288 /// removeDestination - This method removes the specified successor from the
3289 /// indirectbr instruction.
3290 void IndirectBrInst::removeDestination(unsigned idx) {
3291   assert(idx < getNumOperands()-1 && "Successor index out of range!");
3292   
3293   unsigned NumOps = getNumOperands();
3294   Use *OL = OperandList;
3295
3296   // Replace this value with the last one.
3297   OL[idx+1] = OL[NumOps-1];
3298   
3299   // Nuke the last value.
3300   OL[NumOps-1].set(0);
3301   NumOperands = NumOps-1;
3302 }
3303
3304 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3305   return getSuccessor(idx);
3306 }
3307 unsigned IndirectBrInst::getNumSuccessorsV() const {
3308   return getNumSuccessors();
3309 }
3310 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3311   setSuccessor(idx, B);
3312 }
3313
3314 //===----------------------------------------------------------------------===//
3315 //                           clone_impl() implementations
3316 //===----------------------------------------------------------------------===//
3317
3318 // Define these methods here so vtables don't get emitted into every translation
3319 // unit that uses these classes.
3320
3321 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3322   return new (getNumOperands()) GetElementPtrInst(*this);
3323 }
3324
3325 BinaryOperator *BinaryOperator::clone_impl() const {
3326   return Create(getOpcode(), Op<0>(), Op<1>());
3327 }
3328
3329 FCmpInst* FCmpInst::clone_impl() const {
3330   return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3331 }
3332
3333 ICmpInst* ICmpInst::clone_impl() const {
3334   return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3335 }
3336
3337 ExtractValueInst *ExtractValueInst::clone_impl() const {
3338   return new ExtractValueInst(*this);
3339 }
3340
3341 InsertValueInst *InsertValueInst::clone_impl() const {
3342   return new InsertValueInst(*this);
3343 }
3344
3345 AllocaInst *AllocaInst::clone_impl() const {
3346   return new AllocaInst(getAllocatedType(),
3347                         (Value*)getOperand(0),
3348                         getAlignment());
3349 }
3350
3351 LoadInst *LoadInst::clone_impl() const {
3352   return new LoadInst(getOperand(0), Twine(), isVolatile(),
3353                       getAlignment(), getOrdering(), getSynchScope());
3354 }
3355
3356 StoreInst *StoreInst::clone_impl() const {
3357   return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3358                        getAlignment(), getOrdering(), getSynchScope());
3359   
3360 }
3361
3362 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3363   AtomicCmpXchgInst *Result =
3364     new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3365                           getOrdering(), getSynchScope());
3366   Result->setVolatile(isVolatile());
3367   return Result;
3368 }
3369
3370 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3371   AtomicRMWInst *Result =
3372     new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3373                       getOrdering(), getSynchScope());
3374   Result->setVolatile(isVolatile());
3375   return Result;
3376 }
3377
3378 FenceInst *FenceInst::clone_impl() const {
3379   return new FenceInst(getContext(), getOrdering(), getSynchScope());
3380 }
3381
3382 TruncInst *TruncInst::clone_impl() const {
3383   return new TruncInst(getOperand(0), getType());
3384 }
3385
3386 ZExtInst *ZExtInst::clone_impl() const {
3387   return new ZExtInst(getOperand(0), getType());
3388 }
3389
3390 SExtInst *SExtInst::clone_impl() const {
3391   return new SExtInst(getOperand(0), getType());
3392 }
3393
3394 FPTruncInst *FPTruncInst::clone_impl() const {
3395   return new FPTruncInst(getOperand(0), getType());
3396 }
3397
3398 FPExtInst *FPExtInst::clone_impl() const {
3399   return new FPExtInst(getOperand(0), getType());
3400 }
3401
3402 UIToFPInst *UIToFPInst::clone_impl() const {
3403   return new UIToFPInst(getOperand(0), getType());
3404 }
3405
3406 SIToFPInst *SIToFPInst::clone_impl() const {
3407   return new SIToFPInst(getOperand(0), getType());
3408 }
3409
3410 FPToUIInst *FPToUIInst::clone_impl() const {
3411   return new FPToUIInst(getOperand(0), getType());
3412 }
3413
3414 FPToSIInst *FPToSIInst::clone_impl() const {
3415   return new FPToSIInst(getOperand(0), getType());
3416 }
3417
3418 PtrToIntInst *PtrToIntInst::clone_impl() const {
3419   return new PtrToIntInst(getOperand(0), getType());
3420 }
3421
3422 IntToPtrInst *IntToPtrInst::clone_impl() const {
3423   return new IntToPtrInst(getOperand(0), getType());
3424 }
3425
3426 BitCastInst *BitCastInst::clone_impl() const {
3427   return new BitCastInst(getOperand(0), getType());
3428 }
3429
3430 CallInst *CallInst::clone_impl() const {
3431   return  new(getNumOperands()) CallInst(*this);
3432 }
3433
3434 SelectInst *SelectInst::clone_impl() const {
3435   return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3436 }
3437
3438 VAArgInst *VAArgInst::clone_impl() const {
3439   return new VAArgInst(getOperand(0), getType());
3440 }
3441
3442 ExtractElementInst *ExtractElementInst::clone_impl() const {
3443   return ExtractElementInst::Create(getOperand(0), getOperand(1));
3444 }
3445
3446 InsertElementInst *InsertElementInst::clone_impl() const {
3447   return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3448 }
3449
3450 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3451   return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3452 }
3453
3454 PHINode *PHINode::clone_impl() const {
3455   return new PHINode(*this);
3456 }
3457
3458 LandingPadInst *LandingPadInst::clone_impl() const {
3459   return new LandingPadInst(*this);
3460 }
3461
3462 ReturnInst *ReturnInst::clone_impl() const {
3463   return new(getNumOperands()) ReturnInst(*this);
3464 }
3465
3466 BranchInst *BranchInst::clone_impl() const {
3467   return new(getNumOperands()) BranchInst(*this);
3468 }
3469
3470 SwitchInst *SwitchInst::clone_impl() const {
3471   return new SwitchInst(*this);
3472 }
3473
3474 IndirectBrInst *IndirectBrInst::clone_impl() const {
3475   return new IndirectBrInst(*this);
3476 }
3477
3478
3479 InvokeInst *InvokeInst::clone_impl() const {
3480   return new(getNumOperands()) InvokeInst(*this);
3481 }
3482
3483 ResumeInst *ResumeInst::clone_impl() const {
3484   return new(1) ResumeInst(*this);
3485 }
3486
3487 UnreachableInst *UnreachableInst::clone_impl() const {
3488   LLVMContext &Context = getContext();
3489   return new UnreachableInst(Context);
3490 }