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