Add support for vectors of pointers.
[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   return 0;
629 }
630
631 ReturnInst::~ReturnInst() {
632 }
633
634 //===----------------------------------------------------------------------===//
635 //                        UnwindInst Implementation
636 //===----------------------------------------------------------------------===//
637
638 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
639   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
640                    0, 0, InsertBefore) {
641 }
642 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
643   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
644                    0, 0, InsertAtEnd) {
645 }
646
647
648 unsigned UnwindInst::getNumSuccessorsV() const {
649   return getNumSuccessors();
650 }
651
652 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
653   llvm_unreachable("UnwindInst has no successors!");
654 }
655
656 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
657   llvm_unreachable("UnwindInst has no successors!");
658   return 0;
659 }
660
661 //===----------------------------------------------------------------------===//
662 //                        ResumeInst Implementation
663 //===----------------------------------------------------------------------===//
664
665 ResumeInst::ResumeInst(const ResumeInst &RI)
666   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
667                    OperandTraits<ResumeInst>::op_begin(this), 1) {
668   Op<0>() = RI.Op<0>();
669 }
670
671 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
672   : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
673                    OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
674   Op<0>() = Exn;
675 }
676
677 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
678   : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
679                    OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
680   Op<0>() = Exn;
681 }
682
683 unsigned ResumeInst::getNumSuccessorsV() const {
684   return getNumSuccessors();
685 }
686
687 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
688   llvm_unreachable("ResumeInst has no successors!");
689 }
690
691 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
692   llvm_unreachable("ResumeInst has no successors!");
693   return 0;
694 }
695
696 //===----------------------------------------------------------------------===//
697 //                      UnreachableInst Implementation
698 //===----------------------------------------------------------------------===//
699
700 UnreachableInst::UnreachableInst(LLVMContext &Context, 
701                                  Instruction *InsertBefore)
702   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
703                    0, 0, InsertBefore) {
704 }
705 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
706   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
707                    0, 0, InsertAtEnd) {
708 }
709
710 unsigned UnreachableInst::getNumSuccessorsV() const {
711   return getNumSuccessors();
712 }
713
714 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
715   llvm_unreachable("UnwindInst has no successors!");
716 }
717
718 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
719   llvm_unreachable("UnwindInst has no successors!");
720   return 0;
721 }
722
723 //===----------------------------------------------------------------------===//
724 //                        BranchInst Implementation
725 //===----------------------------------------------------------------------===//
726
727 void BranchInst::AssertOK() {
728   if (isConditional())
729     assert(getCondition()->getType()->isIntegerTy(1) &&
730            "May only branch on boolean predicates!");
731 }
732
733 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
734   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
735                    OperandTraits<BranchInst>::op_end(this) - 1,
736                    1, InsertBefore) {
737   assert(IfTrue != 0 && "Branch destination may not be null!");
738   Op<-1>() = IfTrue;
739 }
740 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
741                        Instruction *InsertBefore)
742   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
743                    OperandTraits<BranchInst>::op_end(this) - 3,
744                    3, InsertBefore) {
745   Op<-1>() = IfTrue;
746   Op<-2>() = IfFalse;
747   Op<-3>() = Cond;
748 #ifndef NDEBUG
749   AssertOK();
750 #endif
751 }
752
753 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
754   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
755                    OperandTraits<BranchInst>::op_end(this) - 1,
756                    1, InsertAtEnd) {
757   assert(IfTrue != 0 && "Branch destination may not be null!");
758   Op<-1>() = IfTrue;
759 }
760
761 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
762            BasicBlock *InsertAtEnd)
763   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
764                    OperandTraits<BranchInst>::op_end(this) - 3,
765                    3, InsertAtEnd) {
766   Op<-1>() = IfTrue;
767   Op<-2>() = IfFalse;
768   Op<-3>() = Cond;
769 #ifndef NDEBUG
770   AssertOK();
771 #endif
772 }
773
774
775 BranchInst::BranchInst(const BranchInst &BI) :
776   TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
777                  OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
778                  BI.getNumOperands()) {
779   Op<-1>() = BI.Op<-1>();
780   if (BI.getNumOperands() != 1) {
781     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
782     Op<-3>() = BI.Op<-3>();
783     Op<-2>() = BI.Op<-2>();
784   }
785   SubclassOptionalData = BI.SubclassOptionalData;
786 }
787
788 void BranchInst::swapSuccessors() {
789   assert(isConditional() &&
790          "Cannot swap successors of an unconditional branch");
791   Op<-1>().swap(Op<-2>());
792
793   // Update profile metadata if present and it matches our structural
794   // expectations.
795   MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
796   if (!ProfileData || ProfileData->getNumOperands() != 3)
797     return;
798
799   // The first operand is the name. Fetch them backwards and build a new one.
800   Value *Ops[] = {
801     ProfileData->getOperand(0),
802     ProfileData->getOperand(2),
803     ProfileData->getOperand(1)
804   };
805   setMetadata(LLVMContext::MD_prof,
806               MDNode::get(ProfileData->getContext(), Ops));
807 }
808
809 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
810   return getSuccessor(idx);
811 }
812 unsigned BranchInst::getNumSuccessorsV() const {
813   return getNumSuccessors();
814 }
815 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
816   setSuccessor(idx, B);
817 }
818
819
820 //===----------------------------------------------------------------------===//
821 //                        AllocaInst Implementation
822 //===----------------------------------------------------------------------===//
823
824 static Value *getAISize(LLVMContext &Context, Value *Amt) {
825   if (!Amt)
826     Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
827   else {
828     assert(!isa<BasicBlock>(Amt) &&
829            "Passed basic block into allocation size parameter! Use other ctor");
830     assert(Amt->getType()->isIntegerTy() &&
831            "Allocation array size is not an integer!");
832   }
833   return Amt;
834 }
835
836 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
837                        const Twine &Name, Instruction *InsertBefore)
838   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
839                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
840   setAlignment(0);
841   assert(!Ty->isVoidTy() && "Cannot allocate void!");
842   setName(Name);
843 }
844
845 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
846                        const Twine &Name, BasicBlock *InsertAtEnd)
847   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
848                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
849   setAlignment(0);
850   assert(!Ty->isVoidTy() && "Cannot allocate void!");
851   setName(Name);
852 }
853
854 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
855                        Instruction *InsertBefore)
856   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
857                      getAISize(Ty->getContext(), 0), InsertBefore) {
858   setAlignment(0);
859   assert(!Ty->isVoidTy() && "Cannot allocate void!");
860   setName(Name);
861 }
862
863 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
864                        BasicBlock *InsertAtEnd)
865   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
866                      getAISize(Ty->getContext(), 0), InsertAtEnd) {
867   setAlignment(0);
868   assert(!Ty->isVoidTy() && "Cannot allocate void!");
869   setName(Name);
870 }
871
872 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
873                        const Twine &Name, Instruction *InsertBefore)
874   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
875                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
876   setAlignment(Align);
877   assert(!Ty->isVoidTy() && "Cannot allocate void!");
878   setName(Name);
879 }
880
881 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
882                        const Twine &Name, BasicBlock *InsertAtEnd)
883   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
884                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
885   setAlignment(Align);
886   assert(!Ty->isVoidTy() && "Cannot allocate void!");
887   setName(Name);
888 }
889
890 // Out of line virtual method, so the vtable, etc has a home.
891 AllocaInst::~AllocaInst() {
892 }
893
894 void AllocaInst::setAlignment(unsigned Align) {
895   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
896   assert(Align <= MaximumAlignment &&
897          "Alignment is greater than MaximumAlignment!");
898   setInstructionSubclassData(Log2_32(Align) + 1);
899   assert(getAlignment() == Align && "Alignment representation error!");
900 }
901
902 bool AllocaInst::isArrayAllocation() const {
903   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
904     return !CI->isOne();
905   return true;
906 }
907
908 Type *AllocaInst::getAllocatedType() const {
909   return getType()->getElementType();
910 }
911
912 /// isStaticAlloca - Return true if this alloca is in the entry block of the
913 /// function and is a constant size.  If so, the code generator will fold it
914 /// into the prolog/epilog code, so it is basically free.
915 bool AllocaInst::isStaticAlloca() const {
916   // Must be constant size.
917   if (!isa<ConstantInt>(getArraySize())) return false;
918   
919   // Must be in the entry block.
920   const BasicBlock *Parent = getParent();
921   return Parent == &Parent->getParent()->front();
922 }
923
924 //===----------------------------------------------------------------------===//
925 //                           LoadInst Implementation
926 //===----------------------------------------------------------------------===//
927
928 void LoadInst::AssertOK() {
929   assert(getOperand(0)->getType()->isPointerTy() &&
930          "Ptr must have pointer type.");
931   assert(!(isAtomic() && getAlignment() == 0) &&
932          "Alignment required for atomic load");
933 }
934
935 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
936   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
937                      Load, Ptr, InsertBef) {
938   setVolatile(false);
939   setAlignment(0);
940   setAtomic(NotAtomic);
941   AssertOK();
942   setName(Name);
943 }
944
945 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
946   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
947                      Load, Ptr, InsertAE) {
948   setVolatile(false);
949   setAlignment(0);
950   setAtomic(NotAtomic);
951   AssertOK();
952   setName(Name);
953 }
954
955 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
956                    Instruction *InsertBef)
957   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
958                      Load, Ptr, InsertBef) {
959   setVolatile(isVolatile);
960   setAlignment(0);
961   setAtomic(NotAtomic);
962   AssertOK();
963   setName(Name);
964 }
965
966 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
967                    BasicBlock *InsertAE)
968   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
969                      Load, Ptr, InsertAE) {
970   setVolatile(isVolatile);
971   setAlignment(0);
972   setAtomic(NotAtomic);
973   AssertOK();
974   setName(Name);
975 }
976
977 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
978                    unsigned Align, Instruction *InsertBef)
979   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
980                      Load, Ptr, InsertBef) {
981   setVolatile(isVolatile);
982   setAlignment(Align);
983   setAtomic(NotAtomic);
984   AssertOK();
985   setName(Name);
986 }
987
988 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
989                    unsigned Align, BasicBlock *InsertAE)
990   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
991                      Load, Ptr, InsertAE) {
992   setVolatile(isVolatile);
993   setAlignment(Align);
994   setAtomic(NotAtomic);
995   AssertOK();
996   setName(Name);
997 }
998
999 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
1000                    unsigned Align, AtomicOrdering Order,
1001                    SynchronizationScope SynchScope,
1002                    Instruction *InsertBef)
1003   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1004                      Load, Ptr, InsertBef) {
1005   setVolatile(isVolatile);
1006   setAlignment(Align);
1007   setAtomic(Order, SynchScope);
1008   AssertOK();
1009   setName(Name);
1010 }
1011
1012 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
1013                    unsigned Align, AtomicOrdering Order,
1014                    SynchronizationScope SynchScope,
1015                    BasicBlock *InsertAE)
1016   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1017                      Load, Ptr, InsertAE) {
1018   setVolatile(isVolatile);
1019   setAlignment(Align);
1020   setAtomic(Order, SynchScope);
1021   AssertOK();
1022   setName(Name);
1023 }
1024
1025 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1026   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1027                      Load, Ptr, InsertBef) {
1028   setVolatile(false);
1029   setAlignment(0);
1030   setAtomic(NotAtomic);
1031   AssertOK();
1032   if (Name && Name[0]) setName(Name);
1033 }
1034
1035 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1036   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1037                      Load, Ptr, InsertAE) {
1038   setVolatile(false);
1039   setAlignment(0);
1040   setAtomic(NotAtomic);
1041   AssertOK();
1042   if (Name && Name[0]) setName(Name);
1043 }
1044
1045 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1046                    Instruction *InsertBef)
1047 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1048                    Load, Ptr, InsertBef) {
1049   setVolatile(isVolatile);
1050   setAlignment(0);
1051   setAtomic(NotAtomic);
1052   AssertOK();
1053   if (Name && Name[0]) setName(Name);
1054 }
1055
1056 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1057                    BasicBlock *InsertAE)
1058   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1059                      Load, Ptr, InsertAE) {
1060   setVolatile(isVolatile);
1061   setAlignment(0);
1062   setAtomic(NotAtomic);
1063   AssertOK();
1064   if (Name && Name[0]) setName(Name);
1065 }
1066
1067 void LoadInst::setAlignment(unsigned Align) {
1068   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1069   assert(Align <= MaximumAlignment &&
1070          "Alignment is greater than MaximumAlignment!");
1071   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1072                              ((Log2_32(Align)+1)<<1));
1073   assert(getAlignment() == Align && "Alignment representation error!");
1074 }
1075
1076 //===----------------------------------------------------------------------===//
1077 //                           StoreInst Implementation
1078 //===----------------------------------------------------------------------===//
1079
1080 void StoreInst::AssertOK() {
1081   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1082   assert(getOperand(1)->getType()->isPointerTy() &&
1083          "Ptr must have pointer type!");
1084   assert(getOperand(0)->getType() ==
1085                  cast<PointerType>(getOperand(1)->getType())->getElementType()
1086          && "Ptr must be a pointer to Val type!");
1087   assert(!(isAtomic() && getAlignment() == 0) &&
1088          "Alignment required for atomic load");
1089 }
1090
1091
1092 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1093   : Instruction(Type::getVoidTy(val->getContext()), Store,
1094                 OperandTraits<StoreInst>::op_begin(this),
1095                 OperandTraits<StoreInst>::operands(this),
1096                 InsertBefore) {
1097   Op<0>() = val;
1098   Op<1>() = addr;
1099   setVolatile(false);
1100   setAlignment(0);
1101   setAtomic(NotAtomic);
1102   AssertOK();
1103 }
1104
1105 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1106   : Instruction(Type::getVoidTy(val->getContext()), Store,
1107                 OperandTraits<StoreInst>::op_begin(this),
1108                 OperandTraits<StoreInst>::operands(this),
1109                 InsertAtEnd) {
1110   Op<0>() = val;
1111   Op<1>() = addr;
1112   setVolatile(false);
1113   setAlignment(0);
1114   setAtomic(NotAtomic);
1115   AssertOK();
1116 }
1117
1118 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
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(0);
1128   setAtomic(NotAtomic);
1129   AssertOK();
1130 }
1131
1132 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1133                      unsigned Align, Instruction *InsertBefore)
1134   : Instruction(Type::getVoidTy(val->getContext()), Store,
1135                 OperandTraits<StoreInst>::op_begin(this),
1136                 OperandTraits<StoreInst>::operands(this),
1137                 InsertBefore) {
1138   Op<0>() = val;
1139   Op<1>() = addr;
1140   setVolatile(isVolatile);
1141   setAlignment(Align);
1142   setAtomic(NotAtomic);
1143   AssertOK();
1144 }
1145
1146 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1147                      unsigned Align, AtomicOrdering Order,
1148                      SynchronizationScope SynchScope,
1149                      Instruction *InsertBefore)
1150   : Instruction(Type::getVoidTy(val->getContext()), Store,
1151                 OperandTraits<StoreInst>::op_begin(this),
1152                 OperandTraits<StoreInst>::operands(this),
1153                 InsertBefore) {
1154   Op<0>() = val;
1155   Op<1>() = addr;
1156   setVolatile(isVolatile);
1157   setAlignment(Align);
1158   setAtomic(Order, SynchScope);
1159   AssertOK();
1160 }
1161
1162 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
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(0);
1172   setAtomic(NotAtomic);
1173   AssertOK();
1174 }
1175
1176 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1177                      unsigned Align, BasicBlock *InsertAtEnd)
1178   : Instruction(Type::getVoidTy(val->getContext()), Store,
1179                 OperandTraits<StoreInst>::op_begin(this),
1180                 OperandTraits<StoreInst>::operands(this),
1181                 InsertAtEnd) {
1182   Op<0>() = val;
1183   Op<1>() = addr;
1184   setVolatile(isVolatile);
1185   setAlignment(Align);
1186   setAtomic(NotAtomic);
1187   AssertOK();
1188 }
1189
1190 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1191                      unsigned Align, AtomicOrdering Order,
1192                      SynchronizationScope SynchScope,
1193                      BasicBlock *InsertAtEnd)
1194   : Instruction(Type::getVoidTy(val->getContext()), Store,
1195                 OperandTraits<StoreInst>::op_begin(this),
1196                 OperandTraits<StoreInst>::operands(this),
1197                 InsertAtEnd) {
1198   Op<0>() = val;
1199   Op<1>() = addr;
1200   setVolatile(isVolatile);
1201   setAlignment(Align);
1202   setAtomic(Order, SynchScope);
1203   AssertOK();
1204 }
1205
1206 void StoreInst::setAlignment(unsigned Align) {
1207   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1208   assert(Align <= MaximumAlignment &&
1209          "Alignment is greater than MaximumAlignment!");
1210   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1211                              ((Log2_32(Align)+1) << 1));
1212   assert(getAlignment() == Align && "Alignment representation error!");
1213 }
1214
1215 //===----------------------------------------------------------------------===//
1216 //                       AtomicCmpXchgInst Implementation
1217 //===----------------------------------------------------------------------===//
1218
1219 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1220                              AtomicOrdering Ordering,
1221                              SynchronizationScope SynchScope) {
1222   Op<0>() = Ptr;
1223   Op<1>() = Cmp;
1224   Op<2>() = NewVal;
1225   setOrdering(Ordering);
1226   setSynchScope(SynchScope);
1227
1228   assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1229          "All operands must be non-null!");
1230   assert(getOperand(0)->getType()->isPointerTy() &&
1231          "Ptr must have pointer type!");
1232   assert(getOperand(1)->getType() ==
1233                  cast<PointerType>(getOperand(0)->getType())->getElementType()
1234          && "Ptr must be a pointer to Cmp type!");
1235   assert(getOperand(2)->getType() ==
1236                  cast<PointerType>(getOperand(0)->getType())->getElementType()
1237          && "Ptr must be a pointer to NewVal type!");
1238   assert(Ordering != NotAtomic &&
1239          "AtomicCmpXchg instructions must be atomic!");
1240 }
1241
1242 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1243                                      AtomicOrdering Ordering,
1244                                      SynchronizationScope SynchScope,
1245                                      Instruction *InsertBefore)
1246   : Instruction(Cmp->getType(), AtomicCmpXchg,
1247                 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1248                 OperandTraits<AtomicCmpXchgInst>::operands(this),
1249                 InsertBefore) {
1250   Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1251 }
1252
1253 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1254                                      AtomicOrdering Ordering,
1255                                      SynchronizationScope SynchScope,
1256                                      BasicBlock *InsertAtEnd)
1257   : Instruction(Cmp->getType(), AtomicCmpXchg,
1258                 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1259                 OperandTraits<AtomicCmpXchgInst>::operands(this),
1260                 InsertAtEnd) {
1261   Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1262 }
1263  
1264 //===----------------------------------------------------------------------===//
1265 //                       AtomicRMWInst Implementation
1266 //===----------------------------------------------------------------------===//
1267
1268 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1269                          AtomicOrdering Ordering,
1270                          SynchronizationScope SynchScope) {
1271   Op<0>() = Ptr;
1272   Op<1>() = Val;
1273   setOperation(Operation);
1274   setOrdering(Ordering);
1275   setSynchScope(SynchScope);
1276
1277   assert(getOperand(0) && getOperand(1) &&
1278          "All operands must be non-null!");
1279   assert(getOperand(0)->getType()->isPointerTy() &&
1280          "Ptr must have pointer type!");
1281   assert(getOperand(1)->getType() ==
1282          cast<PointerType>(getOperand(0)->getType())->getElementType()
1283          && "Ptr must be a pointer to Val type!");
1284   assert(Ordering != NotAtomic &&
1285          "AtomicRMW instructions must be atomic!");
1286 }
1287
1288 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1289                              AtomicOrdering Ordering,
1290                              SynchronizationScope SynchScope,
1291                              Instruction *InsertBefore)
1292   : Instruction(Val->getType(), AtomicRMW,
1293                 OperandTraits<AtomicRMWInst>::op_begin(this),
1294                 OperandTraits<AtomicRMWInst>::operands(this),
1295                 InsertBefore) {
1296   Init(Operation, Ptr, Val, Ordering, SynchScope);
1297 }
1298
1299 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1300                              AtomicOrdering Ordering,
1301                              SynchronizationScope SynchScope,
1302                              BasicBlock *InsertAtEnd)
1303   : Instruction(Val->getType(), AtomicRMW,
1304                 OperandTraits<AtomicRMWInst>::op_begin(this),
1305                 OperandTraits<AtomicRMWInst>::operands(this),
1306                 InsertAtEnd) {
1307   Init(Operation, Ptr, Val, Ordering, SynchScope);
1308 }
1309
1310 //===----------------------------------------------------------------------===//
1311 //                       FenceInst Implementation
1312 //===----------------------------------------------------------------------===//
1313
1314 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
1315                      SynchronizationScope SynchScope,
1316                      Instruction *InsertBefore)
1317   : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1318   setOrdering(Ordering);
1319   setSynchScope(SynchScope);
1320 }
1321
1322 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
1323                      SynchronizationScope SynchScope,
1324                      BasicBlock *InsertAtEnd)
1325   : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1326   setOrdering(Ordering);
1327   setSynchScope(SynchScope);
1328 }
1329
1330 //===----------------------------------------------------------------------===//
1331 //                       GetElementPtrInst Implementation
1332 //===----------------------------------------------------------------------===//
1333
1334 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1335                              const Twine &Name) {
1336   assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1337   OperandList[0] = Ptr;
1338   std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1339   setName(Name);
1340 }
1341
1342 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1343   : Instruction(GEPI.getType(), GetElementPtr,
1344                 OperandTraits<GetElementPtrInst>::op_end(this)
1345                 - GEPI.getNumOperands(),
1346                 GEPI.getNumOperands()) {
1347   std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1348   SubclassOptionalData = GEPI.SubclassOptionalData;
1349 }
1350
1351 /// getIndexedType - Returns the type of the element that would be accessed with
1352 /// a gep instruction with the specified parameters.
1353 ///
1354 /// The Idxs pointer should point to a continuous piece of memory containing the
1355 /// indices, either as Value* or uint64_t.
1356 ///
1357 /// A null type is returned if the indices are invalid for the specified
1358 /// pointer type.
1359 ///
1360 template <typename IndexTy>
1361 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1362   if (Ptr->isVectorTy()) {
1363     assert(IdxList.size() == 1 &&
1364       "GEP with vector pointers must have a single index");
1365     PointerType *PTy = dyn_cast<PointerType>(
1366         cast<VectorType>(Ptr)->getElementType());
1367     assert(PTy && "Gep with invalid vector pointer found");
1368     return PTy->getElementType();
1369   }
1370
1371   PointerType *PTy = dyn_cast<PointerType>(Ptr);
1372   if (!PTy) return 0;   // Type isn't a pointer type!
1373   Type *Agg = PTy->getElementType();
1374
1375   // Handle the special case of the empty set index set, which is always valid.
1376   if (IdxList.empty())
1377     return Agg;
1378
1379   // If there is at least one index, the top level type must be sized, otherwise
1380   // it cannot be 'stepped over'.
1381   if (!Agg->isSized())
1382     return 0;
1383
1384   unsigned CurIdx = 1;
1385   for (; CurIdx != IdxList.size(); ++CurIdx) {
1386     CompositeType *CT = dyn_cast<CompositeType>(Agg);
1387     if (!CT || CT->isPointerTy()) return 0;
1388     IndexTy Index = IdxList[CurIdx];
1389     if (!CT->indexValid(Index)) return 0;
1390     Agg = CT->getTypeAtIndex(Index);
1391   }
1392   return CurIdx == IdxList.size() ? Agg : 0;
1393 }
1394
1395 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1396   return getIndexedTypeInternal(Ptr, IdxList);
1397 }
1398
1399 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1400                                         ArrayRef<Constant *> IdxList) {
1401   return getIndexedTypeInternal(Ptr, IdxList);
1402 }
1403
1404 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1405   return getIndexedTypeInternal(Ptr, IdxList);
1406 }
1407
1408 unsigned GetElementPtrInst::getAddressSpace(Value *Ptr) {
1409   Type *Ty = Ptr->getType();
1410
1411   if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1412     Ty = VTy->getElementType();
1413
1414   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1415     return PTy->getAddressSpace();
1416
1417   assert(false && "Invalid GEP pointer type");
1418   return 0;
1419 }
1420
1421 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1422 /// zeros.  If so, the result pointer and the first operand have the same
1423 /// value, just potentially different types.
1424 bool GetElementPtrInst::hasAllZeroIndices() const {
1425   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1426     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1427       if (!CI->isZero()) return false;
1428     } else {
1429       return false;
1430     }
1431   }
1432   return true;
1433 }
1434
1435 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1436 /// constant integers.  If so, the result pointer and the first operand have
1437 /// a constant offset between them.
1438 bool GetElementPtrInst::hasAllConstantIndices() const {
1439   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1440     if (!isa<ConstantInt>(getOperand(i)))
1441       return false;
1442   }
1443   return true;
1444 }
1445
1446 void GetElementPtrInst::setIsInBounds(bool B) {
1447   cast<GEPOperator>(this)->setIsInBounds(B);
1448 }
1449
1450 bool GetElementPtrInst::isInBounds() const {
1451   return cast<GEPOperator>(this)->isInBounds();
1452 }
1453
1454 //===----------------------------------------------------------------------===//
1455 //                           ExtractElementInst Implementation
1456 //===----------------------------------------------------------------------===//
1457
1458 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1459                                        const Twine &Name,
1460                                        Instruction *InsertBef)
1461   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1462                 ExtractElement,
1463                 OperandTraits<ExtractElementInst>::op_begin(this),
1464                 2, InsertBef) {
1465   assert(isValidOperands(Val, Index) &&
1466          "Invalid extractelement instruction operands!");
1467   Op<0>() = Val;
1468   Op<1>() = Index;
1469   setName(Name);
1470 }
1471
1472 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1473                                        const Twine &Name,
1474                                        BasicBlock *InsertAE)
1475   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1476                 ExtractElement,
1477                 OperandTraits<ExtractElementInst>::op_begin(this),
1478                 2, InsertAE) {
1479   assert(isValidOperands(Val, Index) &&
1480          "Invalid extractelement instruction operands!");
1481
1482   Op<0>() = Val;
1483   Op<1>() = Index;
1484   setName(Name);
1485 }
1486
1487
1488 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1489   if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1490     return false;
1491   return true;
1492 }
1493
1494
1495 //===----------------------------------------------------------------------===//
1496 //                           InsertElementInst Implementation
1497 //===----------------------------------------------------------------------===//
1498
1499 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1500                                      const Twine &Name,
1501                                      Instruction *InsertBef)
1502   : Instruction(Vec->getType(), InsertElement,
1503                 OperandTraits<InsertElementInst>::op_begin(this),
1504                 3, InsertBef) {
1505   assert(isValidOperands(Vec, Elt, Index) &&
1506          "Invalid insertelement instruction operands!");
1507   Op<0>() = Vec;
1508   Op<1>() = Elt;
1509   Op<2>() = Index;
1510   setName(Name);
1511 }
1512
1513 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1514                                      const Twine &Name,
1515                                      BasicBlock *InsertAE)
1516   : Instruction(Vec->getType(), InsertElement,
1517                 OperandTraits<InsertElementInst>::op_begin(this),
1518                 3, InsertAE) {
1519   assert(isValidOperands(Vec, Elt, Index) &&
1520          "Invalid insertelement instruction operands!");
1521
1522   Op<0>() = Vec;
1523   Op<1>() = Elt;
1524   Op<2>() = Index;
1525   setName(Name);
1526 }
1527
1528 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
1529                                         const Value *Index) {
1530   if (!Vec->getType()->isVectorTy())
1531     return false;   // First operand of insertelement must be vector type.
1532   
1533   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1534     return false;// Second operand of insertelement must be vector element type.
1535     
1536   if (!Index->getType()->isIntegerTy(32))
1537     return false;  // Third operand of insertelement must be i32.
1538   return true;
1539 }
1540
1541
1542 //===----------------------------------------------------------------------===//
1543 //                      ShuffleVectorInst Implementation
1544 //===----------------------------------------------------------------------===//
1545
1546 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1547                                      const Twine &Name,
1548                                      Instruction *InsertBefore)
1549 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1550                 cast<VectorType>(Mask->getType())->getNumElements()),
1551               ShuffleVector,
1552               OperandTraits<ShuffleVectorInst>::op_begin(this),
1553               OperandTraits<ShuffleVectorInst>::operands(this),
1554               InsertBefore) {
1555   assert(isValidOperands(V1, V2, Mask) &&
1556          "Invalid shuffle vector instruction operands!");
1557   Op<0>() = V1;
1558   Op<1>() = V2;
1559   Op<2>() = Mask;
1560   setName(Name);
1561 }
1562
1563 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1564                                      const Twine &Name,
1565                                      BasicBlock *InsertAtEnd)
1566 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1567                 cast<VectorType>(Mask->getType())->getNumElements()),
1568               ShuffleVector,
1569               OperandTraits<ShuffleVectorInst>::op_begin(this),
1570               OperandTraits<ShuffleVectorInst>::operands(this),
1571               InsertAtEnd) {
1572   assert(isValidOperands(V1, V2, Mask) &&
1573          "Invalid shuffle vector instruction operands!");
1574
1575   Op<0>() = V1;
1576   Op<1>() = V2;
1577   Op<2>() = Mask;
1578   setName(Name);
1579 }
1580
1581 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1582                                         const Value *Mask) {
1583   if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1584     return false;
1585   
1586   VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1587   if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1588     return false;
1589
1590   // Check to see if Mask is valid.
1591   if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1592     VectorType *VTy = cast<VectorType>(V1->getType());
1593     for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1594       if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1595         if (CI->uge(VTy->getNumElements()*2))
1596           return false;
1597       } else if (!isa<UndefValue>(MV->getOperand(i))) {
1598         return false;
1599       }
1600     }
1601   } else if (!isa<UndefValue>(Mask) && !isa<ConstantAggregateZero>(Mask)) {
1602     // The bitcode reader can create a place holder for a forward reference
1603     // used as the shuffle mask. When this occurs, the shuffle mask will
1604     // fall into this case and fail. To avoid this error, do this bit of
1605     // ugliness to allow such a mask pass.
1606     if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(Mask)) {
1607       if (CE->getOpcode() == Instruction::UserOp1)
1608         return true;
1609     }
1610     return false;
1611   }
1612   return true;
1613 }
1614
1615 /// getMaskValue - Return the index from the shuffle mask for the specified
1616 /// output result.  This is either -1 if the element is undef or a number less
1617 /// than 2*numelements.
1618 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1619   const Constant *Mask = cast<Constant>(getOperand(2));
1620   if (isa<UndefValue>(Mask)) return -1;
1621   if (isa<ConstantAggregateZero>(Mask)) return 0;
1622   const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1623   assert(i < MaskCV->getNumOperands() && "Index out of range");
1624
1625   if (isa<UndefValue>(MaskCV->getOperand(i)))
1626     return -1;
1627   return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
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,
1881                             zero, Op,
1882                             Op->getType(), Name, InsertBefore);
1883 }
1884
1885 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1886                                            BasicBlock *InsertAtEnd) {
1887   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1888   return new BinaryOperator(Instruction::FSub,
1889                             zero, Op,
1890                             Op->getType(), Name, InsertAtEnd);
1891 }
1892
1893 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1894                                           Instruction *InsertBefore) {
1895   Constant *C;
1896   if (VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1897     C = Constant::getAllOnesValue(PTy->getElementType());
1898     C = ConstantVector::get(
1899                               std::vector<Constant*>(PTy->getNumElements(), C));
1900   } else {
1901     C = Constant::getAllOnesValue(Op->getType());
1902   }
1903   
1904   return new BinaryOperator(Instruction::Xor, Op, C,
1905                             Op->getType(), Name, InsertBefore);
1906 }
1907
1908 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1909                                           BasicBlock *InsertAtEnd) {
1910   Constant *AllOnes;
1911   if (VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1912     // Create a vector of all ones values.
1913     Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1914     AllOnes = ConstantVector::get(
1915                             std::vector<Constant*>(PTy->getNumElements(), Elt));
1916   } else {
1917     AllOnes = Constant::getAllOnesValue(Op->getType());
1918   }
1919   
1920   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1921                             Op->getType(), Name, InsertAtEnd);
1922 }
1923
1924
1925 // isConstantAllOnes - Helper function for several functions below
1926 static inline bool isConstantAllOnes(const Value *V) {
1927   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1928     return CI->isAllOnesValue();
1929   if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1930     return CV->isAllOnesValue();
1931   return false;
1932 }
1933
1934 bool BinaryOperator::isNeg(const Value *V) {
1935   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1936     if (Bop->getOpcode() == Instruction::Sub)
1937       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1938         return C->isNegativeZeroValue();
1939   return false;
1940 }
1941
1942 bool BinaryOperator::isFNeg(const Value *V) {
1943   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1944     if (Bop->getOpcode() == Instruction::FSub)
1945       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1946         return C->isNegativeZeroValue();
1947   return false;
1948 }
1949
1950 bool BinaryOperator::isNot(const Value *V) {
1951   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1952     return (Bop->getOpcode() == Instruction::Xor &&
1953             (isConstantAllOnes(Bop->getOperand(1)) ||
1954              isConstantAllOnes(Bop->getOperand(0))));
1955   return false;
1956 }
1957
1958 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1959   return cast<BinaryOperator>(BinOp)->getOperand(1);
1960 }
1961
1962 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1963   return getNegArgument(const_cast<Value*>(BinOp));
1964 }
1965
1966 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1967   return cast<BinaryOperator>(BinOp)->getOperand(1);
1968 }
1969
1970 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1971   return getFNegArgument(const_cast<Value*>(BinOp));
1972 }
1973
1974 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1975   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1976   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1977   Value *Op0 = BO->getOperand(0);
1978   Value *Op1 = BO->getOperand(1);
1979   if (isConstantAllOnes(Op0)) return Op1;
1980
1981   assert(isConstantAllOnes(Op1));
1982   return Op0;
1983 }
1984
1985 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1986   return getNotArgument(const_cast<Value*>(BinOp));
1987 }
1988
1989
1990 // swapOperands - Exchange the two operands to this instruction.  This
1991 // instruction is safe to use on any binary instruction and does not
1992 // modify the semantics of the instruction.  If the instruction is
1993 // order dependent (SetLT f.e.) the opcode is changed.
1994 //
1995 bool BinaryOperator::swapOperands() {
1996   if (!isCommutative())
1997     return true; // Can't commute operands
1998   Op<0>().swap(Op<1>());
1999   return false;
2000 }
2001
2002 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2003   cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2004 }
2005
2006 void BinaryOperator::setHasNoSignedWrap(bool b) {
2007   cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2008 }
2009
2010 void BinaryOperator::setIsExact(bool b) {
2011   cast<PossiblyExactOperator>(this)->setIsExact(b);
2012 }
2013
2014 bool BinaryOperator::hasNoUnsignedWrap() const {
2015   return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2016 }
2017
2018 bool BinaryOperator::hasNoSignedWrap() const {
2019   return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2020 }
2021
2022 bool BinaryOperator::isExact() const {
2023   return cast<PossiblyExactOperator>(this)->isExact();
2024 }
2025
2026 //===----------------------------------------------------------------------===//
2027 //                                CastInst Class
2028 //===----------------------------------------------------------------------===//
2029
2030 void CastInst::anchor() {}
2031
2032 // Just determine if this cast only deals with integral->integral conversion.
2033 bool CastInst::isIntegerCast() const {
2034   switch (getOpcode()) {
2035     default: return false;
2036     case Instruction::ZExt:
2037     case Instruction::SExt:
2038     case Instruction::Trunc:
2039       return true;
2040     case Instruction::BitCast:
2041       return getOperand(0)->getType()->isIntegerTy() &&
2042         getType()->isIntegerTy();
2043   }
2044 }
2045
2046 bool CastInst::isLosslessCast() const {
2047   // Only BitCast can be lossless, exit fast if we're not BitCast
2048   if (getOpcode() != Instruction::BitCast)
2049     return false;
2050
2051   // Identity cast is always lossless
2052   Type* SrcTy = getOperand(0)->getType();
2053   Type* DstTy = getType();
2054   if (SrcTy == DstTy)
2055     return true;
2056   
2057   // Pointer to pointer is always lossless.
2058   if (SrcTy->isPointerTy())
2059     return DstTy->isPointerTy();
2060   return false;  // Other types have no identity values
2061 }
2062
2063 /// This function determines if the CastInst does not require any bits to be
2064 /// changed in order to effect the cast. Essentially, it identifies cases where
2065 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
2066 /// example, the following are all no-op casts:
2067 /// # bitcast i32* %x to i8*
2068 /// # bitcast <2 x i32> %x to <4 x i16> 
2069 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
2070 /// @brief Determine if the described cast is a no-op.
2071 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2072                           Type *SrcTy,
2073                           Type *DestTy,
2074                           Type *IntPtrTy) {
2075   switch (Opcode) {
2076     default:
2077       assert(0 && "Invalid CastOp");
2078     case Instruction::Trunc:
2079     case Instruction::ZExt:
2080     case Instruction::SExt: 
2081     case Instruction::FPTrunc:
2082     case Instruction::FPExt:
2083     case Instruction::UIToFP:
2084     case Instruction::SIToFP:
2085     case Instruction::FPToUI:
2086     case Instruction::FPToSI:
2087       return false; // These always modify bits
2088     case Instruction::BitCast:
2089       return true;  // BitCast never modifies bits.
2090     case Instruction::PtrToInt:
2091       return IntPtrTy->getScalarSizeInBits() ==
2092              DestTy->getScalarSizeInBits();
2093     case Instruction::IntToPtr:
2094       return IntPtrTy->getScalarSizeInBits() ==
2095              SrcTy->getScalarSizeInBits();
2096   }
2097 }
2098
2099 /// @brief Determine if a cast is a no-op.
2100 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2101   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2102 }
2103
2104 /// This function determines if a pair of casts can be eliminated and what 
2105 /// opcode should be used in the elimination. This assumes that there are two 
2106 /// instructions like this:
2107 /// *  %F = firstOpcode SrcTy %x to MidTy
2108 /// *  %S = secondOpcode MidTy %F to DstTy
2109 /// The function returns a resultOpcode so these two casts can be replaced with:
2110 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
2111 /// If no such cast is permited, the function returns 0.
2112 unsigned CastInst::isEliminableCastPair(
2113   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2114   Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy) {
2115   // Define the 144 possibilities for these two cast instructions. The values
2116   // in this matrix determine what to do in a given situation and select the
2117   // case in the switch below.  The rows correspond to firstOp, the columns 
2118   // correspond to secondOp.  In looking at the table below, keep in  mind
2119   // the following cast properties:
2120   //
2121   //          Size Compare       Source               Destination
2122   // Operator  Src ? Size   Type       Sign         Type       Sign
2123   // -------- ------------ -------------------   ---------------------
2124   // TRUNC         >       Integer      Any        Integral     Any
2125   // ZEXT          <       Integral   Unsigned     Integer      Any
2126   // SEXT          <       Integral    Signed      Integer      Any
2127   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
2128   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed 
2129   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a   
2130   // SITOFP       n/a      Integral    Signed      FloatPt      n/a   
2131   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a   
2132   // FPEXT         <       FloatPt      n/a        FloatPt      n/a   
2133   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
2134   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
2135   // BITCAST       =       FirstClass   n/a       FirstClass    n/a   
2136   //
2137   // NOTE: some transforms are safe, but we consider them to be non-profitable.
2138   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2139   // into "fptoui double to i64", but this loses information about the range
2140   // of the produced value (we no longer know the top-part is all zeros). 
2141   // Further this conversion is often much more expensive for typical hardware,
2142   // and causes issues when building libgcc.  We disallow fptosi+sext for the 
2143   // same reason.
2144   const unsigned numCastOps = 
2145     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2146   static const uint8_t CastResults[numCastOps][numCastOps] = {
2147     // T        F  F  U  S  F  F  P  I  B   -+
2148     // R  Z  S  P  P  I  I  T  P  2  N  T    |
2149     // U  E  E  2  2  2  2  R  E  I  T  C    +- secondOp
2150     // N  X  X  U  S  F  F  N  X  N  2  V    |
2151     // C  T  T  I  I  P  P  C  T  T  P  T   -+
2152     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc      -+
2153     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt        |
2154     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt        |
2155     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI      |
2156     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI      |
2157     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP      +- firstOp
2158     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP      |
2159     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc     |
2160     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt       |
2161     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt    |
2162     { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr    |
2163     {  5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast    -+
2164   };
2165   
2166   // If either of the casts are a bitcast from scalar to vector, disallow the
2167   // merging. However, bitcast of A->B->A are allowed.
2168   bool isFirstBitcast  = (firstOp == Instruction::BitCast);
2169   bool isSecondBitcast = (secondOp == Instruction::BitCast);
2170   bool chainedBitcast  = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2171
2172   // Check if any of the bitcasts convert scalars<->vectors.
2173   if ((isFirstBitcast  && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2174       (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2175     // Unless we are bitcasing to the original type, disallow optimizations.
2176     if (!chainedBitcast) return 0;
2177
2178   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2179                             [secondOp-Instruction::CastOpsBegin];
2180   switch (ElimCase) {
2181     case 0: 
2182       // categorically disallowed
2183       return 0;
2184     case 1: 
2185       // allowed, use first cast's opcode
2186       return firstOp;
2187     case 2: 
2188       // allowed, use second cast's opcode
2189       return secondOp;
2190     case 3: 
2191       // no-op cast in second op implies firstOp as long as the DestTy 
2192       // is integer and we are not converting between a vector and a
2193       // non vector type.
2194       if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2195         return firstOp;
2196       return 0;
2197     case 4:
2198       // no-op cast in second op implies firstOp as long as the DestTy
2199       // is floating point.
2200       if (DstTy->isFloatingPointTy())
2201         return firstOp;
2202       return 0;
2203     case 5: 
2204       // no-op cast in first op implies secondOp as long as the SrcTy
2205       // is an integer.
2206       if (SrcTy->isIntegerTy())
2207         return secondOp;
2208       return 0;
2209     case 6:
2210       // no-op cast in first op implies secondOp as long as the SrcTy
2211       // is a floating point.
2212       if (SrcTy->isFloatingPointTy())
2213         return secondOp;
2214       return 0;
2215     case 7: { 
2216       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2217       if (!IntPtrTy)
2218         return 0;
2219       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2220       unsigned MidSize = MidTy->getScalarSizeInBits();
2221       if (MidSize >= PtrSize)
2222         return Instruction::BitCast;
2223       return 0;
2224     }
2225     case 8: {
2226       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
2227       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
2228       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
2229       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2230       unsigned DstSize = DstTy->getScalarSizeInBits();
2231       if (SrcSize == DstSize)
2232         return Instruction::BitCast;
2233       else if (SrcSize < DstSize)
2234         return firstOp;
2235       return secondOp;
2236     }
2237     case 9: // zext, sext -> zext, because sext can't sign extend after zext
2238       return Instruction::ZExt;
2239     case 10:
2240       // fpext followed by ftrunc is allowed if the bit size returned to is
2241       // the same as the original, in which case its just a bitcast
2242       if (SrcTy == DstTy)
2243         return Instruction::BitCast;
2244       return 0; // If the types are not the same we can't eliminate it.
2245     case 11:
2246       // bitcast followed by ptrtoint is allowed as long as the bitcast
2247       // is a pointer to pointer cast.
2248       if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2249         return secondOp;
2250       return 0;
2251     case 12:
2252       // inttoptr, bitcast -> intptr  if bitcast is a ptr to ptr cast
2253       if (MidTy->isPointerTy() && DstTy->isPointerTy())
2254         return firstOp;
2255       return 0;
2256     case 13: {
2257       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2258       if (!IntPtrTy)
2259         return 0;
2260       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2261       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2262       unsigned DstSize = DstTy->getScalarSizeInBits();
2263       if (SrcSize <= PtrSize && SrcSize == DstSize)
2264         return Instruction::BitCast;
2265       return 0;
2266     }
2267     case 99: 
2268       // cast combination can't happen (error in input). This is for all cases
2269       // where the MidTy is not the same for the two cast instructions.
2270       assert(0 && "Invalid Cast Combination");
2271       return 0;
2272     default:
2273       assert(0 && "Error in CastResults table!!!");
2274       return 0;
2275   }
2276   return 0;
2277 }
2278
2279 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 
2280   const Twine &Name, Instruction *InsertBefore) {
2281   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2282   // Construct and return the appropriate CastInst subclass
2283   switch (op) {
2284     case Trunc:    return new TruncInst    (S, Ty, Name, InsertBefore);
2285     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertBefore);
2286     case SExt:     return new SExtInst     (S, Ty, Name, InsertBefore);
2287     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertBefore);
2288     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertBefore);
2289     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertBefore);
2290     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertBefore);
2291     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertBefore);
2292     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertBefore);
2293     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2294     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2295     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertBefore);
2296     default:
2297       assert(0 && "Invalid opcode provided");
2298   }
2299   return 0;
2300 }
2301
2302 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2303   const Twine &Name, BasicBlock *InsertAtEnd) {
2304   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2305   // Construct and return the appropriate CastInst subclass
2306   switch (op) {
2307     case Trunc:    return new TruncInst    (S, Ty, Name, InsertAtEnd);
2308     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertAtEnd);
2309     case SExt:     return new SExtInst     (S, Ty, Name, InsertAtEnd);
2310     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertAtEnd);
2311     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertAtEnd);
2312     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertAtEnd);
2313     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertAtEnd);
2314     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertAtEnd);
2315     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertAtEnd);
2316     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2317     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2318     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertAtEnd);
2319     default:
2320       assert(0 && "Invalid opcode provided");
2321   }
2322   return 0;
2323 }
2324
2325 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
2326                                         const Twine &Name,
2327                                         Instruction *InsertBefore) {
2328   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2329     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2330   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2331 }
2332
2333 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
2334                                         const Twine &Name,
2335                                         BasicBlock *InsertAtEnd) {
2336   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2337     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2338   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2339 }
2340
2341 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
2342                                         const Twine &Name,
2343                                         Instruction *InsertBefore) {
2344   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2345     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2346   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2347 }
2348
2349 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
2350                                         const Twine &Name,
2351                                         BasicBlock *InsertAtEnd) {
2352   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2353     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2354   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2355 }
2356
2357 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2358                                          const Twine &Name,
2359                                          Instruction *InsertBefore) {
2360   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2361     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2362   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2363 }
2364
2365 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2366                                          const Twine &Name, 
2367                                          BasicBlock *InsertAtEnd) {
2368   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2369     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2370   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2371 }
2372
2373 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2374                                       const Twine &Name,
2375                                       BasicBlock *InsertAtEnd) {
2376   assert(S->getType()->isPointerTy() && "Invalid cast");
2377   assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2378          "Invalid cast");
2379
2380   if (Ty->isIntegerTy())
2381     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2382   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2383 }
2384
2385 /// @brief Create a BitCast or a PtrToInt cast instruction
2386 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 
2387                                       const Twine &Name, 
2388                                       Instruction *InsertBefore) {
2389   assert(S->getType()->isPointerTy() && "Invalid cast");
2390   assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2391          "Invalid cast");
2392
2393   if (Ty->isIntegerTy())
2394     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2395   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2396 }
2397
2398 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 
2399                                       bool isSigned, const Twine &Name,
2400                                       Instruction *InsertBefore) {
2401   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2402          "Invalid integer cast");
2403   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2404   unsigned DstBits = Ty->getScalarSizeInBits();
2405   Instruction::CastOps opcode =
2406     (SrcBits == DstBits ? Instruction::BitCast :
2407      (SrcBits > DstBits ? Instruction::Trunc :
2408       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2409   return Create(opcode, C, Ty, Name, InsertBefore);
2410 }
2411
2412 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 
2413                                       bool isSigned, const Twine &Name,
2414                                       BasicBlock *InsertAtEnd) {
2415   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2416          "Invalid cast");
2417   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2418   unsigned DstBits = Ty->getScalarSizeInBits();
2419   Instruction::CastOps opcode =
2420     (SrcBits == DstBits ? Instruction::BitCast :
2421      (SrcBits > DstBits ? Instruction::Trunc :
2422       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2423   return Create(opcode, C, Ty, Name, InsertAtEnd);
2424 }
2425
2426 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
2427                                  const Twine &Name, 
2428                                  Instruction *InsertBefore) {
2429   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2430          "Invalid cast");
2431   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2432   unsigned DstBits = Ty->getScalarSizeInBits();
2433   Instruction::CastOps opcode =
2434     (SrcBits == DstBits ? Instruction::BitCast :
2435      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2436   return Create(opcode, C, Ty, Name, InsertBefore);
2437 }
2438
2439 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
2440                                  const Twine &Name, 
2441                                  BasicBlock *InsertAtEnd) {
2442   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2443          "Invalid cast");
2444   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2445   unsigned DstBits = Ty->getScalarSizeInBits();
2446   Instruction::CastOps opcode =
2447     (SrcBits == DstBits ? Instruction::BitCast :
2448      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2449   return Create(opcode, C, Ty, Name, InsertAtEnd);
2450 }
2451
2452 // Check whether it is valid to call getCastOpcode for these types.
2453 // This routine must be kept in sync with getCastOpcode.
2454 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2455   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2456     return false;
2457
2458   if (SrcTy == DestTy)
2459     return true;
2460
2461   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2462     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2463       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2464         // An element by element cast.  Valid if casting the elements is valid.
2465         SrcTy = SrcVecTy->getElementType();
2466         DestTy = DestVecTy->getElementType();
2467       }
2468
2469   // Get the bit sizes, we'll need these
2470   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2471   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2472
2473   // Run through the possibilities ...
2474   if (DestTy->isIntegerTy()) {               // Casting to integral
2475     if (SrcTy->isIntegerTy()) {                // Casting from integral
2476         return true;
2477     } else if (SrcTy->isFloatingPointTy()) {   // Casting from floating pt
2478       return true;
2479     } else if (SrcTy->isVectorTy()) {          // Casting from vector
2480       return DestBits == SrcBits;
2481     } else {                                   // Casting from something else
2482       return SrcTy->isPointerTy();
2483     }
2484   } else if (DestTy->isFloatingPointTy()) {  // Casting to floating pt
2485     if (SrcTy->isIntegerTy()) {                // Casting from integral
2486       return true;
2487     } else if (SrcTy->isFloatingPointTy()) {   // Casting from floating pt
2488       return true;
2489     } else if (SrcTy->isVectorTy()) {          // Casting from vector
2490       return DestBits == SrcBits;
2491     } else {                                   // Casting from something else
2492       return false;
2493     }
2494   } else if (DestTy->isVectorTy()) {         // Casting to vector
2495     return DestBits == SrcBits;
2496   } else if (DestTy->isPointerTy()) {        // Casting to pointer
2497     if (SrcTy->isPointerTy()) {                // Casting from pointer
2498       return true;
2499     } else if (SrcTy->isIntegerTy()) {         // Casting from integral
2500       return true;
2501     } else {                                   // Casting from something else
2502       return false;
2503     }
2504   } else if (DestTy->isX86_MMXTy()) {
2505     if (SrcTy->isVectorTy()) {
2506       return DestBits == SrcBits;       // 64-bit vector to MMX
2507     } else {
2508       return false;
2509     }
2510   } else {                                   // Casting to something else
2511     return false;
2512   }
2513 }
2514
2515 // Provide a way to get a "cast" where the cast opcode is inferred from the 
2516 // types and size of the operand. This, basically, is a parallel of the 
2517 // logic in the castIsValid function below.  This axiom should hold:
2518 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2519 // should not assert in castIsValid. In other words, this produces a "correct"
2520 // casting opcode for the arguments passed to it.
2521 // This routine must be kept in sync with isCastable.
2522 Instruction::CastOps
2523 CastInst::getCastOpcode(
2524   const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2525   Type *SrcTy = Src->getType();
2526
2527   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2528          "Only first class types are castable!");
2529
2530   if (SrcTy == DestTy)
2531     return BitCast;
2532
2533   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2534     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2535       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2536         // An element by element cast.  Find the appropriate opcode based on the
2537         // element types.
2538         SrcTy = SrcVecTy->getElementType();
2539         DestTy = DestVecTy->getElementType();
2540       }
2541
2542   // Get the bit sizes, we'll need these
2543   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2544   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2545
2546   // Run through the possibilities ...
2547   if (DestTy->isIntegerTy()) {                      // Casting to integral
2548     if (SrcTy->isIntegerTy()) {                     // Casting from integral
2549       if (DestBits < SrcBits)
2550         return Trunc;                               // int -> smaller int
2551       else if (DestBits > SrcBits) {                // its an extension
2552         if (SrcIsSigned)
2553           return SExt;                              // signed -> SEXT
2554         else
2555           return ZExt;                              // unsigned -> ZEXT
2556       } else {
2557         return BitCast;                             // Same size, No-op cast
2558       }
2559     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
2560       if (DestIsSigned) 
2561         return FPToSI;                              // FP -> sint
2562       else
2563         return FPToUI;                              // FP -> uint 
2564     } else if (SrcTy->isVectorTy()) {
2565       assert(DestBits == SrcBits &&
2566              "Casting vector to integer of different width");
2567       return BitCast;                             // Same size, no-op cast
2568     } else {
2569       assert(SrcTy->isPointerTy() &&
2570              "Casting from a value that is not first-class type");
2571       return PtrToInt;                              // ptr -> int
2572     }
2573   } else if (DestTy->isFloatingPointTy()) {         // Casting to floating pt
2574     if (SrcTy->isIntegerTy()) {                     // Casting from integral
2575       if (SrcIsSigned)
2576         return SIToFP;                              // sint -> FP
2577       else
2578         return UIToFP;                              // uint -> FP
2579     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
2580       if (DestBits < SrcBits) {
2581         return FPTrunc;                             // FP -> smaller FP
2582       } else if (DestBits > SrcBits) {
2583         return FPExt;                               // FP -> larger FP
2584       } else  {
2585         return BitCast;                             // same size, no-op cast
2586       }
2587     } else if (SrcTy->isVectorTy()) {
2588       assert(DestBits == SrcBits &&
2589              "Casting vector to floating point of different width");
2590       return BitCast;                             // same size, no-op cast
2591     } else {
2592       llvm_unreachable("Casting pointer or non-first class to float");
2593     }
2594   } else if (DestTy->isVectorTy()) {
2595     assert(DestBits == SrcBits &&
2596            "Illegal cast to vector (wrong type or size)");
2597     return BitCast;
2598   } else if (DestTy->isPointerTy()) {
2599     if (SrcTy->isPointerTy()) {
2600       return BitCast;                               // ptr -> ptr
2601     } else if (SrcTy->isIntegerTy()) {
2602       return IntToPtr;                              // int -> ptr
2603     } else {
2604       assert(0 && "Casting pointer to other than pointer or int");
2605     }
2606   } else if (DestTy->isX86_MMXTy()) {
2607     if (SrcTy->isVectorTy()) {
2608       assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2609       return BitCast;                               // 64-bit vector to MMX
2610     } else {
2611       assert(0 && "Illegal cast to X86_MMX");
2612     }
2613   } else {
2614     assert(0 && "Casting to type that is not first-class");
2615   }
2616
2617   // If we fall through to here we probably hit an assertion cast above
2618   // and assertions are not turned on. Anything we return is an error, so
2619   // BitCast is as good a choice as any.
2620   return BitCast;
2621 }
2622
2623 //===----------------------------------------------------------------------===//
2624 //                    CastInst SubClass Constructors
2625 //===----------------------------------------------------------------------===//
2626
2627 /// Check that the construction parameters for a CastInst are correct. This
2628 /// could be broken out into the separate constructors but it is useful to have
2629 /// it in one place and to eliminate the redundant code for getting the sizes
2630 /// of the types involved.
2631 bool 
2632 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2633
2634   // Check for type sanity on the arguments
2635   Type *SrcTy = S->getType();
2636   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2637       SrcTy->isAggregateType() || DstTy->isAggregateType())
2638     return false;
2639
2640   // Get the size of the types in bits, we'll need this later
2641   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2642   unsigned DstBitSize = DstTy->getScalarSizeInBits();
2643
2644   // If these are vector types, get the lengths of the vectors (using zero for
2645   // scalar types means that checking that vector lengths match also checks that
2646   // scalars are not being converted to vectors or vectors to scalars).
2647   unsigned SrcLength = SrcTy->isVectorTy() ?
2648     cast<VectorType>(SrcTy)->getNumElements() : 0;
2649   unsigned DstLength = DstTy->isVectorTy() ?
2650     cast<VectorType>(DstTy)->getNumElements() : 0;
2651
2652   // Switch on the opcode provided
2653   switch (op) {
2654   default: return false; // This is an input error
2655   case Instruction::Trunc:
2656     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2657       SrcLength == DstLength && SrcBitSize > DstBitSize;
2658   case Instruction::ZExt:
2659     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2660       SrcLength == DstLength && SrcBitSize < DstBitSize;
2661   case Instruction::SExt: 
2662     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2663       SrcLength == DstLength && SrcBitSize < DstBitSize;
2664   case Instruction::FPTrunc:
2665     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2666       SrcLength == DstLength && SrcBitSize > DstBitSize;
2667   case Instruction::FPExt:
2668     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2669       SrcLength == DstLength && SrcBitSize < DstBitSize;
2670   case Instruction::UIToFP:
2671   case Instruction::SIToFP:
2672     return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2673       SrcLength == DstLength;
2674   case Instruction::FPToUI:
2675   case Instruction::FPToSI:
2676     return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2677       SrcLength == DstLength;
2678   case Instruction::PtrToInt:
2679     if (SrcTy->getNumElements() != DstTy->getNumElements())
2680       return false;
2681     return SrcTy->getScalarType()->isPointerTy() &&
2682            DstTy->getScalarType()->isIntegerTy();
2683   case Instruction::IntToPtr:
2684     if (SrcTy->getNumElements() != DstTy->getNumElements())
2685       return false;
2686     return SrcTy->getScalarType()->isIntegerTy() &&
2687            DstTy->getScalarType()->isPointerTy();
2688   case Instruction::BitCast:
2689     // BitCast implies a no-op cast of type only. No bits change.
2690     // However, you can't cast pointers to anything but pointers.
2691     if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2692       return false;
2693
2694     // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2695     // these cases, the cast is okay if the source and destination bit widths
2696     // are identical.
2697     return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2698   }
2699 }
2700
2701 TruncInst::TruncInst(
2702   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2703 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2704   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2705 }
2706
2707 TruncInst::TruncInst(
2708   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2709 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
2710   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2711 }
2712
2713 ZExtInst::ZExtInst(
2714   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2715 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
2716   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2717 }
2718
2719 ZExtInst::ZExtInst(
2720   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2721 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
2722   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2723 }
2724 SExtInst::SExtInst(
2725   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2726 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
2727   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2728 }
2729
2730 SExtInst::SExtInst(
2731   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2732 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
2733   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2734 }
2735
2736 FPTruncInst::FPTruncInst(
2737   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2738 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
2739   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2740 }
2741
2742 FPTruncInst::FPTruncInst(
2743   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2744 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
2745   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2746 }
2747
2748 FPExtInst::FPExtInst(
2749   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2750 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
2751   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2752 }
2753
2754 FPExtInst::FPExtInst(
2755   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2756 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
2757   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2758 }
2759
2760 UIToFPInst::UIToFPInst(
2761   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2762 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
2763   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2764 }
2765
2766 UIToFPInst::UIToFPInst(
2767   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2768 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
2769   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2770 }
2771
2772 SIToFPInst::SIToFPInst(
2773   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2774 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
2775   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2776 }
2777
2778 SIToFPInst::SIToFPInst(
2779   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2780 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
2781   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2782 }
2783
2784 FPToUIInst::FPToUIInst(
2785   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2786 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
2787   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2788 }
2789
2790 FPToUIInst::FPToUIInst(
2791   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2792 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
2793   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2794 }
2795
2796 FPToSIInst::FPToSIInst(
2797   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2798 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
2799   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2800 }
2801
2802 FPToSIInst::FPToSIInst(
2803   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2804 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
2805   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2806 }
2807
2808 PtrToIntInst::PtrToIntInst(
2809   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2810 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
2811   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2812 }
2813
2814 PtrToIntInst::PtrToIntInst(
2815   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2816 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
2817   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2818 }
2819
2820 IntToPtrInst::IntToPtrInst(
2821   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2822 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
2823   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2824 }
2825
2826 IntToPtrInst::IntToPtrInst(
2827   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2828 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
2829   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2830 }
2831
2832 BitCastInst::BitCastInst(
2833   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2834 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
2835   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2836 }
2837
2838 BitCastInst::BitCastInst(
2839   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2840 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
2841   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2842 }
2843
2844 //===----------------------------------------------------------------------===//
2845 //                               CmpInst Classes
2846 //===----------------------------------------------------------------------===//
2847
2848 void CmpInst::Anchor() const {}
2849
2850 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2851                  Value *LHS, Value *RHS, const Twine &Name,
2852                  Instruction *InsertBefore)
2853   : Instruction(ty, op,
2854                 OperandTraits<CmpInst>::op_begin(this),
2855                 OperandTraits<CmpInst>::operands(this),
2856                 InsertBefore) {
2857     Op<0>() = LHS;
2858     Op<1>() = RHS;
2859   setPredicate((Predicate)predicate);
2860   setName(Name);
2861 }
2862
2863 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2864                  Value *LHS, Value *RHS, const Twine &Name,
2865                  BasicBlock *InsertAtEnd)
2866   : Instruction(ty, op,
2867                 OperandTraits<CmpInst>::op_begin(this),
2868                 OperandTraits<CmpInst>::operands(this),
2869                 InsertAtEnd) {
2870   Op<0>() = LHS;
2871   Op<1>() = RHS;
2872   setPredicate((Predicate)predicate);
2873   setName(Name);
2874 }
2875
2876 CmpInst *
2877 CmpInst::Create(OtherOps Op, unsigned short predicate,
2878                 Value *S1, Value *S2, 
2879                 const Twine &Name, Instruction *InsertBefore) {
2880   if (Op == Instruction::ICmp) {
2881     if (InsertBefore)
2882       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2883                           S1, S2, Name);
2884     else
2885       return new ICmpInst(CmpInst::Predicate(predicate),
2886                           S1, S2, Name);
2887   }
2888   
2889   if (InsertBefore)
2890     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2891                         S1, S2, Name);
2892   else
2893     return new FCmpInst(CmpInst::Predicate(predicate),
2894                         S1, S2, Name);
2895 }
2896
2897 CmpInst *
2898 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
2899                 const Twine &Name, BasicBlock *InsertAtEnd) {
2900   if (Op == Instruction::ICmp) {
2901     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2902                         S1, S2, Name);
2903   }
2904   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2905                       S1, S2, Name);
2906 }
2907
2908 void CmpInst::swapOperands() {
2909   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2910     IC->swapOperands();
2911   else
2912     cast<FCmpInst>(this)->swapOperands();
2913 }
2914
2915 bool CmpInst::isCommutative() const {
2916   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2917     return IC->isCommutative();
2918   return cast<FCmpInst>(this)->isCommutative();
2919 }
2920
2921 bool CmpInst::isEquality() const {
2922   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2923     return IC->isEquality();
2924   return cast<FCmpInst>(this)->isEquality();
2925 }
2926
2927
2928 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2929   switch (pred) {
2930     default: assert(0 && "Unknown cmp predicate!");
2931     case ICMP_EQ: return ICMP_NE;
2932     case ICMP_NE: return ICMP_EQ;
2933     case ICMP_UGT: return ICMP_ULE;
2934     case ICMP_ULT: return ICMP_UGE;
2935     case ICMP_UGE: return ICMP_ULT;
2936     case ICMP_ULE: return ICMP_UGT;
2937     case ICMP_SGT: return ICMP_SLE;
2938     case ICMP_SLT: return ICMP_SGE;
2939     case ICMP_SGE: return ICMP_SLT;
2940     case ICMP_SLE: return ICMP_SGT;
2941
2942     case FCMP_OEQ: return FCMP_UNE;
2943     case FCMP_ONE: return FCMP_UEQ;
2944     case FCMP_OGT: return FCMP_ULE;
2945     case FCMP_OLT: return FCMP_UGE;
2946     case FCMP_OGE: return FCMP_ULT;
2947     case FCMP_OLE: return FCMP_UGT;
2948     case FCMP_UEQ: return FCMP_ONE;
2949     case FCMP_UNE: return FCMP_OEQ;
2950     case FCMP_UGT: return FCMP_OLE;
2951     case FCMP_ULT: return FCMP_OGE;
2952     case FCMP_UGE: return FCMP_OLT;
2953     case FCMP_ULE: return FCMP_OGT;
2954     case FCMP_ORD: return FCMP_UNO;
2955     case FCMP_UNO: return FCMP_ORD;
2956     case FCMP_TRUE: return FCMP_FALSE;
2957     case FCMP_FALSE: return FCMP_TRUE;
2958   }
2959 }
2960
2961 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2962   switch (pred) {
2963     default: assert(0 && "Unknown icmp predicate!");
2964     case ICMP_EQ: case ICMP_NE: 
2965     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2966        return pred;
2967     case ICMP_UGT: return ICMP_SGT;
2968     case ICMP_ULT: return ICMP_SLT;
2969     case ICMP_UGE: return ICMP_SGE;
2970     case ICMP_ULE: return ICMP_SLE;
2971   }
2972 }
2973
2974 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2975   switch (pred) {
2976     default: assert(0 && "Unknown icmp predicate!");
2977     case ICMP_EQ: case ICMP_NE: 
2978     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 
2979        return pred;
2980     case ICMP_SGT: return ICMP_UGT;
2981     case ICMP_SLT: return ICMP_ULT;
2982     case ICMP_SGE: return ICMP_UGE;
2983     case ICMP_SLE: return ICMP_ULE;
2984   }
2985 }
2986
2987 /// Initialize a set of values that all satisfy the condition with C.
2988 ///
2989 ConstantRange 
2990 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2991   APInt Lower(C);
2992   APInt Upper(C);
2993   uint32_t BitWidth = C.getBitWidth();
2994   switch (pred) {
2995   default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2996   case ICmpInst::ICMP_EQ: Upper++; break;
2997   case ICmpInst::ICMP_NE: Lower++; break;
2998   case ICmpInst::ICMP_ULT:
2999     Lower = APInt::getMinValue(BitWidth);
3000     // Check for an empty-set condition.
3001     if (Lower == Upper)
3002       return ConstantRange(BitWidth, /*isFullSet=*/false);
3003     break;
3004   case ICmpInst::ICMP_SLT:
3005     Lower = APInt::getSignedMinValue(BitWidth);
3006     // Check for an empty-set condition.
3007     if (Lower == Upper)
3008       return ConstantRange(BitWidth, /*isFullSet=*/false);
3009     break;
3010   case ICmpInst::ICMP_UGT: 
3011     Lower++; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
3012     // Check for an empty-set condition.
3013     if (Lower == Upper)
3014       return ConstantRange(BitWidth, /*isFullSet=*/false);
3015     break;
3016   case ICmpInst::ICMP_SGT:
3017     Lower++; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
3018     // Check for an empty-set condition.
3019     if (Lower == Upper)
3020       return ConstantRange(BitWidth, /*isFullSet=*/false);
3021     break;
3022   case ICmpInst::ICMP_ULE: 
3023     Lower = APInt::getMinValue(BitWidth); Upper++; 
3024     // Check for a full-set condition.
3025     if (Lower == Upper)
3026       return ConstantRange(BitWidth, /*isFullSet=*/true);
3027     break;
3028   case ICmpInst::ICMP_SLE: 
3029     Lower = APInt::getSignedMinValue(BitWidth); Upper++; 
3030     // Check for a full-set condition.
3031     if (Lower == Upper)
3032       return ConstantRange(BitWidth, /*isFullSet=*/true);
3033     break;
3034   case ICmpInst::ICMP_UGE:
3035     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
3036     // Check for a full-set condition.
3037     if (Lower == Upper)
3038       return ConstantRange(BitWidth, /*isFullSet=*/true);
3039     break;
3040   case ICmpInst::ICMP_SGE:
3041     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
3042     // Check for a full-set condition.
3043     if (Lower == Upper)
3044       return ConstantRange(BitWidth, /*isFullSet=*/true);
3045     break;
3046   }
3047   return ConstantRange(Lower, Upper);
3048 }
3049
3050 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3051   switch (pred) {
3052     default: assert(0 && "Unknown cmp predicate!");
3053     case ICMP_EQ: case ICMP_NE:
3054       return pred;
3055     case ICMP_SGT: return ICMP_SLT;
3056     case ICMP_SLT: return ICMP_SGT;
3057     case ICMP_SGE: return ICMP_SLE;
3058     case ICMP_SLE: return ICMP_SGE;
3059     case ICMP_UGT: return ICMP_ULT;
3060     case ICMP_ULT: return ICMP_UGT;
3061     case ICMP_UGE: return ICMP_ULE;
3062     case ICMP_ULE: return ICMP_UGE;
3063   
3064     case FCMP_FALSE: case FCMP_TRUE:
3065     case FCMP_OEQ: case FCMP_ONE:
3066     case FCMP_UEQ: case FCMP_UNE:
3067     case FCMP_ORD: case FCMP_UNO:
3068       return pred;
3069     case FCMP_OGT: return FCMP_OLT;
3070     case FCMP_OLT: return FCMP_OGT;
3071     case FCMP_OGE: return FCMP_OLE;
3072     case FCMP_OLE: return FCMP_OGE;
3073     case FCMP_UGT: return FCMP_ULT;
3074     case FCMP_ULT: return FCMP_UGT;
3075     case FCMP_UGE: return FCMP_ULE;
3076     case FCMP_ULE: return FCMP_UGE;
3077   }
3078 }
3079
3080 bool CmpInst::isUnsigned(unsigned short predicate) {
3081   switch (predicate) {
3082     default: return false;
3083     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
3084     case ICmpInst::ICMP_UGE: return true;
3085   }
3086 }
3087
3088 bool CmpInst::isSigned(unsigned short predicate) {
3089   switch (predicate) {
3090     default: return false;
3091     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
3092     case ICmpInst::ICMP_SGE: return true;
3093   }
3094 }
3095
3096 bool CmpInst::isOrdered(unsigned short predicate) {
3097   switch (predicate) {
3098     default: return false;
3099     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
3100     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
3101     case FCmpInst::FCMP_ORD: return true;
3102   }
3103 }
3104       
3105 bool CmpInst::isUnordered(unsigned short predicate) {
3106   switch (predicate) {
3107     default: return false;
3108     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
3109     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
3110     case FCmpInst::FCMP_UNO: return true;
3111   }
3112 }
3113
3114 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3115   switch(predicate) {
3116     default: return false;
3117     case ICMP_EQ:   case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3118     case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3119   }
3120 }
3121
3122 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3123   switch(predicate) {
3124   case ICMP_NE:    case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3125   case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3126   default: return false;
3127   }
3128 }
3129
3130
3131 //===----------------------------------------------------------------------===//
3132 //                        SwitchInst Implementation
3133 //===----------------------------------------------------------------------===//
3134
3135 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3136   assert(Value && Default && NumReserved);
3137   ReservedSpace = NumReserved;
3138   NumOperands = 2;
3139   OperandList = allocHungoffUses(ReservedSpace);
3140
3141   OperandList[0] = Value;
3142   OperandList[1] = Default;
3143 }
3144
3145 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3146 /// switch on and a default destination.  The number of additional cases can
3147 /// be specified here to make memory allocation more efficient.  This
3148 /// constructor can also autoinsert before another instruction.
3149 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3150                        Instruction *InsertBefore)
3151   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3152                    0, 0, InsertBefore) {
3153   init(Value, Default, 2+NumCases*2);
3154 }
3155
3156 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3157 /// switch on and a default destination.  The number of additional cases can
3158 /// be specified here to make memory allocation more efficient.  This
3159 /// constructor also autoinserts at the end of the specified BasicBlock.
3160 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3161                        BasicBlock *InsertAtEnd)
3162   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3163                    0, 0, InsertAtEnd) {
3164   init(Value, Default, 2+NumCases*2);
3165 }
3166
3167 SwitchInst::SwitchInst(const SwitchInst &SI)
3168   : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3169   init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3170   NumOperands = SI.getNumOperands();
3171   Use *OL = OperandList, *InOL = SI.OperandList;
3172   for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3173     OL[i] = InOL[i];
3174     OL[i+1] = InOL[i+1];
3175   }
3176   SubclassOptionalData = SI.SubclassOptionalData;
3177 }
3178
3179 SwitchInst::~SwitchInst() {
3180   dropHungoffUses();
3181 }
3182
3183
3184 /// addCase - Add an entry to the switch instruction...
3185 ///
3186 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3187   unsigned OpNo = NumOperands;
3188   if (OpNo+2 > ReservedSpace)
3189     growOperands();  // Get more space!
3190   // Initialize some new operands.
3191   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3192   NumOperands = OpNo+2;
3193   OperandList[OpNo] = OnVal;
3194   OperandList[OpNo+1] = Dest;
3195 }
3196
3197 /// removeCase - This method removes the specified successor from the switch
3198 /// instruction.  Note that this cannot be used to remove the default
3199 /// destination (successor #0).
3200 ///
3201 void SwitchInst::removeCase(unsigned idx) {
3202   assert(idx != 0 && "Cannot remove the default case!");
3203   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3204
3205   unsigned NumOps = getNumOperands();
3206   Use *OL = OperandList;
3207
3208   // Overwrite this case with the end of the list.
3209   if ((idx + 1) * 2 != NumOps) {
3210     OL[idx * 2] = OL[NumOps - 2];
3211     OL[idx * 2 + 1] = OL[NumOps - 1];
3212   }
3213
3214   // Nuke the last value.
3215   OL[NumOps-2].set(0);
3216   OL[NumOps-2+1].set(0);
3217   NumOperands = NumOps-2;
3218 }
3219
3220 /// growOperands - grow operands - This grows the operand list in response
3221 /// to a push_back style of operation.  This grows the number of ops by 3 times.
3222 ///
3223 void SwitchInst::growOperands() {
3224   unsigned e = getNumOperands();
3225   unsigned NumOps = e*3;
3226
3227   ReservedSpace = NumOps;
3228   Use *NewOps = allocHungoffUses(NumOps);
3229   Use *OldOps = OperandList;
3230   for (unsigned i = 0; i != e; ++i) {
3231       NewOps[i] = OldOps[i];
3232   }
3233   OperandList = NewOps;
3234   Use::zap(OldOps, OldOps + e, true);
3235 }
3236
3237
3238 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3239   return getSuccessor(idx);
3240 }
3241 unsigned SwitchInst::getNumSuccessorsV() const {
3242   return getNumSuccessors();
3243 }
3244 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3245   setSuccessor(idx, B);
3246 }
3247
3248 //===----------------------------------------------------------------------===//
3249 //                        IndirectBrInst Implementation
3250 //===----------------------------------------------------------------------===//
3251
3252 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3253   assert(Address && Address->getType()->isPointerTy() &&
3254          "Address of indirectbr must be a pointer");
3255   ReservedSpace = 1+NumDests;
3256   NumOperands = 1;
3257   OperandList = allocHungoffUses(ReservedSpace);
3258   
3259   OperandList[0] = Address;
3260 }
3261
3262
3263 /// growOperands - grow operands - This grows the operand list in response
3264 /// to a push_back style of operation.  This grows the number of ops by 2 times.
3265 ///
3266 void IndirectBrInst::growOperands() {
3267   unsigned e = getNumOperands();
3268   unsigned NumOps = e*2;
3269   
3270   ReservedSpace = NumOps;
3271   Use *NewOps = allocHungoffUses(NumOps);
3272   Use *OldOps = OperandList;
3273   for (unsigned i = 0; i != e; ++i)
3274     NewOps[i] = OldOps[i];
3275   OperandList = NewOps;
3276   Use::zap(OldOps, OldOps + e, true);
3277 }
3278
3279 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3280                                Instruction *InsertBefore)
3281 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3282                  0, 0, InsertBefore) {
3283   init(Address, NumCases);
3284 }
3285
3286 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3287                                BasicBlock *InsertAtEnd)
3288 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3289                  0, 0, InsertAtEnd) {
3290   init(Address, NumCases);
3291 }
3292
3293 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3294   : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3295                    allocHungoffUses(IBI.getNumOperands()),
3296                    IBI.getNumOperands()) {
3297   Use *OL = OperandList, *InOL = IBI.OperandList;
3298   for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3299     OL[i] = InOL[i];
3300   SubclassOptionalData = IBI.SubclassOptionalData;
3301 }
3302
3303 IndirectBrInst::~IndirectBrInst() {
3304   dropHungoffUses();
3305 }
3306
3307 /// addDestination - Add a destination.
3308 ///
3309 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3310   unsigned OpNo = NumOperands;
3311   if (OpNo+1 > ReservedSpace)
3312     growOperands();  // Get more space!
3313   // Initialize some new operands.
3314   assert(OpNo < ReservedSpace && "Growing didn't work!");
3315   NumOperands = OpNo+1;
3316   OperandList[OpNo] = DestBB;
3317 }
3318
3319 /// removeDestination - This method removes the specified successor from the
3320 /// indirectbr instruction.
3321 void IndirectBrInst::removeDestination(unsigned idx) {
3322   assert(idx < getNumOperands()-1 && "Successor index out of range!");
3323   
3324   unsigned NumOps = getNumOperands();
3325   Use *OL = OperandList;
3326
3327   // Replace this value with the last one.
3328   OL[idx+1] = OL[NumOps-1];
3329   
3330   // Nuke the last value.
3331   OL[NumOps-1].set(0);
3332   NumOperands = NumOps-1;
3333 }
3334
3335 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3336   return getSuccessor(idx);
3337 }
3338 unsigned IndirectBrInst::getNumSuccessorsV() const {
3339   return getNumSuccessors();
3340 }
3341 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3342   setSuccessor(idx, B);
3343 }
3344
3345 //===----------------------------------------------------------------------===//
3346 //                           clone_impl() implementations
3347 //===----------------------------------------------------------------------===//
3348
3349 // Define these methods here so vtables don't get emitted into every translation
3350 // unit that uses these classes.
3351
3352 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3353   return new (getNumOperands()) GetElementPtrInst(*this);
3354 }
3355
3356 BinaryOperator *BinaryOperator::clone_impl() const {
3357   return Create(getOpcode(), Op<0>(), Op<1>());
3358 }
3359
3360 FCmpInst* FCmpInst::clone_impl() const {
3361   return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3362 }
3363
3364 ICmpInst* ICmpInst::clone_impl() const {
3365   return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3366 }
3367
3368 ExtractValueInst *ExtractValueInst::clone_impl() const {
3369   return new ExtractValueInst(*this);
3370 }
3371
3372 InsertValueInst *InsertValueInst::clone_impl() const {
3373   return new InsertValueInst(*this);
3374 }
3375
3376 AllocaInst *AllocaInst::clone_impl() const {
3377   return new AllocaInst(getAllocatedType(),
3378                         (Value*)getOperand(0),
3379                         getAlignment());
3380 }
3381
3382 LoadInst *LoadInst::clone_impl() const {
3383   return new LoadInst(getOperand(0), Twine(), isVolatile(),
3384                       getAlignment(), getOrdering(), getSynchScope());
3385 }
3386
3387 StoreInst *StoreInst::clone_impl() const {
3388   return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3389                        getAlignment(), getOrdering(), getSynchScope());
3390   
3391 }
3392
3393 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3394   AtomicCmpXchgInst *Result =
3395     new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3396                           getOrdering(), getSynchScope());
3397   Result->setVolatile(isVolatile());
3398   return Result;
3399 }
3400
3401 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3402   AtomicRMWInst *Result =
3403     new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3404                       getOrdering(), getSynchScope());
3405   Result->setVolatile(isVolatile());
3406   return Result;
3407 }
3408
3409 FenceInst *FenceInst::clone_impl() const {
3410   return new FenceInst(getContext(), getOrdering(), getSynchScope());
3411 }
3412
3413 TruncInst *TruncInst::clone_impl() const {
3414   return new TruncInst(getOperand(0), getType());
3415 }
3416
3417 ZExtInst *ZExtInst::clone_impl() const {
3418   return new ZExtInst(getOperand(0), getType());
3419 }
3420
3421 SExtInst *SExtInst::clone_impl() const {
3422   return new SExtInst(getOperand(0), getType());
3423 }
3424
3425 FPTruncInst *FPTruncInst::clone_impl() const {
3426   return new FPTruncInst(getOperand(0), getType());
3427 }
3428
3429 FPExtInst *FPExtInst::clone_impl() const {
3430   return new FPExtInst(getOperand(0), getType());
3431 }
3432
3433 UIToFPInst *UIToFPInst::clone_impl() const {
3434   return new UIToFPInst(getOperand(0), getType());
3435 }
3436
3437 SIToFPInst *SIToFPInst::clone_impl() const {
3438   return new SIToFPInst(getOperand(0), getType());
3439 }
3440
3441 FPToUIInst *FPToUIInst::clone_impl() const {
3442   return new FPToUIInst(getOperand(0), getType());
3443 }
3444
3445 FPToSIInst *FPToSIInst::clone_impl() const {
3446   return new FPToSIInst(getOperand(0), getType());
3447 }
3448
3449 PtrToIntInst *PtrToIntInst::clone_impl() const {
3450   return new PtrToIntInst(getOperand(0), getType());
3451 }
3452
3453 IntToPtrInst *IntToPtrInst::clone_impl() const {
3454   return new IntToPtrInst(getOperand(0), getType());
3455 }
3456
3457 BitCastInst *BitCastInst::clone_impl() const {
3458   return new BitCastInst(getOperand(0), getType());
3459 }
3460
3461 CallInst *CallInst::clone_impl() const {
3462   return  new(getNumOperands()) CallInst(*this);
3463 }
3464
3465 SelectInst *SelectInst::clone_impl() const {
3466   return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3467 }
3468
3469 VAArgInst *VAArgInst::clone_impl() const {
3470   return new VAArgInst(getOperand(0), getType());
3471 }
3472
3473 ExtractElementInst *ExtractElementInst::clone_impl() const {
3474   return ExtractElementInst::Create(getOperand(0), getOperand(1));
3475 }
3476
3477 InsertElementInst *InsertElementInst::clone_impl() const {
3478   return InsertElementInst::Create(getOperand(0),
3479                                    getOperand(1),
3480                                    getOperand(2));
3481 }
3482
3483 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3484   return new ShuffleVectorInst(getOperand(0),
3485                            getOperand(1),
3486                            getOperand(2));
3487 }
3488
3489 PHINode *PHINode::clone_impl() const {
3490   return new PHINode(*this);
3491 }
3492
3493 LandingPadInst *LandingPadInst::clone_impl() const {
3494   return new LandingPadInst(*this);
3495 }
3496
3497 ReturnInst *ReturnInst::clone_impl() const {
3498   return new(getNumOperands()) ReturnInst(*this);
3499 }
3500
3501 BranchInst *BranchInst::clone_impl() const {
3502   return new(getNumOperands()) BranchInst(*this);
3503 }
3504
3505 SwitchInst *SwitchInst::clone_impl() const {
3506   return new SwitchInst(*this);
3507 }
3508
3509 IndirectBrInst *IndirectBrInst::clone_impl() const {
3510   return new IndirectBrInst(*this);
3511 }
3512
3513
3514 InvokeInst *InvokeInst::clone_impl() const {
3515   return new(getNumOperands()) InvokeInst(*this);
3516 }
3517
3518 ResumeInst *ResumeInst::clone_impl() const {
3519   return new(1) ResumeInst(*this);
3520 }
3521
3522 UnwindInst *UnwindInst::clone_impl() const {
3523   LLVMContext &Context = getContext();
3524   return new UnwindInst(Context);
3525 }
3526
3527 UnreachableInst *UnreachableInst::clone_impl() const {
3528   LLVMContext &Context = getContext();
3529   return new UnreachableInst(Context);
3530 }