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