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