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