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