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