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