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