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