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