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