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