Hack on vectors too.
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/ParameterAttributes.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/GetElementPtrTypeIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include <algorithm>
60 #include <sstream>
61 using namespace llvm;
62 using namespace llvm::PatternMatch;
63
64 STATISTIC(NumCombined , "Number of insts combined");
65 STATISTIC(NumConstProp, "Number of constant folds");
66 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68 STATISTIC(NumSunkInst , "Number of instructions sunk");
69
70 namespace {
71   class VISIBILITY_HIDDEN InstCombiner
72     : public FunctionPass,
73       public InstVisitor<InstCombiner, Instruction*> {
74     // Worklist of all of the instructions that need to be simplified.
75     std::vector<Instruction*> Worklist;
76     DenseMap<Instruction*, unsigned> WorklistMap;
77     TargetData *TD;
78     bool MustPreserveLCSSA;
79   public:
80     static char ID; // Pass identification, replacement for typeid
81     InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
83     /// AddToWorkList - Add the specified instruction to the worklist if it
84     /// isn't already in it.
85     void AddToWorkList(Instruction *I) {
86       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87         Worklist.push_back(I);
88     }
89     
90     // RemoveFromWorkList - remove I from the worklist if it exists.
91     void RemoveFromWorkList(Instruction *I) {
92       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93       if (It == WorklistMap.end()) return; // Not in worklist.
94       
95       // Don't bother moving everything down, just null out the slot.
96       Worklist[It->second] = 0;
97       
98       WorklistMap.erase(It);
99     }
100     
101     Instruction *RemoveOneFromWorkList() {
102       Instruction *I = Worklist.back();
103       Worklist.pop_back();
104       WorklistMap.erase(I);
105       return I;
106     }
107
108     
109     /// AddUsersToWorkList - When an instruction is simplified, add all users of
110     /// the instruction to the work lists because they might get more simplified
111     /// now.
112     ///
113     void AddUsersToWorkList(Value &I) {
114       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
115            UI != UE; ++UI)
116         AddToWorkList(cast<Instruction>(*UI));
117     }
118
119     /// AddUsesToWorkList - When an instruction is simplified, add operands to
120     /// the work lists because they might get more simplified now.
121     ///
122     void AddUsesToWorkList(Instruction &I) {
123       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
125           AddToWorkList(Op);
126     }
127     
128     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129     /// dead.  Add all of its operands to the worklist, turning them into
130     /// undef's to reduce the number of uses of those instructions.
131     ///
132     /// Return the specified operand before it is turned into an undef.
133     ///
134     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135       Value *R = I.getOperand(op);
136       
137       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
139           AddToWorkList(Op);
140           // Set the operand to undef to drop the use.
141           I.setOperand(i, UndefValue::get(Op->getType()));
142         }
143       
144       return R;
145     }
146
147   public:
148     virtual bool runOnFunction(Function &F);
149     
150     bool DoOneIteration(Function &F, unsigned ItNum);
151
152     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153       AU.addRequired<TargetData>();
154       AU.addPreservedID(LCSSAID);
155       AU.setPreservesCFG();
156     }
157
158     TargetData &getTargetData() const { return *TD; }
159
160     // Visitation implementation - Implement instruction combining for different
161     // instruction types.  The semantics are as follows:
162     // Return Value:
163     //    null        - No change was made
164     //     I          - Change was made, I is still valid, I may be dead though
165     //   otherwise    - Change was made, replace I with returned instruction
166     //
167     Instruction *visitAdd(BinaryOperator &I);
168     Instruction *visitSub(BinaryOperator &I);
169     Instruction *visitMul(BinaryOperator &I);
170     Instruction *visitURem(BinaryOperator &I);
171     Instruction *visitSRem(BinaryOperator &I);
172     Instruction *visitFRem(BinaryOperator &I);
173     Instruction *commonRemTransforms(BinaryOperator &I);
174     Instruction *commonIRemTransforms(BinaryOperator &I);
175     Instruction *commonDivTransforms(BinaryOperator &I);
176     Instruction *commonIDivTransforms(BinaryOperator &I);
177     Instruction *visitUDiv(BinaryOperator &I);
178     Instruction *visitSDiv(BinaryOperator &I);
179     Instruction *visitFDiv(BinaryOperator &I);
180     Instruction *visitAnd(BinaryOperator &I);
181     Instruction *visitOr (BinaryOperator &I);
182     Instruction *visitXor(BinaryOperator &I);
183     Instruction *visitShl(BinaryOperator &I);
184     Instruction *visitAShr(BinaryOperator &I);
185     Instruction *visitLShr(BinaryOperator &I);
186     Instruction *commonShiftTransforms(BinaryOperator &I);
187     Instruction *visitFCmpInst(FCmpInst &I);
188     Instruction *visitICmpInst(ICmpInst &I);
189     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
190     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191                                                 Instruction *LHS,
192                                                 ConstantInt *RHS);
193     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194                                 ConstantInt *DivRHS);
195
196     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197                              ICmpInst::Predicate Cond, Instruction &I);
198     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
199                                      BinaryOperator &I);
200     Instruction *commonCastTransforms(CastInst &CI);
201     Instruction *commonIntCastTransforms(CastInst &CI);
202     Instruction *commonPointerCastTransforms(CastInst &CI);
203     Instruction *visitTrunc(TruncInst &CI);
204     Instruction *visitZExt(ZExtInst &CI);
205     Instruction *visitSExt(SExtInst &CI);
206     Instruction *visitFPTrunc(FPTruncInst &CI);
207     Instruction *visitFPExt(CastInst &CI);
208     Instruction *visitFPToUI(CastInst &CI);
209     Instruction *visitFPToSI(CastInst &CI);
210     Instruction *visitUIToFP(CastInst &CI);
211     Instruction *visitSIToFP(CastInst &CI);
212     Instruction *visitPtrToInt(CastInst &CI);
213     Instruction *visitIntToPtr(IntToPtrInst &CI);
214     Instruction *visitBitCast(BitCastInst &CI);
215     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216                                 Instruction *FI);
217     Instruction *visitSelectInst(SelectInst &CI);
218     Instruction *visitCallInst(CallInst &CI);
219     Instruction *visitInvokeInst(InvokeInst &II);
220     Instruction *visitPHINode(PHINode &PN);
221     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
222     Instruction *visitAllocationInst(AllocationInst &AI);
223     Instruction *visitFreeInst(FreeInst &FI);
224     Instruction *visitLoadInst(LoadInst &LI);
225     Instruction *visitStoreInst(StoreInst &SI);
226     Instruction *visitBranchInst(BranchInst &BI);
227     Instruction *visitSwitchInst(SwitchInst &SI);
228     Instruction *visitInsertElementInst(InsertElementInst &IE);
229     Instruction *visitExtractElementInst(ExtractElementInst &EI);
230     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
231
232     // visitInstruction - Specify what to return for unhandled instructions...
233     Instruction *visitInstruction(Instruction &I) { return 0; }
234
235   private:
236     Instruction *visitCallSite(CallSite CS);
237     bool transformConstExprCastCall(CallSite CS);
238     Instruction *transformCallThroughTrampoline(CallSite CS);
239
240   public:
241     // InsertNewInstBefore - insert an instruction New before instruction Old
242     // in the program.  Add the new instruction to the worklist.
243     //
244     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
245       assert(New && New->getParent() == 0 &&
246              "New instruction already inserted into a basic block!");
247       BasicBlock *BB = Old.getParent();
248       BB->getInstList().insert(&Old, New);  // Insert inst
249       AddToWorkList(New);
250       return New;
251     }
252
253     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
254     /// This also adds the cast to the worklist.  Finally, this returns the
255     /// cast.
256     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
257                             Instruction &Pos) {
258       if (V->getType() == Ty) return V;
259
260       if (Constant *CV = dyn_cast<Constant>(V))
261         return ConstantExpr::getCast(opc, CV, Ty);
262       
263       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
264       AddToWorkList(C);
265       return C;
266     }
267         
268     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
269       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
270     }
271
272
273     // ReplaceInstUsesWith - This method is to be used when an instruction is
274     // found to be dead, replacable with another preexisting expression.  Here
275     // we add all uses of I to the worklist, replace all uses of I with the new
276     // value, then return I, so that the inst combiner will know that I was
277     // modified.
278     //
279     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
280       AddUsersToWorkList(I);         // Add all modified instrs to worklist
281       if (&I != V) {
282         I.replaceAllUsesWith(V);
283         return &I;
284       } else {
285         // If we are replacing the instruction with itself, this must be in a
286         // segment of unreachable code, so just clobber the instruction.
287         I.replaceAllUsesWith(UndefValue::get(I.getType()));
288         return &I;
289       }
290     }
291
292     // UpdateValueUsesWith - This method is to be used when an value is
293     // found to be replacable with another preexisting expression or was
294     // updated.  Here we add all uses of I to the worklist, replace all uses of
295     // I with the new value (unless the instruction was just updated), then
296     // return true, so that the inst combiner will know that I was modified.
297     //
298     bool UpdateValueUsesWith(Value *Old, Value *New) {
299       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
300       if (Old != New)
301         Old->replaceAllUsesWith(New);
302       if (Instruction *I = dyn_cast<Instruction>(Old))
303         AddToWorkList(I);
304       if (Instruction *I = dyn_cast<Instruction>(New))
305         AddToWorkList(I);
306       return true;
307     }
308     
309     // EraseInstFromFunction - When dealing with an instruction that has side
310     // effects or produces a void value, we can't rely on DCE to delete the
311     // instruction.  Instead, visit methods should return the value returned by
312     // this function.
313     Instruction *EraseInstFromFunction(Instruction &I) {
314       assert(I.use_empty() && "Cannot erase instruction that is used!");
315       AddUsesToWorkList(I);
316       RemoveFromWorkList(&I);
317       I.eraseFromParent();
318       return 0;  // Don't do anything with FI
319     }
320
321   private:
322     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
323     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
324     /// casts that are known to not do anything...
325     ///
326     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
327                                    Value *V, const Type *DestTy,
328                                    Instruction *InsertBefore);
329
330     /// SimplifyCommutative - This performs a few simplifications for 
331     /// commutative operators.
332     bool SimplifyCommutative(BinaryOperator &I);
333
334     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
335     /// most-complex to least-complex order.
336     bool SimplifyCompare(CmpInst &I);
337
338     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
339     /// on the demanded bits.
340     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
341                               APInt& KnownZero, APInt& KnownOne,
342                               unsigned Depth = 0);
343
344     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
345                                       uint64_t &UndefElts, unsigned Depth = 0);
346       
347     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
348     // PHI node as operand #0, see if we can fold the instruction into the PHI
349     // (which is only possible if all operands to the PHI are constants).
350     Instruction *FoldOpIntoPhi(Instruction &I);
351
352     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
353     // operator and they all are only used by the PHI, PHI together their
354     // inputs, and do the operation once, to the result of the PHI.
355     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
356     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
357     
358     
359     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
360                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
361     
362     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
363                               bool isSub, Instruction &I);
364     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
365                                  bool isSigned, bool Inside, Instruction &IB);
366     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
367     Instruction *MatchBSwap(BinaryOperator &I);
368     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
369     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
370
371
372     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
373   };
374
375   char InstCombiner::ID = 0;
376   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
377 }
378
379 // getComplexity:  Assign a complexity or rank value to LLVM Values...
380 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
381 static unsigned getComplexity(Value *V) {
382   if (isa<Instruction>(V)) {
383     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
384       return 3;
385     return 4;
386   }
387   if (isa<Argument>(V)) return 3;
388   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
389 }
390
391 // isOnlyUse - Return true if this instruction will be deleted if we stop using
392 // it.
393 static bool isOnlyUse(Value *V) {
394   return V->hasOneUse() || isa<Constant>(V);
395 }
396
397 // getPromotedType - Return the specified type promoted as it would be to pass
398 // though a va_arg area...
399 static const Type *getPromotedType(const Type *Ty) {
400   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
401     if (ITy->getBitWidth() < 32)
402       return Type::Int32Ty;
403   }
404   return Ty;
405 }
406
407 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
408 /// expression bitcast,  return the operand value, otherwise return null.
409 static Value *getBitCastOperand(Value *V) {
410   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
411     return I->getOperand(0);
412   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
413     if (CE->getOpcode() == Instruction::BitCast)
414       return CE->getOperand(0);
415   return 0;
416 }
417
418 /// This function is a wrapper around CastInst::isEliminableCastPair. It
419 /// simply extracts arguments and returns what that function returns.
420 static Instruction::CastOps 
421 isEliminableCastPair(
422   const CastInst *CI, ///< The first cast instruction
423   unsigned opcode,       ///< The opcode of the second cast instruction
424   const Type *DstTy,     ///< The target type for the second cast instruction
425   TargetData *TD         ///< The target data for pointer size
426 ) {
427   
428   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
429   const Type *MidTy = CI->getType();                  // B from above
430
431   // Get the opcodes of the two Cast instructions
432   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
433   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
434
435   return Instruction::CastOps(
436       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
437                                      DstTy, TD->getIntPtrType()));
438 }
439
440 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
441 /// in any code being generated.  It does not require codegen if V is simple
442 /// enough or if the cast can be folded into other casts.
443 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
444                               const Type *Ty, TargetData *TD) {
445   if (V->getType() == Ty || isa<Constant>(V)) return false;
446   
447   // If this is another cast that can be eliminated, it isn't codegen either.
448   if (const CastInst *CI = dyn_cast<CastInst>(V))
449     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
450       return false;
451   return true;
452 }
453
454 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
455 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
456 /// casts that are known to not do anything...
457 ///
458 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
459                                              Value *V, const Type *DestTy,
460                                              Instruction *InsertBefore) {
461   if (V->getType() == DestTy) return V;
462   if (Constant *C = dyn_cast<Constant>(V))
463     return ConstantExpr::getCast(opcode, C, DestTy);
464   
465   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
466 }
467
468 // SimplifyCommutative - This performs a few simplifications for commutative
469 // operators:
470 //
471 //  1. Order operands such that they are listed from right (least complex) to
472 //     left (most complex).  This puts constants before unary operators before
473 //     binary operators.
474 //
475 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
476 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
477 //
478 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
479   bool Changed = false;
480   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
481     Changed = !I.swapOperands();
482
483   if (!I.isAssociative()) return Changed;
484   Instruction::BinaryOps Opcode = I.getOpcode();
485   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
486     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
487       if (isa<Constant>(I.getOperand(1))) {
488         Constant *Folded = ConstantExpr::get(I.getOpcode(),
489                                              cast<Constant>(I.getOperand(1)),
490                                              cast<Constant>(Op->getOperand(1)));
491         I.setOperand(0, Op->getOperand(0));
492         I.setOperand(1, Folded);
493         return true;
494       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
495         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
496             isOnlyUse(Op) && isOnlyUse(Op1)) {
497           Constant *C1 = cast<Constant>(Op->getOperand(1));
498           Constant *C2 = cast<Constant>(Op1->getOperand(1));
499
500           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
501           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
502           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
503                                                     Op1->getOperand(0),
504                                                     Op1->getName(), &I);
505           AddToWorkList(New);
506           I.setOperand(0, New);
507           I.setOperand(1, Folded);
508           return true;
509         }
510     }
511   return Changed;
512 }
513
514 /// SimplifyCompare - For a CmpInst this function just orders the operands
515 /// so that theyare listed from right (least complex) to left (most complex).
516 /// This puts constants before unary operators before binary operators.
517 bool InstCombiner::SimplifyCompare(CmpInst &I) {
518   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
519     return false;
520   I.swapOperands();
521   // Compare instructions are not associative so there's nothing else we can do.
522   return true;
523 }
524
525 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
526 // if the LHS is a constant zero (which is the 'negate' form).
527 //
528 static inline Value *dyn_castNegVal(Value *V) {
529   if (BinaryOperator::isNeg(V))
530     return BinaryOperator::getNegArgument(V);
531
532   // Constants can be considered to be negated values if they can be folded.
533   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
534     return ConstantExpr::getNeg(C);
535   return 0;
536 }
537
538 static inline Value *dyn_castNotVal(Value *V) {
539   if (BinaryOperator::isNot(V))
540     return BinaryOperator::getNotArgument(V);
541
542   // Constants can be considered to be not'ed values...
543   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
544     return ConstantInt::get(~C->getValue());
545   return 0;
546 }
547
548 // dyn_castFoldableMul - If this value is a multiply that can be folded into
549 // other computations (because it has a constant operand), return the
550 // non-constant operand of the multiply, and set CST to point to the multiplier.
551 // Otherwise, return null.
552 //
553 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
554   if (V->hasOneUse() && V->getType()->isInteger())
555     if (Instruction *I = dyn_cast<Instruction>(V)) {
556       if (I->getOpcode() == Instruction::Mul)
557         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
558           return I->getOperand(0);
559       if (I->getOpcode() == Instruction::Shl)
560         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
561           // The multiplier is really 1 << CST.
562           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
563           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
564           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
565           return I->getOperand(0);
566         }
567     }
568   return 0;
569 }
570
571 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
572 /// expression, return it.
573 static User *dyn_castGetElementPtr(Value *V) {
574   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
575   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
576     if (CE->getOpcode() == Instruction::GetElementPtr)
577       return cast<User>(V);
578   return false;
579 }
580
581 /// AddOne - Add one to a ConstantInt
582 static ConstantInt *AddOne(ConstantInt *C) {
583   APInt Val(C->getValue());
584   return ConstantInt::get(++Val);
585 }
586 /// SubOne - Subtract one from a ConstantInt
587 static ConstantInt *SubOne(ConstantInt *C) {
588   APInt Val(C->getValue());
589   return ConstantInt::get(--Val);
590 }
591 /// Add - Add two ConstantInts together
592 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
593   return ConstantInt::get(C1->getValue() + C2->getValue());
594 }
595 /// And - Bitwise AND two ConstantInts together
596 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
597   return ConstantInt::get(C1->getValue() & C2->getValue());
598 }
599 /// Subtract - Subtract one ConstantInt from another
600 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
601   return ConstantInt::get(C1->getValue() - C2->getValue());
602 }
603 /// Multiply - Multiply two ConstantInts together
604 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
605   return ConstantInt::get(C1->getValue() * C2->getValue());
606 }
607
608 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
609 /// known to be either zero or one and return them in the KnownZero/KnownOne
610 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
611 /// processing.
612 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
613 /// we cannot optimize based on the assumption that it is zero without changing
614 /// it to be an explicit zero.  If we don't change it to zero, other code could
615 /// optimized based on the contradictory assumption that it is non-zero.
616 /// Because instcombine aggressively folds operations with undef args anyway,
617 /// this won't lose us code quality.
618 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
619                               APInt& KnownOne, unsigned Depth = 0) {
620   assert(V && "No Value?");
621   assert(Depth <= 6 && "Limit Search Depth");
622   uint32_t BitWidth = Mask.getBitWidth();
623   assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
624          KnownZero.getBitWidth() == BitWidth && 
625          KnownOne.getBitWidth() == BitWidth &&
626          "V, Mask, KnownOne and KnownZero should have same BitWidth");
627   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
628     // We know all of the bits for a constant!
629     KnownOne = CI->getValue() & Mask;
630     KnownZero = ~KnownOne & Mask;
631     return;
632   }
633
634   if (Depth == 6 || Mask == 0)
635     return;  // Limit search depth.
636
637   Instruction *I = dyn_cast<Instruction>(V);
638   if (!I) return;
639
640   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
641   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
642   
643   switch (I->getOpcode()) {
644   case Instruction::And: {
645     // If either the LHS or the RHS are Zero, the result is zero.
646     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
647     APInt Mask2(Mask & ~KnownZero);
648     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
649     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
650     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
651     
652     // Output known-1 bits are only known if set in both the LHS & RHS.
653     KnownOne &= KnownOne2;
654     // Output known-0 are known to be clear if zero in either the LHS | RHS.
655     KnownZero |= KnownZero2;
656     return;
657   }
658   case Instruction::Or: {
659     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
660     APInt Mask2(Mask & ~KnownOne);
661     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
662     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
663     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
664     
665     // Output known-0 bits are only known if clear in both the LHS & RHS.
666     KnownZero &= KnownZero2;
667     // Output known-1 are known to be set if set in either the LHS | RHS.
668     KnownOne |= KnownOne2;
669     return;
670   }
671   case Instruction::Xor: {
672     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
673     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
674     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
675     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
676     
677     // Output known-0 bits are known if clear or set in both the LHS & RHS.
678     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
679     // Output known-1 are known to be set if set in only one of the LHS, RHS.
680     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
681     KnownZero = KnownZeroOut;
682     return;
683   }
684   case Instruction::Select:
685     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
686     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
687     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
688     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
689
690     // Only known if known in both the LHS and RHS.
691     KnownOne &= KnownOne2;
692     KnownZero &= KnownZero2;
693     return;
694   case Instruction::FPTrunc:
695   case Instruction::FPExt:
696   case Instruction::FPToUI:
697   case Instruction::FPToSI:
698   case Instruction::SIToFP:
699   case Instruction::PtrToInt:
700   case Instruction::UIToFP:
701   case Instruction::IntToPtr:
702     return; // Can't work with floating point or pointers
703   case Instruction::Trunc: {
704     // All these have integer operands
705     uint32_t SrcBitWidth = 
706       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
707     APInt MaskIn(Mask);
708     MaskIn.zext(SrcBitWidth);
709     KnownZero.zext(SrcBitWidth);
710     KnownOne.zext(SrcBitWidth);
711     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
712     KnownZero.trunc(BitWidth);
713     KnownOne.trunc(BitWidth);
714     return;
715   }
716   case Instruction::BitCast: {
717     const Type *SrcTy = I->getOperand(0)->getType();
718     if (SrcTy->isInteger()) {
719       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
720       return;
721     }
722     break;
723   }
724   case Instruction::ZExt:  {
725     // Compute the bits in the result that are not present in the input.
726     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
727     uint32_t SrcBitWidth = SrcTy->getBitWidth();
728       
729     APInt MaskIn(Mask);
730     MaskIn.trunc(SrcBitWidth);
731     KnownZero.trunc(SrcBitWidth);
732     KnownOne.trunc(SrcBitWidth);
733     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
734     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
735     // The top bits are known to be zero.
736     KnownZero.zext(BitWidth);
737     KnownOne.zext(BitWidth);
738     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
739     return;
740   }
741   case Instruction::SExt: {
742     // Compute the bits in the result that are not present in the input.
743     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
744     uint32_t SrcBitWidth = SrcTy->getBitWidth();
745       
746     APInt MaskIn(Mask); 
747     MaskIn.trunc(SrcBitWidth);
748     KnownZero.trunc(SrcBitWidth);
749     KnownOne.trunc(SrcBitWidth);
750     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
751     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
752     KnownZero.zext(BitWidth);
753     KnownOne.zext(BitWidth);
754
755     // If the sign bit of the input is known set or clear, then we know the
756     // top bits of the result.
757     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
758       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
759     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
760       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
761     return;
762   }
763   case Instruction::Shl:
764     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
765     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
766       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
767       APInt Mask2(Mask.lshr(ShiftAmt));
768       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
769       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
770       KnownZero <<= ShiftAmt;
771       KnownOne  <<= ShiftAmt;
772       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
773       return;
774     }
775     break;
776   case Instruction::LShr:
777     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
778     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
779       // Compute the new bits that are at the top now.
780       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
781       
782       // Unsigned shift right.
783       APInt Mask2(Mask.shl(ShiftAmt));
784       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
785       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
786       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
787       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
788       // high bits known zero.
789       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
790       return;
791     }
792     break;
793   case Instruction::AShr:
794     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
795     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
796       // Compute the new bits that are at the top now.
797       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
798       
799       // Signed shift right.
800       APInt Mask2(Mask.shl(ShiftAmt));
801       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
802       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
803       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
804       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
805         
806       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
807       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
808         KnownZero |= HighBits;
809       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
810         KnownOne |= HighBits;
811       return;
812     }
813     break;
814   }
815 }
816
817 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
818 /// this predicate to simplify operations downstream.  Mask is known to be zero
819 /// for bits that V cannot have.
820 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
821   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
822   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
823   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
824   return (KnownZero & Mask) == Mask;
825 }
826
827 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
828 /// specified instruction is a constant integer.  If so, check to see if there
829 /// are any bits set in the constant that are not demanded.  If so, shrink the
830 /// constant and return true.
831 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
832                                    APInt Demanded) {
833   assert(I && "No instruction?");
834   assert(OpNo < I->getNumOperands() && "Operand index too large");
835
836   // If the operand is not a constant integer, nothing to do.
837   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
838   if (!OpC) return false;
839
840   // If there are no bits set that aren't demanded, nothing to do.
841   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
842   if ((~Demanded & OpC->getValue()) == 0)
843     return false;
844
845   // This instruction is producing bits that are not demanded. Shrink the RHS.
846   Demanded &= OpC->getValue();
847   I->setOperand(OpNo, ConstantInt::get(Demanded));
848   return true;
849 }
850
851 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
852 // set of known zero and one bits, compute the maximum and minimum values that
853 // could have the specified known zero and known one bits, returning them in
854 // min/max.
855 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
856                                                    const APInt& KnownZero,
857                                                    const APInt& KnownOne,
858                                                    APInt& Min, APInt& Max) {
859   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
860   assert(KnownZero.getBitWidth() == BitWidth && 
861          KnownOne.getBitWidth() == BitWidth &&
862          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
863          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
864   APInt UnknownBits = ~(KnownZero|KnownOne);
865
866   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
867   // bit if it is unknown.
868   Min = KnownOne;
869   Max = KnownOne|UnknownBits;
870   
871   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
872     Min.set(BitWidth-1);
873     Max.clear(BitWidth-1);
874   }
875 }
876
877 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
878 // a set of known zero and one bits, compute the maximum and minimum values that
879 // could have the specified known zero and known one bits, returning them in
880 // min/max.
881 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
882                                                      const APInt &KnownZero,
883                                                      const APInt &KnownOne,
884                                                      APInt &Min, APInt &Max) {
885   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
886   assert(KnownZero.getBitWidth() == BitWidth && 
887          KnownOne.getBitWidth() == BitWidth &&
888          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
889          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
890   APInt UnknownBits = ~(KnownZero|KnownOne);
891   
892   // The minimum value is when the unknown bits are all zeros.
893   Min = KnownOne;
894   // The maximum value is when the unknown bits are all ones.
895   Max = KnownOne|UnknownBits;
896 }
897
898 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
899 /// value based on the demanded bits. When this function is called, it is known
900 /// that only the bits set in DemandedMask of the result of V are ever used
901 /// downstream. Consequently, depending on the mask and V, it may be possible
902 /// to replace V with a constant or one of its operands. In such cases, this
903 /// function does the replacement and returns true. In all other cases, it
904 /// returns false after analyzing the expression and setting KnownOne and known
905 /// to be one in the expression. KnownZero contains all the bits that are known
906 /// to be zero in the expression. These are provided to potentially allow the
907 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
908 /// the expression. KnownOne and KnownZero always follow the invariant that 
909 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
910 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
911 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
912 /// and KnownOne must all be the same.
913 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
914                                         APInt& KnownZero, APInt& KnownOne,
915                                         unsigned Depth) {
916   assert(V != 0 && "Null pointer of Value???");
917   assert(Depth <= 6 && "Limit Search Depth");
918   uint32_t BitWidth = DemandedMask.getBitWidth();
919   const IntegerType *VTy = cast<IntegerType>(V->getType());
920   assert(VTy->getBitWidth() == BitWidth && 
921          KnownZero.getBitWidth() == BitWidth && 
922          KnownOne.getBitWidth() == BitWidth &&
923          "Value *V, DemandedMask, KnownZero and KnownOne \
924           must have same BitWidth");
925   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
926     // We know all of the bits for a constant!
927     KnownOne = CI->getValue() & DemandedMask;
928     KnownZero = ~KnownOne & DemandedMask;
929     return false;
930   }
931   
932   KnownZero.clear(); 
933   KnownOne.clear();
934   if (!V->hasOneUse()) {    // Other users may use these bits.
935     if (Depth != 0) {       // Not at the root.
936       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
937       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
938       return false;
939     }
940     // If this is the root being simplified, allow it to have multiple uses,
941     // just set the DemandedMask to all bits.
942     DemandedMask = APInt::getAllOnesValue(BitWidth);
943   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
944     if (V != UndefValue::get(VTy))
945       return UpdateValueUsesWith(V, UndefValue::get(VTy));
946     return false;
947   } else if (Depth == 6) {        // Limit search depth.
948     return false;
949   }
950   
951   Instruction *I = dyn_cast<Instruction>(V);
952   if (!I) return false;        // Only analyze instructions.
953
954   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
955   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
956   switch (I->getOpcode()) {
957   default: break;
958   case Instruction::And:
959     // If either the LHS or the RHS are Zero, the result is zero.
960     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
961                              RHSKnownZero, RHSKnownOne, Depth+1))
962       return true;
963     assert((RHSKnownZero & RHSKnownOne) == 0 && 
964            "Bits known to be one AND zero?"); 
965
966     // If something is known zero on the RHS, the bits aren't demanded on the
967     // LHS.
968     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
969                              LHSKnownZero, LHSKnownOne, Depth+1))
970       return true;
971     assert((LHSKnownZero & LHSKnownOne) == 0 && 
972            "Bits known to be one AND zero?"); 
973
974     // If all of the demanded bits are known 1 on one side, return the other.
975     // These bits cannot contribute to the result of the 'and'.
976     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
977         (DemandedMask & ~LHSKnownZero))
978       return UpdateValueUsesWith(I, I->getOperand(0));
979     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
980         (DemandedMask & ~RHSKnownZero))
981       return UpdateValueUsesWith(I, I->getOperand(1));
982     
983     // If all of the demanded bits in the inputs are known zeros, return zero.
984     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
985       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
986       
987     // If the RHS is a constant, see if we can simplify it.
988     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
989       return UpdateValueUsesWith(I, I);
990       
991     // Output known-1 bits are only known if set in both the LHS & RHS.
992     RHSKnownOne &= LHSKnownOne;
993     // Output known-0 are known to be clear if zero in either the LHS | RHS.
994     RHSKnownZero |= LHSKnownZero;
995     break;
996   case Instruction::Or:
997     // If either the LHS or the RHS are One, the result is One.
998     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
999                              RHSKnownZero, RHSKnownOne, Depth+1))
1000       return true;
1001     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1002            "Bits known to be one AND zero?"); 
1003     // If something is known one on the RHS, the bits aren't demanded on the
1004     // LHS.
1005     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1006                              LHSKnownZero, LHSKnownOne, Depth+1))
1007       return true;
1008     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1009            "Bits known to be one AND zero?"); 
1010     
1011     // If all of the demanded bits are known zero on one side, return the other.
1012     // These bits cannot contribute to the result of the 'or'.
1013     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1014         (DemandedMask & ~LHSKnownOne))
1015       return UpdateValueUsesWith(I, I->getOperand(0));
1016     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1017         (DemandedMask & ~RHSKnownOne))
1018       return UpdateValueUsesWith(I, I->getOperand(1));
1019
1020     // If all of the potentially set bits on one side are known to be set on
1021     // the other side, just use the 'other' side.
1022     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1023         (DemandedMask & (~RHSKnownZero)))
1024       return UpdateValueUsesWith(I, I->getOperand(0));
1025     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1026         (DemandedMask & (~LHSKnownZero)))
1027       return UpdateValueUsesWith(I, I->getOperand(1));
1028         
1029     // If the RHS is a constant, see if we can simplify it.
1030     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1031       return UpdateValueUsesWith(I, I);
1032           
1033     // Output known-0 bits are only known if clear in both the LHS & RHS.
1034     RHSKnownZero &= LHSKnownZero;
1035     // Output known-1 are known to be set if set in either the LHS | RHS.
1036     RHSKnownOne |= LHSKnownOne;
1037     break;
1038   case Instruction::Xor: {
1039     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1040                              RHSKnownZero, RHSKnownOne, Depth+1))
1041       return true;
1042     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1043            "Bits known to be one AND zero?"); 
1044     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1045                              LHSKnownZero, LHSKnownOne, Depth+1))
1046       return true;
1047     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1048            "Bits known to be one AND zero?"); 
1049     
1050     // If all of the demanded bits are known zero on one side, return the other.
1051     // These bits cannot contribute to the result of the 'xor'.
1052     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1053       return UpdateValueUsesWith(I, I->getOperand(0));
1054     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1055       return UpdateValueUsesWith(I, I->getOperand(1));
1056     
1057     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1058     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1059                          (RHSKnownOne & LHSKnownOne);
1060     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1061     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1062                         (RHSKnownOne & LHSKnownZero);
1063     
1064     // If all of the demanded bits are known to be zero on one side or the
1065     // other, turn this into an *inclusive* or.
1066     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1067     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1068       Instruction *Or =
1069         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1070                                  I->getName());
1071       InsertNewInstBefore(Or, *I);
1072       return UpdateValueUsesWith(I, Or);
1073     }
1074     
1075     // If all of the demanded bits on one side are known, and all of the set
1076     // bits on that side are also known to be set on the other side, turn this
1077     // into an AND, as we know the bits will be cleared.
1078     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1079     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1080       // all known
1081       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1082         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1083         Instruction *And = 
1084           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1085         InsertNewInstBefore(And, *I);
1086         return UpdateValueUsesWith(I, And);
1087       }
1088     }
1089     
1090     // If the RHS is a constant, see if we can simplify it.
1091     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1092     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1093       return UpdateValueUsesWith(I, I);
1094     
1095     RHSKnownZero = KnownZeroOut;
1096     RHSKnownOne  = KnownOneOut;
1097     break;
1098   }
1099   case Instruction::Select:
1100     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1101                              RHSKnownZero, RHSKnownOne, Depth+1))
1102       return true;
1103     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1104                              LHSKnownZero, LHSKnownOne, Depth+1))
1105       return true;
1106     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1107            "Bits known to be one AND zero?"); 
1108     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1109            "Bits known to be one AND zero?"); 
1110     
1111     // If the operands are constants, see if we can simplify them.
1112     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1113       return UpdateValueUsesWith(I, I);
1114     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1115       return UpdateValueUsesWith(I, I);
1116     
1117     // Only known if known in both the LHS and RHS.
1118     RHSKnownOne &= LHSKnownOne;
1119     RHSKnownZero &= LHSKnownZero;
1120     break;
1121   case Instruction::Trunc: {
1122     uint32_t truncBf = 
1123       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1124     DemandedMask.zext(truncBf);
1125     RHSKnownZero.zext(truncBf);
1126     RHSKnownOne.zext(truncBf);
1127     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1128                              RHSKnownZero, RHSKnownOne, Depth+1))
1129       return true;
1130     DemandedMask.trunc(BitWidth);
1131     RHSKnownZero.trunc(BitWidth);
1132     RHSKnownOne.trunc(BitWidth);
1133     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1134            "Bits known to be one AND zero?"); 
1135     break;
1136   }
1137   case Instruction::BitCast:
1138     if (!I->getOperand(0)->getType()->isInteger())
1139       return false;
1140       
1141     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1142                              RHSKnownZero, RHSKnownOne, Depth+1))
1143       return true;
1144     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1145            "Bits known to be one AND zero?"); 
1146     break;
1147   case Instruction::ZExt: {
1148     // Compute the bits in the result that are not present in the input.
1149     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1150     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1151     
1152     DemandedMask.trunc(SrcBitWidth);
1153     RHSKnownZero.trunc(SrcBitWidth);
1154     RHSKnownOne.trunc(SrcBitWidth);
1155     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1156                              RHSKnownZero, RHSKnownOne, Depth+1))
1157       return true;
1158     DemandedMask.zext(BitWidth);
1159     RHSKnownZero.zext(BitWidth);
1160     RHSKnownOne.zext(BitWidth);
1161     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1162            "Bits known to be one AND zero?"); 
1163     // The top bits are known to be zero.
1164     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1165     break;
1166   }
1167   case Instruction::SExt: {
1168     // Compute the bits in the result that are not present in the input.
1169     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1170     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1171     
1172     APInt InputDemandedBits = DemandedMask & 
1173                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1174
1175     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1176     // If any of the sign extended bits are demanded, we know that the sign
1177     // bit is demanded.
1178     if ((NewBits & DemandedMask) != 0)
1179       InputDemandedBits.set(SrcBitWidth-1);
1180       
1181     InputDemandedBits.trunc(SrcBitWidth);
1182     RHSKnownZero.trunc(SrcBitWidth);
1183     RHSKnownOne.trunc(SrcBitWidth);
1184     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1185                              RHSKnownZero, RHSKnownOne, Depth+1))
1186       return true;
1187     InputDemandedBits.zext(BitWidth);
1188     RHSKnownZero.zext(BitWidth);
1189     RHSKnownOne.zext(BitWidth);
1190     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1191            "Bits known to be one AND zero?"); 
1192       
1193     // If the sign bit of the input is known set or clear, then we know the
1194     // top bits of the result.
1195
1196     // If the input sign bit is known zero, or if the NewBits are not demanded
1197     // convert this into a zero extension.
1198     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1199     {
1200       // Convert to ZExt cast
1201       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1202       return UpdateValueUsesWith(I, NewCast);
1203     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1204       RHSKnownOne |= NewBits;
1205     }
1206     break;
1207   }
1208   case Instruction::Add: {
1209     // Figure out what the input bits are.  If the top bits of the and result
1210     // are not demanded, then the add doesn't demand them from its input
1211     // either.
1212     uint32_t NLZ = DemandedMask.countLeadingZeros();
1213       
1214     // If there is a constant on the RHS, there are a variety of xformations
1215     // we can do.
1216     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1217       // If null, this should be simplified elsewhere.  Some of the xforms here
1218       // won't work if the RHS is zero.
1219       if (RHS->isZero())
1220         break;
1221       
1222       // If the top bit of the output is demanded, demand everything from the
1223       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1224       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1225
1226       // Find information about known zero/one bits in the input.
1227       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1228                                LHSKnownZero, LHSKnownOne, Depth+1))
1229         return true;
1230
1231       // If the RHS of the add has bits set that can't affect the input, reduce
1232       // the constant.
1233       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1234         return UpdateValueUsesWith(I, I);
1235       
1236       // Avoid excess work.
1237       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1238         break;
1239       
1240       // Turn it into OR if input bits are zero.
1241       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1242         Instruction *Or =
1243           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1244                                    I->getName());
1245         InsertNewInstBefore(Or, *I);
1246         return UpdateValueUsesWith(I, Or);
1247       }
1248       
1249       // We can say something about the output known-zero and known-one bits,
1250       // depending on potential carries from the input constant and the
1251       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1252       // bits set and the RHS constant is 0x01001, then we know we have a known
1253       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1254       
1255       // To compute this, we first compute the potential carry bits.  These are
1256       // the bits which may be modified.  I'm not aware of a better way to do
1257       // this scan.
1258       const APInt& RHSVal = RHS->getValue();
1259       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1260       
1261       // Now that we know which bits have carries, compute the known-1/0 sets.
1262       
1263       // Bits are known one if they are known zero in one operand and one in the
1264       // other, and there is no input carry.
1265       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1266                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1267       
1268       // Bits are known zero if they are known zero in both operands and there
1269       // is no input carry.
1270       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1271     } else {
1272       // If the high-bits of this ADD are not demanded, then it does not demand
1273       // the high bits of its LHS or RHS.
1274       if (DemandedMask[BitWidth-1] == 0) {
1275         // Right fill the mask of bits for this ADD to demand the most
1276         // significant bit and all those below it.
1277         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1278         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1279                                  LHSKnownZero, LHSKnownOne, Depth+1))
1280           return true;
1281         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1282                                  LHSKnownZero, LHSKnownOne, Depth+1))
1283           return true;
1284       }
1285     }
1286     break;
1287   }
1288   case Instruction::Sub:
1289     // If the high-bits of this SUB are not demanded, then it does not demand
1290     // the high bits of its LHS or RHS.
1291     if (DemandedMask[BitWidth-1] == 0) {
1292       // Right fill the mask of bits for this SUB to demand the most
1293       // significant bit and all those below it.
1294       uint32_t NLZ = DemandedMask.countLeadingZeros();
1295       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1296       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1297                                LHSKnownZero, LHSKnownOne, Depth+1))
1298         return true;
1299       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1300                                LHSKnownZero, LHSKnownOne, Depth+1))
1301         return true;
1302     }
1303     break;
1304   case Instruction::Shl:
1305     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1306       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1307       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1308       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1309                                RHSKnownZero, RHSKnownOne, Depth+1))
1310         return true;
1311       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1312              "Bits known to be one AND zero?"); 
1313       RHSKnownZero <<= ShiftAmt;
1314       RHSKnownOne  <<= ShiftAmt;
1315       // low bits known zero.
1316       if (ShiftAmt)
1317         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1318     }
1319     break;
1320   case Instruction::LShr:
1321     // For a logical shift right
1322     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1323       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1324       
1325       // Unsigned shift right.
1326       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1327       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1328                                RHSKnownZero, RHSKnownOne, Depth+1))
1329         return true;
1330       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1331              "Bits known to be one AND zero?"); 
1332       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1333       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1334       if (ShiftAmt) {
1335         // Compute the new bits that are at the top now.
1336         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1337         RHSKnownZero |= HighBits;  // high bits known zero.
1338       }
1339     }
1340     break;
1341   case Instruction::AShr:
1342     // If this is an arithmetic shift right and only the low-bit is set, we can
1343     // always convert this into a logical shr, even if the shift amount is
1344     // variable.  The low bit of the shift cannot be an input sign bit unless
1345     // the shift amount is >= the size of the datatype, which is undefined.
1346     if (DemandedMask == 1) {
1347       // Perform the logical shift right.
1348       Value *NewVal = BinaryOperator::createLShr(
1349                         I->getOperand(0), I->getOperand(1), I->getName());
1350       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1351       return UpdateValueUsesWith(I, NewVal);
1352     }    
1353
1354     // If the sign bit is the only bit demanded by this ashr, then there is no
1355     // need to do it, the shift doesn't change the high bit.
1356     if (DemandedMask.isSignBit())
1357       return UpdateValueUsesWith(I, I->getOperand(0));
1358     
1359     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1360       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1361       
1362       // Signed shift right.
1363       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1364       // If any of the "high bits" are demanded, we should set the sign bit as
1365       // demanded.
1366       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1367         DemandedMaskIn.set(BitWidth-1);
1368       if (SimplifyDemandedBits(I->getOperand(0),
1369                                DemandedMaskIn,
1370                                RHSKnownZero, RHSKnownOne, Depth+1))
1371         return true;
1372       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1373              "Bits known to be one AND zero?"); 
1374       // Compute the new bits that are at the top now.
1375       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1376       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1377       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1378         
1379       // Handle the sign bits.
1380       APInt SignBit(APInt::getSignBit(BitWidth));
1381       // Adjust to where it is now in the mask.
1382       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1383         
1384       // If the input sign bit is known to be zero, or if none of the top bits
1385       // are demanded, turn this into an unsigned shift right.
1386       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1387           (HighBits & ~DemandedMask) == HighBits) {
1388         // Perform the logical shift right.
1389         Value *NewVal = BinaryOperator::createLShr(
1390                           I->getOperand(0), SA, I->getName());
1391         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1392         return UpdateValueUsesWith(I, NewVal);
1393       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1394         RHSKnownOne |= HighBits;
1395       }
1396     }
1397     break;
1398   }
1399   
1400   // If the client is only demanding bits that we know, return the known
1401   // constant.
1402   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1403     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1404   return false;
1405 }
1406
1407
1408 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1409 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1410 /// actually used by the caller.  This method analyzes which elements of the
1411 /// operand are undef and returns that information in UndefElts.
1412 ///
1413 /// If the information about demanded elements can be used to simplify the
1414 /// operation, the operation is simplified, then the resultant value is
1415 /// returned.  This returns null if no change was made.
1416 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1417                                                 uint64_t &UndefElts,
1418                                                 unsigned Depth) {
1419   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1420   assert(VWidth <= 64 && "Vector too wide to analyze!");
1421   uint64_t EltMask = ~0ULL >> (64-VWidth);
1422   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1423          "Invalid DemandedElts!");
1424
1425   if (isa<UndefValue>(V)) {
1426     // If the entire vector is undefined, just return this info.
1427     UndefElts = EltMask;
1428     return 0;
1429   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1430     UndefElts = EltMask;
1431     return UndefValue::get(V->getType());
1432   }
1433   
1434   UndefElts = 0;
1435   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1436     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1437     Constant *Undef = UndefValue::get(EltTy);
1438
1439     std::vector<Constant*> Elts;
1440     for (unsigned i = 0; i != VWidth; ++i)
1441       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1442         Elts.push_back(Undef);
1443         UndefElts |= (1ULL << i);
1444       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1445         Elts.push_back(Undef);
1446         UndefElts |= (1ULL << i);
1447       } else {                               // Otherwise, defined.
1448         Elts.push_back(CP->getOperand(i));
1449       }
1450         
1451     // If we changed the constant, return it.
1452     Constant *NewCP = ConstantVector::get(Elts);
1453     return NewCP != CP ? NewCP : 0;
1454   } else if (isa<ConstantAggregateZero>(V)) {
1455     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1456     // set to undef.
1457     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1458     Constant *Zero = Constant::getNullValue(EltTy);
1459     Constant *Undef = UndefValue::get(EltTy);
1460     std::vector<Constant*> Elts;
1461     for (unsigned i = 0; i != VWidth; ++i)
1462       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1463     UndefElts = DemandedElts ^ EltMask;
1464     return ConstantVector::get(Elts);
1465   }
1466   
1467   if (!V->hasOneUse()) {    // Other users may use these bits.
1468     if (Depth != 0) {       // Not at the root.
1469       // TODO: Just compute the UndefElts information recursively.
1470       return false;
1471     }
1472     return false;
1473   } else if (Depth == 10) {        // Limit search depth.
1474     return false;
1475   }
1476   
1477   Instruction *I = dyn_cast<Instruction>(V);
1478   if (!I) return false;        // Only analyze instructions.
1479   
1480   bool MadeChange = false;
1481   uint64_t UndefElts2;
1482   Value *TmpV;
1483   switch (I->getOpcode()) {
1484   default: break;
1485     
1486   case Instruction::InsertElement: {
1487     // If this is a variable index, we don't know which element it overwrites.
1488     // demand exactly the same input as we produce.
1489     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1490     if (Idx == 0) {
1491       // Note that we can't propagate undef elt info, because we don't know
1492       // which elt is getting updated.
1493       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1494                                         UndefElts2, Depth+1);
1495       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1496       break;
1497     }
1498     
1499     // If this is inserting an element that isn't demanded, remove this
1500     // insertelement.
1501     unsigned IdxNo = Idx->getZExtValue();
1502     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1503       return AddSoonDeadInstToWorklist(*I, 0);
1504     
1505     // Otherwise, the element inserted overwrites whatever was there, so the
1506     // input demanded set is simpler than the output set.
1507     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1508                                       DemandedElts & ~(1ULL << IdxNo),
1509                                       UndefElts, Depth+1);
1510     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1511
1512     // The inserted element is defined.
1513     UndefElts |= 1ULL << IdxNo;
1514     break;
1515   }
1516   case Instruction::BitCast: {
1517     // Vector->vector casts only.
1518     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1519     if (!VTy) break;
1520     unsigned InVWidth = VTy->getNumElements();
1521     uint64_t InputDemandedElts = 0;
1522     unsigned Ratio;
1523
1524     if (VWidth == InVWidth) {
1525       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1526       // elements as are demanded of us.
1527       Ratio = 1;
1528       InputDemandedElts = DemandedElts;
1529     } else if (VWidth > InVWidth) {
1530       // Untested so far.
1531       break;
1532       
1533       // If there are more elements in the result than there are in the source,
1534       // then an input element is live if any of the corresponding output
1535       // elements are live.
1536       Ratio = VWidth/InVWidth;
1537       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1538         if (DemandedElts & (1ULL << OutIdx))
1539           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1540       }
1541     } else {
1542       // Untested so far.
1543       break;
1544       
1545       // If there are more elements in the source than there are in the result,
1546       // then an input element is live if the corresponding output element is
1547       // live.
1548       Ratio = InVWidth/VWidth;
1549       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1550         if (DemandedElts & (1ULL << InIdx/Ratio))
1551           InputDemandedElts |= 1ULL << InIdx;
1552     }
1553     
1554     // div/rem demand all inputs, because they don't want divide by zero.
1555     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1556                                       UndefElts2, Depth+1);
1557     if (TmpV) {
1558       I->setOperand(0, TmpV);
1559       MadeChange = true;
1560     }
1561     
1562     UndefElts = UndefElts2;
1563     if (VWidth > InVWidth) {
1564       assert(0 && "Unimp");
1565       // If there are more elements in the result than there are in the source,
1566       // then an output element is undef if the corresponding input element is
1567       // undef.
1568       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1569         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1570           UndefElts |= 1ULL << OutIdx;
1571     } else if (VWidth < InVWidth) {
1572       assert(0 && "Unimp");
1573       // If there are more elements in the source than there are in the result,
1574       // then a result element is undef if all of the corresponding input
1575       // elements are undef.
1576       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1577       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1578         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1579           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1580     }
1581     break;
1582   }
1583   case Instruction::And:
1584   case Instruction::Or:
1585   case Instruction::Xor:
1586   case Instruction::Add:
1587   case Instruction::Sub:
1588   case Instruction::Mul:
1589     // div/rem demand all inputs, because they don't want divide by zero.
1590     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1591                                       UndefElts, Depth+1);
1592     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1593     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1594                                       UndefElts2, Depth+1);
1595     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1596       
1597     // Output elements are undefined if both are undefined.  Consider things
1598     // like undef&0.  The result is known zero, not undef.
1599     UndefElts &= UndefElts2;
1600     break;
1601     
1602   case Instruction::Call: {
1603     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1604     if (!II) break;
1605     switch (II->getIntrinsicID()) {
1606     default: break;
1607       
1608     // Binary vector operations that work column-wise.  A dest element is a
1609     // function of the corresponding input elements from the two inputs.
1610     case Intrinsic::x86_sse_sub_ss:
1611     case Intrinsic::x86_sse_mul_ss:
1612     case Intrinsic::x86_sse_min_ss:
1613     case Intrinsic::x86_sse_max_ss:
1614     case Intrinsic::x86_sse2_sub_sd:
1615     case Intrinsic::x86_sse2_mul_sd:
1616     case Intrinsic::x86_sse2_min_sd:
1617     case Intrinsic::x86_sse2_max_sd:
1618       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1619                                         UndefElts, Depth+1);
1620       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1621       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1622                                         UndefElts2, Depth+1);
1623       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1624
1625       // If only the low elt is demanded and this is a scalarizable intrinsic,
1626       // scalarize it now.
1627       if (DemandedElts == 1) {
1628         switch (II->getIntrinsicID()) {
1629         default: break;
1630         case Intrinsic::x86_sse_sub_ss:
1631         case Intrinsic::x86_sse_mul_ss:
1632         case Intrinsic::x86_sse2_sub_sd:
1633         case Intrinsic::x86_sse2_mul_sd:
1634           // TODO: Lower MIN/MAX/ABS/etc
1635           Value *LHS = II->getOperand(1);
1636           Value *RHS = II->getOperand(2);
1637           // Extract the element as scalars.
1638           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1639           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1640           
1641           switch (II->getIntrinsicID()) {
1642           default: assert(0 && "Case stmts out of sync!");
1643           case Intrinsic::x86_sse_sub_ss:
1644           case Intrinsic::x86_sse2_sub_sd:
1645             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1646                                                         II->getName()), *II);
1647             break;
1648           case Intrinsic::x86_sse_mul_ss:
1649           case Intrinsic::x86_sse2_mul_sd:
1650             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1651                                                          II->getName()), *II);
1652             break;
1653           }
1654           
1655           Instruction *New =
1656             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1657                                   II->getName());
1658           InsertNewInstBefore(New, *II);
1659           AddSoonDeadInstToWorklist(*II, 0);
1660           return New;
1661         }            
1662       }
1663         
1664       // Output elements are undefined if both are undefined.  Consider things
1665       // like undef&0.  The result is known zero, not undef.
1666       UndefElts &= UndefElts2;
1667       break;
1668     }
1669     break;
1670   }
1671   }
1672   return MadeChange ? I : 0;
1673 }
1674
1675 /// @returns true if the specified compare predicate is
1676 /// true when both operands are equal...
1677 /// @brief Determine if the icmp Predicate is true when both operands are equal
1678 static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
1679   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1680          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1681          pred == ICmpInst::ICMP_SLE;
1682 }
1683
1684 /// @returns true if the specified compare instruction is
1685 /// true when both operands are equal...
1686 /// @brief Determine if the ICmpInst returns true when both operands are equal
1687 static bool isTrueWhenEqual(ICmpInst &ICI) {
1688   return isTrueWhenEqual(ICI.getPredicate());
1689 }
1690
1691 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1692 /// function is designed to check a chain of associative operators for a
1693 /// potential to apply a certain optimization.  Since the optimization may be
1694 /// applicable if the expression was reassociated, this checks the chain, then
1695 /// reassociates the expression as necessary to expose the optimization
1696 /// opportunity.  This makes use of a special Functor, which must define
1697 /// 'shouldApply' and 'apply' methods.
1698 ///
1699 template<typename Functor>
1700 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1701   unsigned Opcode = Root.getOpcode();
1702   Value *LHS = Root.getOperand(0);
1703
1704   // Quick check, see if the immediate LHS matches...
1705   if (F.shouldApply(LHS))
1706     return F.apply(Root);
1707
1708   // Otherwise, if the LHS is not of the same opcode as the root, return.
1709   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1710   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1711     // Should we apply this transform to the RHS?
1712     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1713
1714     // If not to the RHS, check to see if we should apply to the LHS...
1715     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1716       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1717       ShouldApply = true;
1718     }
1719
1720     // If the functor wants to apply the optimization to the RHS of LHSI,
1721     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1722     if (ShouldApply) {
1723       BasicBlock *BB = Root.getParent();
1724
1725       // Now all of the instructions are in the current basic block, go ahead
1726       // and perform the reassociation.
1727       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1728
1729       // First move the selected RHS to the LHS of the root...
1730       Root.setOperand(0, LHSI->getOperand(1));
1731
1732       // Make what used to be the LHS of the root be the user of the root...
1733       Value *ExtraOperand = TmpLHSI->getOperand(1);
1734       if (&Root == TmpLHSI) {
1735         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1736         return 0;
1737       }
1738       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1739       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1740       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1741       BasicBlock::iterator ARI = &Root; ++ARI;
1742       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1743       ARI = Root;
1744
1745       // Now propagate the ExtraOperand down the chain of instructions until we
1746       // get to LHSI.
1747       while (TmpLHSI != LHSI) {
1748         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1749         // Move the instruction to immediately before the chain we are
1750         // constructing to avoid breaking dominance properties.
1751         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1752         BB->getInstList().insert(ARI, NextLHSI);
1753         ARI = NextLHSI;
1754
1755         Value *NextOp = NextLHSI->getOperand(1);
1756         NextLHSI->setOperand(1, ExtraOperand);
1757         TmpLHSI = NextLHSI;
1758         ExtraOperand = NextOp;
1759       }
1760
1761       // Now that the instructions are reassociated, have the functor perform
1762       // the transformation...
1763       return F.apply(Root);
1764     }
1765
1766     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1767   }
1768   return 0;
1769 }
1770
1771
1772 // AddRHS - Implements: X + X --> X << 1
1773 struct AddRHS {
1774   Value *RHS;
1775   AddRHS(Value *rhs) : RHS(rhs) {}
1776   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1777   Instruction *apply(BinaryOperator &Add) const {
1778     return BinaryOperator::createShl(Add.getOperand(0),
1779                                   ConstantInt::get(Add.getType(), 1));
1780   }
1781 };
1782
1783 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1784 //                 iff C1&C2 == 0
1785 struct AddMaskingAnd {
1786   Constant *C2;
1787   AddMaskingAnd(Constant *c) : C2(c) {}
1788   bool shouldApply(Value *LHS) const {
1789     ConstantInt *C1;
1790     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1791            ConstantExpr::getAnd(C1, C2)->isNullValue();
1792   }
1793   Instruction *apply(BinaryOperator &Add) const {
1794     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1795   }
1796 };
1797
1798 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1799                                              InstCombiner *IC) {
1800   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1801     if (Constant *SOC = dyn_cast<Constant>(SO))
1802       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1803
1804     return IC->InsertNewInstBefore(CastInst::create(
1805           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1806   }
1807
1808   // Figure out if the constant is the left or the right argument.
1809   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1810   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1811
1812   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1813     if (ConstIsRHS)
1814       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1815     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1816   }
1817
1818   Value *Op0 = SO, *Op1 = ConstOperand;
1819   if (!ConstIsRHS)
1820     std::swap(Op0, Op1);
1821   Instruction *New;
1822   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1823     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1824   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1825     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1826                           SO->getName()+".cmp");
1827   else {
1828     assert(0 && "Unknown binary instruction type!");
1829     abort();
1830   }
1831   return IC->InsertNewInstBefore(New, I);
1832 }
1833
1834 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1835 // constant as the other operand, try to fold the binary operator into the
1836 // select arguments.  This also works for Cast instructions, which obviously do
1837 // not have a second operand.
1838 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1839                                      InstCombiner *IC) {
1840   // Don't modify shared select instructions
1841   if (!SI->hasOneUse()) return 0;
1842   Value *TV = SI->getOperand(1);
1843   Value *FV = SI->getOperand(2);
1844
1845   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1846     // Bool selects with constant operands can be folded to logical ops.
1847     if (SI->getType() == Type::Int1Ty) return 0;
1848
1849     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1850     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1851
1852     return new SelectInst(SI->getCondition(), SelectTrueVal,
1853                           SelectFalseVal);
1854   }
1855   return 0;
1856 }
1857
1858
1859 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1860 /// node as operand #0, see if we can fold the instruction into the PHI (which
1861 /// is only possible if all operands to the PHI are constants).
1862 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1863   PHINode *PN = cast<PHINode>(I.getOperand(0));
1864   unsigned NumPHIValues = PN->getNumIncomingValues();
1865   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1866
1867   // Check to see if all of the operands of the PHI are constants.  If there is
1868   // one non-constant value, remember the BB it is.  If there is more than one
1869   // or if *it* is a PHI, bail out.
1870   BasicBlock *NonConstBB = 0;
1871   for (unsigned i = 0; i != NumPHIValues; ++i)
1872     if (!isa<Constant>(PN->getIncomingValue(i))) {
1873       if (NonConstBB) return 0;  // More than one non-const value.
1874       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1875       NonConstBB = PN->getIncomingBlock(i);
1876       
1877       // If the incoming non-constant value is in I's block, we have an infinite
1878       // loop.
1879       if (NonConstBB == I.getParent())
1880         return 0;
1881     }
1882   
1883   // If there is exactly one non-constant value, we can insert a copy of the
1884   // operation in that block.  However, if this is a critical edge, we would be
1885   // inserting the computation one some other paths (e.g. inside a loop).  Only
1886   // do this if the pred block is unconditionally branching into the phi block.
1887   if (NonConstBB) {
1888     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1889     if (!BI || !BI->isUnconditional()) return 0;
1890   }
1891
1892   // Okay, we can do the transformation: create the new PHI node.
1893   PHINode *NewPN = new PHINode(I.getType(), "");
1894   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1895   InsertNewInstBefore(NewPN, *PN);
1896   NewPN->takeName(PN);
1897
1898   // Next, add all of the operands to the PHI.
1899   if (I.getNumOperands() == 2) {
1900     Constant *C = cast<Constant>(I.getOperand(1));
1901     for (unsigned i = 0; i != NumPHIValues; ++i) {
1902       Value *InV = 0;
1903       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1904         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1905           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1906         else
1907           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1908       } else {
1909         assert(PN->getIncomingBlock(i) == NonConstBB);
1910         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1911           InV = BinaryOperator::create(BO->getOpcode(),
1912                                        PN->getIncomingValue(i), C, "phitmp",
1913                                        NonConstBB->getTerminator());
1914         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1915           InV = CmpInst::create(CI->getOpcode(), 
1916                                 CI->getPredicate(),
1917                                 PN->getIncomingValue(i), C, "phitmp",
1918                                 NonConstBB->getTerminator());
1919         else
1920           assert(0 && "Unknown binop!");
1921         
1922         AddToWorkList(cast<Instruction>(InV));
1923       }
1924       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1925     }
1926   } else { 
1927     CastInst *CI = cast<CastInst>(&I);
1928     const Type *RetTy = CI->getType();
1929     for (unsigned i = 0; i != NumPHIValues; ++i) {
1930       Value *InV;
1931       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1932         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1933       } else {
1934         assert(PN->getIncomingBlock(i) == NonConstBB);
1935         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1936                                I.getType(), "phitmp", 
1937                                NonConstBB->getTerminator());
1938         AddToWorkList(cast<Instruction>(InV));
1939       }
1940       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1941     }
1942   }
1943   return ReplaceInstUsesWith(I, NewPN);
1944 }
1945
1946
1947 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
1948 /// value is never equal to -0.0.
1949 ///
1950 /// Note that this function will need to be revisited when we support nondefault
1951 /// rounding modes!
1952 ///
1953 static bool CannotBeNegativeZero(const Value *V) {
1954   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1955     return !CFP->getValueAPF().isNegZero();
1956
1957   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1958   if (const Instruction *I = dyn_cast<Instruction>(V)) {
1959     if (I->getOpcode() == Instruction::Add &&
1960         isa<ConstantFP>(I->getOperand(1)) && 
1961         cast<ConstantFP>(I->getOperand(1))->isNullValue())
1962       return true;
1963     
1964     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1965       if (II->getIntrinsicID() == Intrinsic::sqrt)
1966         return CannotBeNegativeZero(II->getOperand(1));
1967     
1968     if (const CallInst *CI = dyn_cast<CallInst>(I))
1969       if (const Function *F = CI->getCalledFunction()) {
1970         if (F->isDeclaration()) {
1971           switch (F->getNameLen()) {
1972           case 3:  // abs(x) != -0.0
1973             if (!strcmp(F->getNameStart(), "abs")) return true;
1974             break;
1975           case 4:  // abs[lf](x) != -0.0
1976             if (!strcmp(F->getNameStart(), "absf")) return true;
1977             if (!strcmp(F->getNameStart(), "absl")) return true;
1978             break;
1979           }
1980         }
1981       }
1982   }
1983   
1984   return false;
1985 }
1986
1987
1988 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1989   bool Changed = SimplifyCommutative(I);
1990   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1991
1992   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1993     // X + undef -> undef
1994     if (isa<UndefValue>(RHS))
1995       return ReplaceInstUsesWith(I, RHS);
1996
1997     // X + 0 --> X
1998     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1999       if (RHSC->isNullValue())
2000         return ReplaceInstUsesWith(I, LHS);
2001     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2002       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2003                               (I.getType())->getValueAPF()))
2004         return ReplaceInstUsesWith(I, LHS);
2005     }
2006
2007     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2008       // X + (signbit) --> X ^ signbit
2009       const APInt& Val = CI->getValue();
2010       uint32_t BitWidth = Val.getBitWidth();
2011       if (Val == APInt::getSignBit(BitWidth))
2012         return BinaryOperator::createXor(LHS, RHS);
2013       
2014       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2015       // (X & 254)+1 -> (X&254)|1
2016       if (!isa<VectorType>(I.getType())) {
2017         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2018         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2019                                  KnownZero, KnownOne))
2020           return &I;
2021       }
2022     }
2023
2024     if (isa<PHINode>(LHS))
2025       if (Instruction *NV = FoldOpIntoPhi(I))
2026         return NV;
2027     
2028     ConstantInt *XorRHS = 0;
2029     Value *XorLHS = 0;
2030     if (isa<ConstantInt>(RHSC) &&
2031         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2032       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2033       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2034       
2035       uint32_t Size = TySizeBits / 2;
2036       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2037       APInt CFF80Val(-C0080Val);
2038       do {
2039         if (TySizeBits > Size) {
2040           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2041           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2042           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2043               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2044             // This is a sign extend if the top bits are known zero.
2045             if (!MaskedValueIsZero(XorLHS, 
2046                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2047               Size = 0;  // Not a sign ext, but can't be any others either.
2048             break;
2049           }
2050         }
2051         Size >>= 1;
2052         C0080Val = APIntOps::lshr(C0080Val, Size);
2053         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2054       } while (Size >= 1);
2055       
2056       // FIXME: This shouldn't be necessary. When the backends can handle types
2057       // with funny bit widths then this whole cascade of if statements should
2058       // be removed. It is just here to get the size of the "middle" type back
2059       // up to something that the back ends can handle.
2060       const Type *MiddleType = 0;
2061       switch (Size) {
2062         default: break;
2063         case 32: MiddleType = Type::Int32Ty; break;
2064         case 16: MiddleType = Type::Int16Ty; break;
2065         case  8: MiddleType = Type::Int8Ty; break;
2066       }
2067       if (MiddleType) {
2068         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2069         InsertNewInstBefore(NewTrunc, I);
2070         return new SExtInst(NewTrunc, I.getType(), I.getName());
2071       }
2072     }
2073   }
2074
2075   // X + X --> X << 1
2076   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2077     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2078
2079     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2080       if (RHSI->getOpcode() == Instruction::Sub)
2081         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2082           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2083     }
2084     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2085       if (LHSI->getOpcode() == Instruction::Sub)
2086         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2087           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2088     }
2089   }
2090
2091   // -A + B  -->  B - A
2092   if (Value *V = dyn_castNegVal(LHS))
2093     return BinaryOperator::createSub(RHS, V);
2094
2095   // A + -B  -->  A - B
2096   if (!isa<Constant>(RHS))
2097     if (Value *V = dyn_castNegVal(RHS))
2098       return BinaryOperator::createSub(LHS, V);
2099
2100
2101   ConstantInt *C2;
2102   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2103     if (X == RHS)   // X*C + X --> X * (C+1)
2104       return BinaryOperator::createMul(RHS, AddOne(C2));
2105
2106     // X*C1 + X*C2 --> X * (C1+C2)
2107     ConstantInt *C1;
2108     if (X == dyn_castFoldableMul(RHS, C1))
2109       return BinaryOperator::createMul(X, Add(C1, C2));
2110   }
2111
2112   // X + X*C --> X * (C+1)
2113   if (dyn_castFoldableMul(RHS, C2) == LHS)
2114     return BinaryOperator::createMul(LHS, AddOne(C2));
2115
2116   // X + ~X --> -1   since   ~X = -X-1
2117   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2118     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2119   
2120
2121   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2122   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2123     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2124       return R;
2125
2126   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2127   if (I.getType()->isIntOrIntVector()) {
2128     Value *W, *X, *Y, *Z;
2129     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2130         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2131       if (W != Y) {
2132         if (W == Z) {
2133           std::swap(Y, Z);
2134         } else if (Y == X) {
2135           std::swap(W, X);
2136         } else if (X == Z) {
2137           std::swap(Y, Z);
2138           std::swap(W, X);
2139         }
2140       }
2141
2142       if (W == Y) {
2143         Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2144                                                             LHS->getName()), I);
2145         return BinaryOperator::createMul(W, NewAdd);
2146       }
2147     }
2148   }
2149
2150   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2151     Value *X = 0;
2152     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2153       return BinaryOperator::createSub(SubOne(CRHS), X);
2154
2155     // (X & FF00) + xx00  -> (X+xx00) & FF00
2156     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2157       Constant *Anded = And(CRHS, C2);
2158       if (Anded == CRHS) {
2159         // See if all bits from the first bit set in the Add RHS up are included
2160         // in the mask.  First, get the rightmost bit.
2161         const APInt& AddRHSV = CRHS->getValue();
2162
2163         // Form a mask of all bits from the lowest bit added through the top.
2164         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2165
2166         // See if the and mask includes all of these bits.
2167         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2168
2169         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2170           // Okay, the xform is safe.  Insert the new add pronto.
2171           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2172                                                             LHS->getName()), I);
2173           return BinaryOperator::createAnd(NewAdd, C2);
2174         }
2175       }
2176     }
2177
2178     // Try to fold constant add into select arguments.
2179     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2180       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2181         return R;
2182   }
2183
2184   // add (cast *A to intptrtype) B -> 
2185   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2186   {
2187     CastInst *CI = dyn_cast<CastInst>(LHS);
2188     Value *Other = RHS;
2189     if (!CI) {
2190       CI = dyn_cast<CastInst>(RHS);
2191       Other = LHS;
2192     }
2193     if (CI && CI->getType()->isSized() && 
2194         (CI->getType()->getPrimitiveSizeInBits() == 
2195          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2196         && isa<PointerType>(CI->getOperand(0)->getType())) {
2197       unsigned AS =
2198         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2199       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2200                                       PointerType::get(Type::Int8Ty, AS), I);
2201       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2202       return new PtrToIntInst(I2, CI->getType());
2203     }
2204   }
2205   
2206   // add (select X 0 (sub n A)) A  -->  select X A n
2207   {
2208     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2209     Value *Other = RHS;
2210     if (!SI) {
2211       SI = dyn_cast<SelectInst>(RHS);
2212       Other = LHS;
2213     }
2214     if (SI && SI->hasOneUse()) {
2215       Value *TV = SI->getTrueValue();
2216       Value *FV = SI->getFalseValue();
2217       Value *A, *N;
2218
2219       // Can we fold the add into the argument of the select?
2220       // We check both true and false select arguments for a matching subtract.
2221       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2222           A == Other)  // Fold the add into the true select value.
2223         return new SelectInst(SI->getCondition(), N, A);
2224       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2225           A == Other)  // Fold the add into the false select value.
2226         return new SelectInst(SI->getCondition(), A, N);
2227     }
2228   }
2229   
2230   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2231   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2232     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2233       return ReplaceInstUsesWith(I, LHS);
2234
2235   return Changed ? &I : 0;
2236 }
2237
2238 // isSignBit - Return true if the value represented by the constant only has the
2239 // highest order bit set.
2240 static bool isSignBit(ConstantInt *CI) {
2241   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2242   return CI->getValue() == APInt::getSignBit(NumBits);
2243 }
2244
2245 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2246   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2247
2248   if (Op0 == Op1)         // sub X, X  -> 0
2249     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2250
2251   // If this is a 'B = x-(-A)', change to B = x+A...
2252   if (Value *V = dyn_castNegVal(Op1))
2253     return BinaryOperator::createAdd(Op0, V);
2254
2255   if (isa<UndefValue>(Op0))
2256     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2257   if (isa<UndefValue>(Op1))
2258     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2259
2260   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2261     // Replace (-1 - A) with (~A)...
2262     if (C->isAllOnesValue())
2263       return BinaryOperator::createNot(Op1);
2264
2265     // C - ~X == X + (1+C)
2266     Value *X = 0;
2267     if (match(Op1, m_Not(m_Value(X))))
2268       return BinaryOperator::createAdd(X, AddOne(C));
2269
2270     // -(X >>u 31) -> (X >>s 31)
2271     // -(X >>s 31) -> (X >>u 31)
2272     if (C->isZero()) {
2273       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2274         if (SI->getOpcode() == Instruction::LShr) {
2275           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2276             // Check to see if we are shifting out everything but the sign bit.
2277             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2278                 SI->getType()->getPrimitiveSizeInBits()-1) {
2279               // Ok, the transformation is safe.  Insert AShr.
2280               return BinaryOperator::create(Instruction::AShr, 
2281                                           SI->getOperand(0), CU, SI->getName());
2282             }
2283           }
2284         }
2285         else if (SI->getOpcode() == Instruction::AShr) {
2286           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2287             // Check to see if we are shifting out everything but the sign bit.
2288             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2289                 SI->getType()->getPrimitiveSizeInBits()-1) {
2290               // Ok, the transformation is safe.  Insert LShr. 
2291               return BinaryOperator::createLShr(
2292                                           SI->getOperand(0), CU, SI->getName());
2293             }
2294           }
2295         } 
2296     }
2297
2298     // Try to fold constant sub into select arguments.
2299     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2300       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2301         return R;
2302
2303     if (isa<PHINode>(Op0))
2304       if (Instruction *NV = FoldOpIntoPhi(I))
2305         return NV;
2306   }
2307
2308   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2309     if (Op1I->getOpcode() == Instruction::Add &&
2310         !Op0->getType()->isFPOrFPVector()) {
2311       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2312         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2313       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2314         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2315       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2316         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2317           // C1-(X+C2) --> (C1-C2)-X
2318           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2319                                            Op1I->getOperand(0));
2320       }
2321     }
2322
2323     if (Op1I->hasOneUse()) {
2324       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2325       // is not used by anyone else...
2326       //
2327       if (Op1I->getOpcode() == Instruction::Sub &&
2328           !Op1I->getType()->isFPOrFPVector()) {
2329         // Swap the two operands of the subexpr...
2330         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2331         Op1I->setOperand(0, IIOp1);
2332         Op1I->setOperand(1, IIOp0);
2333
2334         // Create the new top level add instruction...
2335         return BinaryOperator::createAdd(Op0, Op1);
2336       }
2337
2338       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2339       //
2340       if (Op1I->getOpcode() == Instruction::And &&
2341           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2342         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2343
2344         Value *NewNot =
2345           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2346         return BinaryOperator::createAnd(Op0, NewNot);
2347       }
2348
2349       // 0 - (X sdiv C)  -> (X sdiv -C)
2350       if (Op1I->getOpcode() == Instruction::SDiv)
2351         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2352           if (CSI->isZero())
2353             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2354               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2355                                                ConstantExpr::getNeg(DivRHS));
2356
2357       // X - X*C --> X * (1-C)
2358       ConstantInt *C2 = 0;
2359       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2360         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2361         return BinaryOperator::createMul(Op0, CP1);
2362       }
2363
2364       // X - ((X / Y) * Y) --> X % Y
2365       if (Op1I->getOpcode() == Instruction::Mul)
2366         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2367           if (Op0 == I->getOperand(0) &&
2368               Op1I->getOperand(1) == I->getOperand(1)) {
2369             if (I->getOpcode() == Instruction::SDiv)
2370               return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2371             if (I->getOpcode() == Instruction::UDiv)
2372               return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2373           }
2374     }
2375   }
2376
2377   if (!Op0->getType()->isFPOrFPVector())
2378     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2379       if (Op0I->getOpcode() == Instruction::Add) {
2380         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2381           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2382         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2383           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2384       } else if (Op0I->getOpcode() == Instruction::Sub) {
2385         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2386           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2387       }
2388
2389   ConstantInt *C1;
2390   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2391     if (X == Op1)  // X*C - X --> X * (C-1)
2392       return BinaryOperator::createMul(Op1, SubOne(C1));
2393
2394     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2395     if (X == dyn_castFoldableMul(Op1, C2))
2396       return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2397   }
2398   return 0;
2399 }
2400
2401 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2402 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2403 /// TrueIfSigned if the result of the comparison is true when the input value is
2404 /// signed.
2405 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2406                            bool &TrueIfSigned) {
2407   switch (pred) {
2408   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2409     TrueIfSigned = true;
2410     return RHS->isZero();
2411   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2412     TrueIfSigned = true;
2413     return RHS->isAllOnesValue();
2414   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2415     TrueIfSigned = false;
2416     return RHS->isAllOnesValue();
2417   case ICmpInst::ICMP_UGT:
2418     // True if LHS u> RHS and RHS == high-bit-mask - 1
2419     TrueIfSigned = true;
2420     return RHS->getValue() ==
2421       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2422   case ICmpInst::ICMP_UGE: 
2423     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2424     TrueIfSigned = true;
2425     return RHS->getValue() == 
2426       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2427   default:
2428     return false;
2429   }
2430 }
2431
2432 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2433   bool Changed = SimplifyCommutative(I);
2434   Value *Op0 = I.getOperand(0);
2435
2436   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2437     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2438
2439   // Simplify mul instructions with a constant RHS...
2440   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2441     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2442
2443       // ((X << C1)*C2) == (X * (C2 << C1))
2444       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2445         if (SI->getOpcode() == Instruction::Shl)
2446           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2447             return BinaryOperator::createMul(SI->getOperand(0),
2448                                              ConstantExpr::getShl(CI, ShOp));
2449
2450       if (CI->isZero())
2451         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2452       if (CI->equalsInt(1))                  // X * 1  == X
2453         return ReplaceInstUsesWith(I, Op0);
2454       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2455         return BinaryOperator::createNeg(Op0, I.getName());
2456
2457       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2458       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2459         return BinaryOperator::createShl(Op0,
2460                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2461       }
2462     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2463       if (Op1F->isNullValue())
2464         return ReplaceInstUsesWith(I, Op1);
2465
2466       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2467       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2468       // We need a better interface for long double here.
2469       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2470         if (Op1F->isExactlyValue(1.0))
2471           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2472     }
2473     
2474     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2475       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2476           isa<ConstantInt>(Op0I->getOperand(1))) {
2477         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2478         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2479                                                      Op1, "tmp");
2480         InsertNewInstBefore(Add, I);
2481         Value *C1C2 = ConstantExpr::getMul(Op1, 
2482                                            cast<Constant>(Op0I->getOperand(1)));
2483         return BinaryOperator::createAdd(Add, C1C2);
2484         
2485       }
2486
2487     // Try to fold constant mul into select arguments.
2488     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2489       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2490         return R;
2491
2492     if (isa<PHINode>(Op0))
2493       if (Instruction *NV = FoldOpIntoPhi(I))
2494         return NV;
2495   }
2496
2497   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2498     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2499       return BinaryOperator::createMul(Op0v, Op1v);
2500
2501   // If one of the operands of the multiply is a cast from a boolean value, then
2502   // we know the bool is either zero or one, so this is a 'masking' multiply.
2503   // See if we can simplify things based on how the boolean was originally
2504   // formed.
2505   CastInst *BoolCast = 0;
2506   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2507     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2508       BoolCast = CI;
2509   if (!BoolCast)
2510     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2511       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2512         BoolCast = CI;
2513   if (BoolCast) {
2514     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2515       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2516       const Type *SCOpTy = SCIOp0->getType();
2517       bool TIS = false;
2518       
2519       // If the icmp is true iff the sign bit of X is set, then convert this
2520       // multiply into a shift/and combination.
2521       if (isa<ConstantInt>(SCIOp1) &&
2522           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2523           TIS) {
2524         // Shift the X value right to turn it into "all signbits".
2525         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2526                                           SCOpTy->getPrimitiveSizeInBits()-1);
2527         Value *V =
2528           InsertNewInstBefore(
2529             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2530                                             BoolCast->getOperand(0)->getName()+
2531                                             ".mask"), I);
2532
2533         // If the multiply type is not the same as the source type, sign extend
2534         // or truncate to the multiply type.
2535         if (I.getType() != V->getType()) {
2536           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2537           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2538           Instruction::CastOps opcode = 
2539             (SrcBits == DstBits ? Instruction::BitCast : 
2540              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2541           V = InsertCastBefore(opcode, V, I.getType(), I);
2542         }
2543
2544         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2545         return BinaryOperator::createAnd(V, OtherOp);
2546       }
2547     }
2548   }
2549
2550   return Changed ? &I : 0;
2551 }
2552
2553 /// This function implements the transforms on div instructions that work
2554 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2555 /// used by the visitors to those instructions.
2556 /// @brief Transforms common to all three div instructions
2557 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2558   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2559
2560   // undef / X -> 0
2561   if (isa<UndefValue>(Op0))
2562     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2563
2564   // X / undef -> undef
2565   if (isa<UndefValue>(Op1))
2566     return ReplaceInstUsesWith(I, Op1);
2567
2568   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2569   // This does not apply for fdiv.
2570   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2571     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2572     // the same basic block, then we replace the select with Y, and the
2573     // condition of the select with false (if the cond value is in the same BB).
2574     // If the select has uses other than the div, this allows them to be
2575     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2576     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2577       if (ST->isNullValue()) {
2578         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2579         if (CondI && CondI->getParent() == I.getParent())
2580           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2581         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2582           I.setOperand(1, SI->getOperand(2));
2583         else
2584           UpdateValueUsesWith(SI, SI->getOperand(2));
2585         return &I;
2586       }
2587
2588     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2589     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2590       if (ST->isNullValue()) {
2591         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2592         if (CondI && CondI->getParent() == I.getParent())
2593           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2594         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2595           I.setOperand(1, SI->getOperand(1));
2596         else
2597           UpdateValueUsesWith(SI, SI->getOperand(1));
2598         return &I;
2599       }
2600   }
2601
2602   return 0;
2603 }
2604
2605 /// This function implements the transforms common to both integer division
2606 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2607 /// division instructions.
2608 /// @brief Common integer divide transforms
2609 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2610   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2611
2612   if (Instruction *Common = commonDivTransforms(I))
2613     return Common;
2614
2615   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2616     // div X, 1 == X
2617     if (RHS->equalsInt(1))
2618       return ReplaceInstUsesWith(I, Op0);
2619
2620     // (X / C1) / C2  -> X / (C1*C2)
2621     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2622       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2623         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2624           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2625                                         Multiply(RHS, LHSRHS));
2626         }
2627
2628     if (!RHS->isZero()) { // avoid X udiv 0
2629       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2630         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2631           return R;
2632       if (isa<PHINode>(Op0))
2633         if (Instruction *NV = FoldOpIntoPhi(I))
2634           return NV;
2635     }
2636   }
2637
2638   // 0 / X == 0, we don't need to preserve faults!
2639   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2640     if (LHS->equalsInt(0))
2641       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2642
2643   return 0;
2644 }
2645
2646 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2647   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2648
2649   // Handle the integer div common cases
2650   if (Instruction *Common = commonIDivTransforms(I))
2651     return Common;
2652
2653   // X udiv C^2 -> X >> C
2654   // Check to see if this is an unsigned division with an exact power of 2,
2655   // if so, convert to a right shift.
2656   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2657     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2658       return BinaryOperator::createLShr(Op0, 
2659                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2660   }
2661
2662   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2663   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2664     if (RHSI->getOpcode() == Instruction::Shl &&
2665         isa<ConstantInt>(RHSI->getOperand(0))) {
2666       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2667       if (C1.isPowerOf2()) {
2668         Value *N = RHSI->getOperand(1);
2669         const Type *NTy = N->getType();
2670         if (uint32_t C2 = C1.logBase2()) {
2671           Constant *C2V = ConstantInt::get(NTy, C2);
2672           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2673         }
2674         return BinaryOperator::createLShr(Op0, N);
2675       }
2676     }
2677   }
2678   
2679   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2680   // where C1&C2 are powers of two.
2681   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2682     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2683       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2684         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2685         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2686           // Compute the shift amounts
2687           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2688           // Construct the "on true" case of the select
2689           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2690           Instruction *TSI = BinaryOperator::createLShr(
2691                                                  Op0, TC, SI->getName()+".t");
2692           TSI = InsertNewInstBefore(TSI, I);
2693   
2694           // Construct the "on false" case of the select
2695           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2696           Instruction *FSI = BinaryOperator::createLShr(
2697                                                  Op0, FC, SI->getName()+".f");
2698           FSI = InsertNewInstBefore(FSI, I);
2699
2700           // construct the select instruction and return it.
2701           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2702         }
2703       }
2704   return 0;
2705 }
2706
2707 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2708   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2709
2710   // Handle the integer div common cases
2711   if (Instruction *Common = commonIDivTransforms(I))
2712     return Common;
2713
2714   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2715     // sdiv X, -1 == -X
2716     if (RHS->isAllOnesValue())
2717       return BinaryOperator::createNeg(Op0);
2718
2719     // -X/C -> X/-C
2720     if (Value *LHSNeg = dyn_castNegVal(Op0))
2721       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2722   }
2723
2724   // If the sign bits of both operands are zero (i.e. we can prove they are
2725   // unsigned inputs), turn this into a udiv.
2726   if (I.getType()->isInteger()) {
2727     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2728     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2729       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2730       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2731     }
2732   }      
2733   
2734   return 0;
2735 }
2736
2737 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2738   return commonDivTransforms(I);
2739 }
2740
2741 /// GetFactor - If we can prove that the specified value is at least a multiple
2742 /// of some factor, return that factor.
2743 static Constant *GetFactor(Value *V) {
2744   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2745     return CI;
2746   
2747   // Unless we can be tricky, we know this is a multiple of 1.
2748   Constant *Result = ConstantInt::get(V->getType(), 1);
2749   
2750   Instruction *I = dyn_cast<Instruction>(V);
2751   if (!I) return Result;
2752   
2753   if (I->getOpcode() == Instruction::Mul) {
2754     // Handle multiplies by a constant, etc.
2755     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2756                                 GetFactor(I->getOperand(1)));
2757   } else if (I->getOpcode() == Instruction::Shl) {
2758     // (X<<C) -> X * (1 << C)
2759     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2760       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2761       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2762     }
2763   } else if (I->getOpcode() == Instruction::And) {
2764     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2765       // X & 0xFFF0 is known to be a multiple of 16.
2766       uint32_t Zeros = RHS->getValue().countTrailingZeros();
2767       if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
2768         return ConstantExpr::getShl(Result, 
2769                                     ConstantInt::get(Result->getType(), Zeros));
2770     }
2771   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2772     // Only handle int->int casts.
2773     if (!CI->isIntegerCast())
2774       return Result;
2775     Value *Op = CI->getOperand(0);
2776     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2777   }    
2778   return Result;
2779 }
2780
2781 /// This function implements the transforms on rem instructions that work
2782 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2783 /// is used by the visitors to those instructions.
2784 /// @brief Transforms common to all three rem instructions
2785 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2786   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2787
2788   // 0 % X == 0, we don't need to preserve faults!
2789   if (Constant *LHS = dyn_cast<Constant>(Op0))
2790     if (LHS->isNullValue())
2791       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2792
2793   if (isa<UndefValue>(Op0))              // undef % X -> 0
2794     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2795   if (isa<UndefValue>(Op1))
2796     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2797
2798   // Handle cases involving: rem X, (select Cond, Y, Z)
2799   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2800     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2801     // the same basic block, then we replace the select with Y, and the
2802     // condition of the select with false (if the cond value is in the same
2803     // BB).  If the select has uses other than the div, this allows them to be
2804     // simplified also.
2805     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2806       if (ST->isNullValue()) {
2807         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2808         if (CondI && CondI->getParent() == I.getParent())
2809           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2810         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2811           I.setOperand(1, SI->getOperand(2));
2812         else
2813           UpdateValueUsesWith(SI, SI->getOperand(2));
2814         return &I;
2815       }
2816     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2817     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2818       if (ST->isNullValue()) {
2819         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2820         if (CondI && CondI->getParent() == I.getParent())
2821           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2822         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2823           I.setOperand(1, SI->getOperand(1));
2824         else
2825           UpdateValueUsesWith(SI, SI->getOperand(1));
2826         return &I;
2827       }
2828   }
2829
2830   return 0;
2831 }
2832
2833 /// This function implements the transforms common to both integer remainder
2834 /// instructions (urem and srem). It is called by the visitors to those integer
2835 /// remainder instructions.
2836 /// @brief Common integer remainder transforms
2837 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2838   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2839
2840   if (Instruction *common = commonRemTransforms(I))
2841     return common;
2842
2843   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2844     // X % 0 == undef, we don't need to preserve faults!
2845     if (RHS->equalsInt(0))
2846       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2847     
2848     if (RHS->equalsInt(1))  // X % 1 == 0
2849       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2850
2851     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2852       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2853         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2854           return R;
2855       } else if (isa<PHINode>(Op0I)) {
2856         if (Instruction *NV = FoldOpIntoPhi(I))
2857           return NV;
2858       }
2859       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2860       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2861         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2862     }
2863   }
2864
2865   return 0;
2866 }
2867
2868 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2869   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2870
2871   if (Instruction *common = commonIRemTransforms(I))
2872     return common;
2873   
2874   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2875     // X urem C^2 -> X and C
2876     // Check to see if this is an unsigned remainder with an exact power of 2,
2877     // if so, convert to a bitwise and.
2878     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2879       if (C->getValue().isPowerOf2())
2880         return BinaryOperator::createAnd(Op0, SubOne(C));
2881   }
2882
2883   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2884     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2885     if (RHSI->getOpcode() == Instruction::Shl &&
2886         isa<ConstantInt>(RHSI->getOperand(0))) {
2887       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2888         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2889         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2890                                                                    "tmp"), I);
2891         return BinaryOperator::createAnd(Op0, Add);
2892       }
2893     }
2894   }
2895
2896   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2897   // where C1&C2 are powers of two.
2898   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2899     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2900       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2901         // STO == 0 and SFO == 0 handled above.
2902         if ((STO->getValue().isPowerOf2()) && 
2903             (SFO->getValue().isPowerOf2())) {
2904           Value *TrueAnd = InsertNewInstBefore(
2905             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2906           Value *FalseAnd = InsertNewInstBefore(
2907             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2908           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2909         }
2910       }
2911   }
2912   
2913   return 0;
2914 }
2915
2916 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2917   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2918
2919   // Handle the integer rem common cases
2920   if (Instruction *common = commonIRemTransforms(I))
2921     return common;
2922   
2923   if (Value *RHSNeg = dyn_castNegVal(Op1))
2924     if (!isa<ConstantInt>(RHSNeg) || 
2925         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2926       // X % -Y -> X % Y
2927       AddUsesToWorkList(I);
2928       I.setOperand(1, RHSNeg);
2929       return &I;
2930     }
2931  
2932   // If the sign bits of both operands are zero (i.e. we can prove they are
2933   // unsigned inputs), turn this into a urem.
2934   if (I.getType()->isInteger()) {
2935     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2936     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2937       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2938       return BinaryOperator::createURem(Op0, Op1, I.getName());
2939     }
2940   }
2941
2942   return 0;
2943 }
2944
2945 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2946   return commonRemTransforms(I);
2947 }
2948
2949 // isMaxValueMinusOne - return true if this is Max-1
2950 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2951   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2952   if (!isSigned)
2953     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2954   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2955 }
2956
2957 // isMinValuePlusOne - return true if this is Min+1
2958 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2959   if (!isSigned)
2960     return C->getValue() == 1; // unsigned
2961     
2962   // Calculate 1111111111000000000000
2963   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2964   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2965 }
2966
2967 // isOneBitSet - Return true if there is exactly one bit set in the specified
2968 // constant.
2969 static bool isOneBitSet(const ConstantInt *CI) {
2970   return CI->getValue().isPowerOf2();
2971 }
2972
2973 // isHighOnes - Return true if the constant is of the form 1+0+.
2974 // This is the same as lowones(~X).
2975 static bool isHighOnes(const ConstantInt *CI) {
2976   return (~CI->getValue() + 1).isPowerOf2();
2977 }
2978
2979 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2980 /// are carefully arranged to allow folding of expressions such as:
2981 ///
2982 ///      (A < B) | (A > B) --> (A != B)
2983 ///
2984 /// Note that this is only valid if the first and second predicates have the
2985 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2986 ///
2987 /// Three bits are used to represent the condition, as follows:
2988 ///   0  A > B
2989 ///   1  A == B
2990 ///   2  A < B
2991 ///
2992 /// <=>  Value  Definition
2993 /// 000     0   Always false
2994 /// 001     1   A >  B
2995 /// 010     2   A == B
2996 /// 011     3   A >= B
2997 /// 100     4   A <  B
2998 /// 101     5   A != B
2999 /// 110     6   A <= B
3000 /// 111     7   Always true
3001 ///  
3002 static unsigned getICmpCode(const ICmpInst *ICI) {
3003   switch (ICI->getPredicate()) {
3004     // False -> 0
3005   case ICmpInst::ICMP_UGT: return 1;  // 001
3006   case ICmpInst::ICMP_SGT: return 1;  // 001
3007   case ICmpInst::ICMP_EQ:  return 2;  // 010
3008   case ICmpInst::ICMP_UGE: return 3;  // 011
3009   case ICmpInst::ICMP_SGE: return 3;  // 011
3010   case ICmpInst::ICMP_ULT: return 4;  // 100
3011   case ICmpInst::ICMP_SLT: return 4;  // 100
3012   case ICmpInst::ICMP_NE:  return 5;  // 101
3013   case ICmpInst::ICMP_ULE: return 6;  // 110
3014   case ICmpInst::ICMP_SLE: return 6;  // 110
3015     // True -> 7
3016   default:
3017     assert(0 && "Invalid ICmp predicate!");
3018     return 0;
3019   }
3020 }
3021
3022 /// getICmpValue - This is the complement of getICmpCode, which turns an
3023 /// opcode and two operands into either a constant true or false, or a brand 
3024 /// new ICmp instruction. The sign is passed in to determine which kind
3025 /// of predicate to use in new icmp instructions.
3026 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3027   switch (code) {
3028   default: assert(0 && "Illegal ICmp code!");
3029   case  0: return ConstantInt::getFalse();
3030   case  1: 
3031     if (sign)
3032       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3033     else
3034       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3035   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3036   case  3: 
3037     if (sign)
3038       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3039     else
3040       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3041   case  4: 
3042     if (sign)
3043       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3044     else
3045       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3046   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3047   case  6: 
3048     if (sign)
3049       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3050     else
3051       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3052   case  7: return ConstantInt::getTrue();
3053   }
3054 }
3055
3056 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3057   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3058     (ICmpInst::isSignedPredicate(p1) && 
3059      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3060     (ICmpInst::isSignedPredicate(p2) && 
3061      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3062 }
3063
3064 namespace { 
3065 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3066 struct FoldICmpLogical {
3067   InstCombiner &IC;
3068   Value *LHS, *RHS;
3069   ICmpInst::Predicate pred;
3070   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3071     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3072       pred(ICI->getPredicate()) {}
3073   bool shouldApply(Value *V) const {
3074     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3075       if (PredicatesFoldable(pred, ICI->getPredicate()))
3076         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3077                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3078     return false;
3079   }
3080   Instruction *apply(Instruction &Log) const {
3081     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3082     if (ICI->getOperand(0) != LHS) {
3083       assert(ICI->getOperand(1) == LHS);
3084       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3085     }
3086
3087     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3088     unsigned LHSCode = getICmpCode(ICI);
3089     unsigned RHSCode = getICmpCode(RHSICI);
3090     unsigned Code;
3091     switch (Log.getOpcode()) {
3092     case Instruction::And: Code = LHSCode & RHSCode; break;
3093     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3094     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3095     default: assert(0 && "Illegal logical opcode!"); return 0;
3096     }
3097
3098     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3099                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3100       
3101     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3102     if (Instruction *I = dyn_cast<Instruction>(RV))
3103       return I;
3104     // Otherwise, it's a constant boolean value...
3105     return IC.ReplaceInstUsesWith(Log, RV);
3106   }
3107 };
3108 } // end anonymous namespace
3109
3110 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3111 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3112 // guaranteed to be a binary operator.
3113 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3114                                     ConstantInt *OpRHS,
3115                                     ConstantInt *AndRHS,
3116                                     BinaryOperator &TheAnd) {
3117   Value *X = Op->getOperand(0);
3118   Constant *Together = 0;
3119   if (!Op->isShift())
3120     Together = And(AndRHS, OpRHS);
3121
3122   switch (Op->getOpcode()) {
3123   case Instruction::Xor:
3124     if (Op->hasOneUse()) {
3125       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3126       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3127       InsertNewInstBefore(And, TheAnd);
3128       And->takeName(Op);
3129       return BinaryOperator::createXor(And, Together);
3130     }
3131     break;
3132   case Instruction::Or:
3133     if (Together == AndRHS) // (X | C) & C --> C
3134       return ReplaceInstUsesWith(TheAnd, AndRHS);
3135
3136     if (Op->hasOneUse() && Together != OpRHS) {
3137       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3138       Instruction *Or = BinaryOperator::createOr(X, Together);
3139       InsertNewInstBefore(Or, TheAnd);
3140       Or->takeName(Op);
3141       return BinaryOperator::createAnd(Or, AndRHS);
3142     }
3143     break;
3144   case Instruction::Add:
3145     if (Op->hasOneUse()) {
3146       // Adding a one to a single bit bit-field should be turned into an XOR
3147       // of the bit.  First thing to check is to see if this AND is with a
3148       // single bit constant.
3149       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3150
3151       // If there is only one bit set...
3152       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3153         // Ok, at this point, we know that we are masking the result of the
3154         // ADD down to exactly one bit.  If the constant we are adding has
3155         // no bits set below this bit, then we can eliminate the ADD.
3156         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3157
3158         // Check to see if any bits below the one bit set in AndRHSV are set.
3159         if ((AddRHS & (AndRHSV-1)) == 0) {
3160           // If not, the only thing that can effect the output of the AND is
3161           // the bit specified by AndRHSV.  If that bit is set, the effect of
3162           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3163           // no effect.
3164           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3165             TheAnd.setOperand(0, X);
3166             return &TheAnd;
3167           } else {
3168             // Pull the XOR out of the AND.
3169             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3170             InsertNewInstBefore(NewAnd, TheAnd);
3171             NewAnd->takeName(Op);
3172             return BinaryOperator::createXor(NewAnd, AndRHS);
3173           }
3174         }
3175       }
3176     }
3177     break;
3178
3179   case Instruction::Shl: {
3180     // We know that the AND will not produce any of the bits shifted in, so if
3181     // the anded constant includes them, clear them now!
3182     //
3183     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3184     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3185     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3186     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3187
3188     if (CI->getValue() == ShlMask) { 
3189     // Masking out bits that the shift already masks
3190       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3191     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3192       TheAnd.setOperand(1, CI);
3193       return &TheAnd;
3194     }
3195     break;
3196   }
3197   case Instruction::LShr:
3198   {
3199     // We know that the AND will not produce any of the bits shifted in, so if
3200     // the anded constant includes them, clear them now!  This only applies to
3201     // unsigned shifts, because a signed shr may bring in set bits!
3202     //
3203     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3204     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3205     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3206     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3207
3208     if (CI->getValue() == ShrMask) {   
3209     // Masking out bits that the shift already masks.
3210       return ReplaceInstUsesWith(TheAnd, Op);
3211     } else if (CI != AndRHS) {
3212       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3213       return &TheAnd;
3214     }
3215     break;
3216   }
3217   case Instruction::AShr:
3218     // Signed shr.
3219     // See if this is shifting in some sign extension, then masking it out
3220     // with an and.
3221     if (Op->hasOneUse()) {
3222       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3223       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3224       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3225       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3226       if (C == AndRHS) {          // Masking out bits shifted in.
3227         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3228         // Make the argument unsigned.
3229         Value *ShVal = Op->getOperand(0);
3230         ShVal = InsertNewInstBefore(
3231             BinaryOperator::createLShr(ShVal, OpRHS, 
3232                                    Op->getName()), TheAnd);
3233         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3234       }
3235     }
3236     break;
3237   }
3238   return 0;
3239 }
3240
3241
3242 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3243 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3244 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3245 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3246 /// insert new instructions.
3247 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3248                                            bool isSigned, bool Inside, 
3249                                            Instruction &IB) {
3250   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3251             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3252          "Lo is not <= Hi in range emission code!");
3253     
3254   if (Inside) {
3255     if (Lo == Hi)  // Trivially false.
3256       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3257
3258     // V >= Min && V < Hi --> V < Hi
3259     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3260       ICmpInst::Predicate pred = (isSigned ? 
3261         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3262       return new ICmpInst(pred, V, Hi);
3263     }
3264
3265     // Emit V-Lo <u Hi-Lo
3266     Constant *NegLo = ConstantExpr::getNeg(Lo);
3267     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3268     InsertNewInstBefore(Add, IB);
3269     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3270     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3271   }
3272
3273   if (Lo == Hi)  // Trivially true.
3274     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3275
3276   // V < Min || V >= Hi -> V > Hi-1
3277   Hi = SubOne(cast<ConstantInt>(Hi));
3278   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3279     ICmpInst::Predicate pred = (isSigned ? 
3280         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3281     return new ICmpInst(pred, V, Hi);
3282   }
3283
3284   // Emit V-Lo >u Hi-1-Lo
3285   // Note that Hi has already had one subtracted from it, above.
3286   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3287   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3288   InsertNewInstBefore(Add, IB);
3289   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3290   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3291 }
3292
3293 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3294 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3295 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3296 // not, since all 1s are not contiguous.
3297 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3298   const APInt& V = Val->getValue();
3299   uint32_t BitWidth = Val->getType()->getBitWidth();
3300   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3301
3302   // look for the first zero bit after the run of ones
3303   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3304   // look for the first non-zero bit
3305   ME = V.getActiveBits(); 
3306   return true;
3307 }
3308
3309 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3310 /// where isSub determines whether the operator is a sub.  If we can fold one of
3311 /// the following xforms:
3312 /// 
3313 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3314 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3315 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3316 ///
3317 /// return (A +/- B).
3318 ///
3319 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3320                                         ConstantInt *Mask, bool isSub,
3321                                         Instruction &I) {
3322   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3323   if (!LHSI || LHSI->getNumOperands() != 2 ||
3324       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3325
3326   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3327
3328   switch (LHSI->getOpcode()) {
3329   default: return 0;
3330   case Instruction::And:
3331     if (And(N, Mask) == Mask) {
3332       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3333       if ((Mask->getValue().countLeadingZeros() + 
3334            Mask->getValue().countPopulation()) == 
3335           Mask->getValue().getBitWidth())
3336         break;
3337
3338       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3339       // part, we don't need any explicit masks to take them out of A.  If that
3340       // is all N is, ignore it.
3341       uint32_t MB = 0, ME = 0;
3342       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3343         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3344         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3345         if (MaskedValueIsZero(RHS, Mask))
3346           break;
3347       }
3348     }
3349     return 0;
3350   case Instruction::Or:
3351   case Instruction::Xor:
3352     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3353     if ((Mask->getValue().countLeadingZeros() + 
3354          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3355         && And(N, Mask)->isZero())
3356       break;
3357     return 0;
3358   }
3359   
3360   Instruction *New;
3361   if (isSub)
3362     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3363   else
3364     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3365   return InsertNewInstBefore(New, I);
3366 }
3367
3368 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3369   bool Changed = SimplifyCommutative(I);
3370   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3371
3372   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3373     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3374
3375   // and X, X = X
3376   if (Op0 == Op1)
3377     return ReplaceInstUsesWith(I, Op1);
3378
3379   // See if we can simplify any instructions used by the instruction whose sole 
3380   // purpose is to compute bits we don't care about.
3381   if (!isa<VectorType>(I.getType())) {
3382     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3383     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3384     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3385                              KnownZero, KnownOne))
3386       return &I;
3387   } else {
3388     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3389       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3390         return ReplaceInstUsesWith(I, I.getOperand(0));
3391     } else if (isa<ConstantAggregateZero>(Op1)) {
3392       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3393     }
3394   }
3395   
3396   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3397     const APInt& AndRHSMask = AndRHS->getValue();
3398     APInt NotAndRHS(~AndRHSMask);
3399
3400     // Optimize a variety of ((val OP C1) & C2) combinations...
3401     if (isa<BinaryOperator>(Op0)) {
3402       Instruction *Op0I = cast<Instruction>(Op0);
3403       Value *Op0LHS = Op0I->getOperand(0);
3404       Value *Op0RHS = Op0I->getOperand(1);
3405       switch (Op0I->getOpcode()) {
3406       case Instruction::Xor:
3407       case Instruction::Or:
3408         // If the mask is only needed on one incoming arm, push it up.
3409         if (Op0I->hasOneUse()) {
3410           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3411             // Not masking anything out for the LHS, move to RHS.
3412             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3413                                                    Op0RHS->getName()+".masked");
3414             InsertNewInstBefore(NewRHS, I);
3415             return BinaryOperator::create(
3416                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3417           }
3418           if (!isa<Constant>(Op0RHS) &&
3419               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3420             // Not masking anything out for the RHS, move to LHS.
3421             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3422                                                    Op0LHS->getName()+".masked");
3423             InsertNewInstBefore(NewLHS, I);
3424             return BinaryOperator::create(
3425                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3426           }
3427         }
3428
3429         break;
3430       case Instruction::Add:
3431         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3432         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3433         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3434         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3435           return BinaryOperator::createAnd(V, AndRHS);
3436         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3437           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3438         break;
3439
3440       case Instruction::Sub:
3441         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3442         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3443         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3444         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3445           return BinaryOperator::createAnd(V, AndRHS);
3446         break;
3447       }
3448
3449       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3450         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3451           return Res;
3452     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3453       // If this is an integer truncation or change from signed-to-unsigned, and
3454       // if the source is an and/or with immediate, transform it.  This
3455       // frequently occurs for bitfield accesses.
3456       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3457         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3458             CastOp->getNumOperands() == 2)
3459           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3460             if (CastOp->getOpcode() == Instruction::And) {
3461               // Change: and (cast (and X, C1) to T), C2
3462               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3463               // This will fold the two constants together, which may allow 
3464               // other simplifications.
3465               Instruction *NewCast = CastInst::createTruncOrBitCast(
3466                 CastOp->getOperand(0), I.getType(), 
3467                 CastOp->getName()+".shrunk");
3468               NewCast = InsertNewInstBefore(NewCast, I);
3469               // trunc_or_bitcast(C1)&C2
3470               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3471               C3 = ConstantExpr::getAnd(C3, AndRHS);
3472               return BinaryOperator::createAnd(NewCast, C3);
3473             } else if (CastOp->getOpcode() == Instruction::Or) {
3474               // Change: and (cast (or X, C1) to T), C2
3475               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3476               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3477               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3478                 return ReplaceInstUsesWith(I, AndRHS);
3479             }
3480       }
3481     }
3482
3483     // Try to fold constant and into select arguments.
3484     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3485       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3486         return R;
3487     if (isa<PHINode>(Op0))
3488       if (Instruction *NV = FoldOpIntoPhi(I))
3489         return NV;
3490   }
3491
3492   Value *Op0NotVal = dyn_castNotVal(Op0);
3493   Value *Op1NotVal = dyn_castNotVal(Op1);
3494
3495   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3496     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3497
3498   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3499   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3500     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3501                                                I.getName()+".demorgan");
3502     InsertNewInstBefore(Or, I);
3503     return BinaryOperator::createNot(Or);
3504   }
3505   
3506   {
3507     Value *A = 0, *B = 0, *C = 0, *D = 0;
3508     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3509       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3510         return ReplaceInstUsesWith(I, Op1);
3511     
3512       // (A|B) & ~(A&B) -> A^B
3513       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3514         if ((A == C && B == D) || (A == D && B == C))
3515           return BinaryOperator::createXor(A, B);
3516       }
3517     }
3518     
3519     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3520       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3521         return ReplaceInstUsesWith(I, Op0);
3522
3523       // ~(A&B) & (A|B) -> A^B
3524       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3525         if ((A == C && B == D) || (A == D && B == C))
3526           return BinaryOperator::createXor(A, B);
3527       }
3528     }
3529     
3530     if (Op0->hasOneUse() &&
3531         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3532       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3533         I.swapOperands();     // Simplify below
3534         std::swap(Op0, Op1);
3535       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3536         cast<BinaryOperator>(Op0)->swapOperands();
3537         I.swapOperands();     // Simplify below
3538         std::swap(Op0, Op1);
3539       }
3540     }
3541     if (Op1->hasOneUse() &&
3542         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3543       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3544         cast<BinaryOperator>(Op1)->swapOperands();
3545         std::swap(A, B);
3546       }
3547       if (A == Op0) {                                // A&(A^B) -> A & ~B
3548         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3549         InsertNewInstBefore(NotB, I);
3550         return BinaryOperator::createAnd(A, NotB);
3551       }
3552     }
3553   }
3554   
3555   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3556     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3557     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3558       return R;
3559
3560     Value *LHSVal, *RHSVal;
3561     ConstantInt *LHSCst, *RHSCst;
3562     ICmpInst::Predicate LHSCC, RHSCC;
3563     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3564       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3565         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3566             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3567             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3568             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3569             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3570             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3571             
3572             // Don't try to fold ICMP_SLT + ICMP_ULT.
3573             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3574              ICmpInst::isSignedPredicate(LHSCC) == 
3575                  ICmpInst::isSignedPredicate(RHSCC))) {
3576           // Ensure that the larger constant is on the RHS.
3577           ICmpInst::Predicate GT;
3578           if (ICmpInst::isSignedPredicate(LHSCC) ||
3579               (ICmpInst::isEquality(LHSCC) && 
3580                ICmpInst::isSignedPredicate(RHSCC)))
3581             GT = ICmpInst::ICMP_SGT;
3582           else
3583             GT = ICmpInst::ICMP_UGT;
3584           
3585           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3586           ICmpInst *LHS = cast<ICmpInst>(Op0);
3587           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3588             std::swap(LHS, RHS);
3589             std::swap(LHSCst, RHSCst);
3590             std::swap(LHSCC, RHSCC);
3591           }
3592
3593           // At this point, we know we have have two icmp instructions
3594           // comparing a value against two constants and and'ing the result
3595           // together.  Because of the above check, we know that we only have
3596           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3597           // (from the FoldICmpLogical check above), that the two constants 
3598           // are not equal and that the larger constant is on the RHS
3599           assert(LHSCst != RHSCst && "Compares not folded above?");
3600
3601           switch (LHSCC) {
3602           default: assert(0 && "Unknown integer condition code!");
3603           case ICmpInst::ICMP_EQ:
3604             switch (RHSCC) {
3605             default: assert(0 && "Unknown integer condition code!");
3606             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3607             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3608             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3609               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3610             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3611             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3612             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3613               return ReplaceInstUsesWith(I, LHS);
3614             }
3615           case ICmpInst::ICMP_NE:
3616             switch (RHSCC) {
3617             default: assert(0 && "Unknown integer condition code!");
3618             case ICmpInst::ICMP_ULT:
3619               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3620                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3621               break;                        // (X != 13 & X u< 15) -> no change
3622             case ICmpInst::ICMP_SLT:
3623               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3624                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3625               break;                        // (X != 13 & X s< 15) -> no change
3626             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3627             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3628             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3629               return ReplaceInstUsesWith(I, RHS);
3630             case ICmpInst::ICMP_NE:
3631               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3632                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3633                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3634                                                       LHSVal->getName()+".off");
3635                 InsertNewInstBefore(Add, I);
3636                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3637                                     ConstantInt::get(Add->getType(), 1));
3638               }
3639               break;                        // (X != 13 & X != 15) -> no change
3640             }
3641             break;
3642           case ICmpInst::ICMP_ULT:
3643             switch (RHSCC) {
3644             default: assert(0 && "Unknown integer condition code!");
3645             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3646             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3647               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3648             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3649               break;
3650             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3651             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3652               return ReplaceInstUsesWith(I, LHS);
3653             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3654               break;
3655             }
3656             break;
3657           case ICmpInst::ICMP_SLT:
3658             switch (RHSCC) {
3659             default: assert(0 && "Unknown integer condition code!");
3660             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3661             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3662               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3663             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3664               break;
3665             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3666             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3667               return ReplaceInstUsesWith(I, LHS);
3668             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3669               break;
3670             }
3671             break;
3672           case ICmpInst::ICMP_UGT:
3673             switch (RHSCC) {
3674             default: assert(0 && "Unknown integer condition code!");
3675             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3676               return ReplaceInstUsesWith(I, LHS);
3677             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3678               return ReplaceInstUsesWith(I, RHS);
3679             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3680               break;
3681             case ICmpInst::ICMP_NE:
3682               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3683                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3684               break;                        // (X u> 13 & X != 15) -> no change
3685             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3686               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3687                                      true, I);
3688             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3689               break;
3690             }
3691             break;
3692           case ICmpInst::ICMP_SGT:
3693             switch (RHSCC) {
3694             default: assert(0 && "Unknown integer condition code!");
3695             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3696             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3697               return ReplaceInstUsesWith(I, RHS);
3698             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3699               break;
3700             case ICmpInst::ICMP_NE:
3701               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3702                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3703               break;                        // (X s> 13 & X != 15) -> no change
3704             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3705               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3706                                      true, I);
3707             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3708               break;
3709             }
3710             break;
3711           }
3712         }
3713   }
3714
3715   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3716   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3717     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3718       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3719         const Type *SrcTy = Op0C->getOperand(0)->getType();
3720         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3721             // Only do this if the casts both really cause code to be generated.
3722             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3723                               I.getType(), TD) &&
3724             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3725                               I.getType(), TD)) {
3726           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3727                                                          Op1C->getOperand(0),
3728                                                          I.getName());
3729           InsertNewInstBefore(NewOp, I);
3730           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3731         }
3732       }
3733     
3734   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3735   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3736     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3737       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3738           SI0->getOperand(1) == SI1->getOperand(1) &&
3739           (SI0->hasOneUse() || SI1->hasOneUse())) {
3740         Instruction *NewOp =
3741           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3742                                                         SI1->getOperand(0),
3743                                                         SI0->getName()), I);
3744         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3745                                       SI1->getOperand(1));
3746       }
3747   }
3748
3749   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3750   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3751     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3752       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3753           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3754         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3755           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3756             // If either of the constants are nans, then the whole thing returns
3757             // false.
3758             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3759               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3760             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3761                                 RHS->getOperand(0));
3762           }
3763     }
3764   }
3765       
3766   return Changed ? &I : 0;
3767 }
3768
3769 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3770 /// in the result.  If it does, and if the specified byte hasn't been filled in
3771 /// yet, fill it in and return false.
3772 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3773   Instruction *I = dyn_cast<Instruction>(V);
3774   if (I == 0) return true;
3775
3776   // If this is an or instruction, it is an inner node of the bswap.
3777   if (I->getOpcode() == Instruction::Or)
3778     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3779            CollectBSwapParts(I->getOperand(1), ByteValues);
3780   
3781   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3782   // If this is a shift by a constant int, and it is "24", then its operand
3783   // defines a byte.  We only handle unsigned types here.
3784   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3785     // Not shifting the entire input by N-1 bytes?
3786     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3787         8*(ByteValues.size()-1))
3788       return true;
3789     
3790     unsigned DestNo;
3791     if (I->getOpcode() == Instruction::Shl) {
3792       // X << 24 defines the top byte with the lowest of the input bytes.
3793       DestNo = ByteValues.size()-1;
3794     } else {
3795       // X >>u 24 defines the low byte with the highest of the input bytes.
3796       DestNo = 0;
3797     }
3798     
3799     // If the destination byte value is already defined, the values are or'd
3800     // together, which isn't a bswap (unless it's an or of the same bits).
3801     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3802       return true;
3803     ByteValues[DestNo] = I->getOperand(0);
3804     return false;
3805   }
3806   
3807   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3808   // don't have this.
3809   Value *Shift = 0, *ShiftLHS = 0;
3810   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3811   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3812       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3813     return true;
3814   Instruction *SI = cast<Instruction>(Shift);
3815
3816   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3817   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3818       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3819     return true;
3820   
3821   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3822   unsigned DestByte;
3823   if (AndAmt->getValue().getActiveBits() > 64)
3824     return true;
3825   uint64_t AndAmtVal = AndAmt->getZExtValue();
3826   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3827     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3828       break;
3829   // Unknown mask for bswap.
3830   if (DestByte == ByteValues.size()) return true;
3831   
3832   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3833   unsigned SrcByte;
3834   if (SI->getOpcode() == Instruction::Shl)
3835     SrcByte = DestByte - ShiftBytes;
3836   else
3837     SrcByte = DestByte + ShiftBytes;
3838   
3839   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3840   if (SrcByte != ByteValues.size()-DestByte-1)
3841     return true;
3842   
3843   // If the destination byte value is already defined, the values are or'd
3844   // together, which isn't a bswap (unless it's an or of the same bits).
3845   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3846     return true;
3847   ByteValues[DestByte] = SI->getOperand(0);
3848   return false;
3849 }
3850
3851 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3852 /// If so, insert the new bswap intrinsic and return it.
3853 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3854   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3855   if (!ITy || ITy->getBitWidth() % 16) 
3856     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3857   
3858   /// ByteValues - For each byte of the result, we keep track of which value
3859   /// defines each byte.
3860   SmallVector<Value*, 8> ByteValues;
3861   ByteValues.resize(ITy->getBitWidth()/8);
3862     
3863   // Try to find all the pieces corresponding to the bswap.
3864   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3865       CollectBSwapParts(I.getOperand(1), ByteValues))
3866     return 0;
3867   
3868   // Check to see if all of the bytes come from the same value.
3869   Value *V = ByteValues[0];
3870   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3871   
3872   // Check to make sure that all of the bytes come from the same value.
3873   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3874     if (ByteValues[i] != V)
3875       return 0;
3876   const Type *Tys[] = { ITy };
3877   Module *M = I.getParent()->getParent()->getParent();
3878   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3879   return new CallInst(F, V);
3880 }
3881
3882
3883 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3884   bool Changed = SimplifyCommutative(I);
3885   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3886
3887   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3888     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3889
3890   // or X, X = X
3891   if (Op0 == Op1)
3892     return ReplaceInstUsesWith(I, Op0);
3893
3894   // See if we can simplify any instructions used by the instruction whose sole 
3895   // purpose is to compute bits we don't care about.
3896   if (!isa<VectorType>(I.getType())) {
3897     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3898     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3899     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3900                              KnownZero, KnownOne))
3901       return &I;
3902   } else if (isa<ConstantAggregateZero>(Op1)) {
3903     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3904   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3905     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3906       return ReplaceInstUsesWith(I, I.getOperand(1));
3907   }
3908     
3909
3910   
3911   // or X, -1 == -1
3912   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3913     ConstantInt *C1 = 0; Value *X = 0;
3914     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3915     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3916       Instruction *Or = BinaryOperator::createOr(X, RHS);
3917       InsertNewInstBefore(Or, I);
3918       Or->takeName(Op0);
3919       return BinaryOperator::createAnd(Or, 
3920                ConstantInt::get(RHS->getValue() | C1->getValue()));
3921     }
3922
3923     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3924     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3925       Instruction *Or = BinaryOperator::createOr(X, RHS);
3926       InsertNewInstBefore(Or, I);
3927       Or->takeName(Op0);
3928       return BinaryOperator::createXor(Or,
3929                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3930     }
3931
3932     // Try to fold constant and into select arguments.
3933     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3934       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3935         return R;
3936     if (isa<PHINode>(Op0))
3937       if (Instruction *NV = FoldOpIntoPhi(I))
3938         return NV;
3939   }
3940
3941   Value *A = 0, *B = 0;
3942   ConstantInt *C1 = 0, *C2 = 0;
3943
3944   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3945     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3946       return ReplaceInstUsesWith(I, Op1);
3947   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3948     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3949       return ReplaceInstUsesWith(I, Op0);
3950
3951   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3952   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3953   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3954       match(Op1, m_Or(m_Value(), m_Value())) ||
3955       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3956        match(Op1, m_Shift(m_Value(), m_Value())))) {
3957     if (Instruction *BSwap = MatchBSwap(I))
3958       return BSwap;
3959   }
3960   
3961   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3962   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3963       MaskedValueIsZero(Op1, C1->getValue())) {
3964     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3965     InsertNewInstBefore(NOr, I);
3966     NOr->takeName(Op0);
3967     return BinaryOperator::createXor(NOr, C1);
3968   }
3969
3970   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3971   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3972       MaskedValueIsZero(Op0, C1->getValue())) {
3973     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3974     InsertNewInstBefore(NOr, I);
3975     NOr->takeName(Op0);
3976     return BinaryOperator::createXor(NOr, C1);
3977   }
3978
3979   // (A & C)|(B & D)
3980   Value *C = 0, *D = 0;
3981   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3982       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3983     Value *V1 = 0, *V2 = 0, *V3 = 0;
3984     C1 = dyn_cast<ConstantInt>(C);
3985     C2 = dyn_cast<ConstantInt>(D);
3986     if (C1 && C2) {  // (A & C1)|(B & C2)
3987       // If we have: ((V + N) & C1) | (V & C2)
3988       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3989       // replace with V+N.
3990       if (C1->getValue() == ~C2->getValue()) {
3991         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3992             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3993           // Add commutes, try both ways.
3994           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3995             return ReplaceInstUsesWith(I, A);
3996           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3997             return ReplaceInstUsesWith(I, A);
3998         }
3999         // Or commutes, try both ways.
4000         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4001             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4002           // Add commutes, try both ways.
4003           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4004             return ReplaceInstUsesWith(I, B);
4005           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4006             return ReplaceInstUsesWith(I, B);
4007         }
4008       }
4009       V1 = 0; V2 = 0; V3 = 0;
4010     }
4011     
4012     // Check to see if we have any common things being and'ed.  If so, find the
4013     // terms for V1 & (V2|V3).
4014     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4015       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4016         V1 = A, V2 = C, V3 = D;
4017       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4018         V1 = A, V2 = B, V3 = C;
4019       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4020         V1 = C, V2 = A, V3 = D;
4021       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4022         V1 = C, V2 = A, V3 = B;
4023       
4024       if (V1) {
4025         Value *Or =
4026           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4027         return BinaryOperator::createAnd(V1, Or);
4028       }
4029     }
4030   }
4031   
4032   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4033   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4034     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4035       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4036           SI0->getOperand(1) == SI1->getOperand(1) &&
4037           (SI0->hasOneUse() || SI1->hasOneUse())) {
4038         Instruction *NewOp =
4039         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4040                                                      SI1->getOperand(0),
4041                                                      SI0->getName()), I);
4042         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4043                                       SI1->getOperand(1));
4044       }
4045   }
4046
4047   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4048     if (A == Op1)   // ~A | A == -1
4049       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4050   } else {
4051     A = 0;
4052   }
4053   // Note, A is still live here!
4054   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4055     if (Op0 == B)
4056       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4057
4058     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4059     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4060       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4061                                               I.getName()+".demorgan"), I);
4062       return BinaryOperator::createNot(And);
4063     }
4064   }
4065
4066   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4067   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4068     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4069       return R;
4070
4071     Value *LHSVal, *RHSVal;
4072     ConstantInt *LHSCst, *RHSCst;
4073     ICmpInst::Predicate LHSCC, RHSCC;
4074     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4075       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4076         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4077             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4078             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4079             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4080             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4081             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4082             // We can't fold (ugt x, C) | (sgt x, C2).
4083             PredicatesFoldable(LHSCC, RHSCC)) {
4084           // Ensure that the larger constant is on the RHS.
4085           ICmpInst *LHS = cast<ICmpInst>(Op0);
4086           bool NeedsSwap;
4087           if (ICmpInst::isSignedPredicate(LHSCC))
4088             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4089           else
4090             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4091             
4092           if (NeedsSwap) {
4093             std::swap(LHS, RHS);
4094             std::swap(LHSCst, RHSCst);
4095             std::swap(LHSCC, RHSCC);
4096           }
4097
4098           // At this point, we know we have have two icmp instructions
4099           // comparing a value against two constants and or'ing the result
4100           // together.  Because of the above check, we know that we only have
4101           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4102           // FoldICmpLogical check above), that the two constants are not
4103           // equal.
4104           assert(LHSCst != RHSCst && "Compares not folded above?");
4105
4106           switch (LHSCC) {
4107           default: assert(0 && "Unknown integer condition code!");
4108           case ICmpInst::ICMP_EQ:
4109             switch (RHSCC) {
4110             default: assert(0 && "Unknown integer condition code!");
4111             case ICmpInst::ICMP_EQ:
4112               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4113                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4114                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4115                                                       LHSVal->getName()+".off");
4116                 InsertNewInstBefore(Add, I);
4117                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4118                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4119               }
4120               break;                         // (X == 13 | X == 15) -> no change
4121             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4122             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4123               break;
4124             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4125             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4126             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4127               return ReplaceInstUsesWith(I, RHS);
4128             }
4129             break;
4130           case ICmpInst::ICMP_NE:
4131             switch (RHSCC) {
4132             default: assert(0 && "Unknown integer condition code!");
4133             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4134             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4135             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4136               return ReplaceInstUsesWith(I, LHS);
4137             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4138             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4139             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4140               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4141             }
4142             break;
4143           case ICmpInst::ICMP_ULT:
4144             switch (RHSCC) {
4145             default: assert(0 && "Unknown integer condition code!");
4146             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4147               break;
4148             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4149               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4150               // this can cause overflow.
4151               if (RHSCst->isMaxValue(false))
4152                 return ReplaceInstUsesWith(I, LHS);
4153               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4154                                      false, I);
4155             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4156               break;
4157             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4158             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4159               return ReplaceInstUsesWith(I, RHS);
4160             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4161               break;
4162             }
4163             break;
4164           case ICmpInst::ICMP_SLT:
4165             switch (RHSCC) {
4166             default: assert(0 && "Unknown integer condition code!");
4167             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4168               break;
4169             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4170               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4171               // this can cause overflow.
4172               if (RHSCst->isMaxValue(true))
4173                 return ReplaceInstUsesWith(I, LHS);
4174               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4175                                      false, I);
4176             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4177               break;
4178             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4179             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4180               return ReplaceInstUsesWith(I, RHS);
4181             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4182               break;
4183             }
4184             break;
4185           case ICmpInst::ICMP_UGT:
4186             switch (RHSCC) {
4187             default: assert(0 && "Unknown integer condition code!");
4188             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4189             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4190               return ReplaceInstUsesWith(I, LHS);
4191             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4192               break;
4193             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4194             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4195               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4196             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4197               break;
4198             }
4199             break;
4200           case ICmpInst::ICMP_SGT:
4201             switch (RHSCC) {
4202             default: assert(0 && "Unknown integer condition code!");
4203             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4204             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4205               return ReplaceInstUsesWith(I, LHS);
4206             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4207               break;
4208             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4209             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4210               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4211             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4212               break;
4213             }
4214             break;
4215           }
4216         }
4217   }
4218     
4219   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4220   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4221     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4222       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4223         const Type *SrcTy = Op0C->getOperand(0)->getType();
4224         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4225             // Only do this if the casts both really cause code to be generated.
4226             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4227                               I.getType(), TD) &&
4228             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4229                               I.getType(), TD)) {
4230           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4231                                                         Op1C->getOperand(0),
4232                                                         I.getName());
4233           InsertNewInstBefore(NewOp, I);
4234           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4235         }
4236       }
4237   }
4238   
4239     
4240   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4241   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4242     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4243       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4244           RHS->getPredicate() == FCmpInst::FCMP_UNO)
4245         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4246           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4247             // If either of the constants are nans, then the whole thing returns
4248             // true.
4249             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4250               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4251             
4252             // Otherwise, no need to compare the two constants, compare the
4253             // rest.
4254             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4255                                 RHS->getOperand(0));
4256           }
4257     }
4258   }
4259
4260   return Changed ? &I : 0;
4261 }
4262
4263 // XorSelf - Implements: X ^ X --> 0
4264 struct XorSelf {
4265   Value *RHS;
4266   XorSelf(Value *rhs) : RHS(rhs) {}
4267   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4268   Instruction *apply(BinaryOperator &Xor) const {
4269     return &Xor;
4270   }
4271 };
4272
4273
4274 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4275   bool Changed = SimplifyCommutative(I);
4276   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4277
4278   if (isa<UndefValue>(Op1))
4279     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4280
4281   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4282   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4283     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4284     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4285   }
4286   
4287   // See if we can simplify any instructions used by the instruction whose sole 
4288   // purpose is to compute bits we don't care about.
4289   if (!isa<VectorType>(I.getType())) {
4290     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4291     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4292     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4293                              KnownZero, KnownOne))
4294       return &I;
4295   } else if (isa<ConstantAggregateZero>(Op1)) {
4296     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4297   }
4298
4299   // Is this a ~ operation?
4300   if (Value *NotOp = dyn_castNotVal(&I)) {
4301     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4302     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4303     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4304       if (Op0I->getOpcode() == Instruction::And || 
4305           Op0I->getOpcode() == Instruction::Or) {
4306         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4307         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4308           Instruction *NotY =
4309             BinaryOperator::createNot(Op0I->getOperand(1),
4310                                       Op0I->getOperand(1)->getName()+".not");
4311           InsertNewInstBefore(NotY, I);
4312           if (Op0I->getOpcode() == Instruction::And)
4313             return BinaryOperator::createOr(Op0NotVal, NotY);
4314           else
4315             return BinaryOperator::createAnd(Op0NotVal, NotY);
4316         }
4317       }
4318     }
4319   }
4320   
4321   
4322   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4323     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4324     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4325       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4326         return new ICmpInst(ICI->getInversePredicate(),
4327                             ICI->getOperand(0), ICI->getOperand(1));
4328
4329       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4330         return new FCmpInst(FCI->getInversePredicate(),
4331                             FCI->getOperand(0), FCI->getOperand(1));
4332     }
4333
4334     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4335       // ~(c-X) == X-c-1 == X+(-c-1)
4336       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4337         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4338           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4339           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4340                                               ConstantInt::get(I.getType(), 1));
4341           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4342         }
4343           
4344       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4345         if (Op0I->getOpcode() == Instruction::Add) {
4346           // ~(X-c) --> (-c-1)-X
4347           if (RHS->isAllOnesValue()) {
4348             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4349             return BinaryOperator::createSub(
4350                            ConstantExpr::getSub(NegOp0CI,
4351                                              ConstantInt::get(I.getType(), 1)),
4352                                           Op0I->getOperand(0));
4353           } else if (RHS->getValue().isSignBit()) {
4354             // (X + C) ^ signbit -> (X + C + signbit)
4355             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4356             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4357
4358           }
4359         } else if (Op0I->getOpcode() == Instruction::Or) {
4360           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4361           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4362             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4363             // Anything in both C1 and C2 is known to be zero, remove it from
4364             // NewRHS.
4365             Constant *CommonBits = And(Op0CI, RHS);
4366             NewRHS = ConstantExpr::getAnd(NewRHS, 
4367                                           ConstantExpr::getNot(CommonBits));
4368             AddToWorkList(Op0I);
4369             I.setOperand(0, Op0I->getOperand(0));
4370             I.setOperand(1, NewRHS);
4371             return &I;
4372           }
4373         }
4374     }
4375
4376     // Try to fold constant and into select arguments.
4377     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4378       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4379         return R;
4380     if (isa<PHINode>(Op0))
4381       if (Instruction *NV = FoldOpIntoPhi(I))
4382         return NV;
4383   }
4384
4385   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4386     if (X == Op1)
4387       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4388
4389   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4390     if (X == Op0)
4391       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4392
4393   
4394   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4395   if (Op1I) {
4396     Value *A, *B;
4397     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4398       if (A == Op0) {              // B^(B|A) == (A|B)^B
4399         Op1I->swapOperands();
4400         I.swapOperands();
4401         std::swap(Op0, Op1);
4402       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4403         I.swapOperands();     // Simplified below.
4404         std::swap(Op0, Op1);
4405       }
4406     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4407       if (Op0 == A)                                          // A^(A^B) == B
4408         return ReplaceInstUsesWith(I, B);
4409       else if (Op0 == B)                                     // A^(B^A) == B
4410         return ReplaceInstUsesWith(I, A);
4411     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4412       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4413         Op1I->swapOperands();
4414         std::swap(A, B);
4415       }
4416       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4417         I.swapOperands();     // Simplified below.
4418         std::swap(Op0, Op1);
4419       }
4420     }
4421   }
4422   
4423   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4424   if (Op0I) {
4425     Value *A, *B;
4426     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4427       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4428         std::swap(A, B);
4429       if (B == Op1) {                                // (A|B)^B == A & ~B
4430         Instruction *NotB =
4431           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4432         return BinaryOperator::createAnd(A, NotB);
4433       }
4434     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4435       if (Op1 == A)                                          // (A^B)^A == B
4436         return ReplaceInstUsesWith(I, B);
4437       else if (Op1 == B)                                     // (B^A)^A == B
4438         return ReplaceInstUsesWith(I, A);
4439     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4440       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4441         std::swap(A, B);
4442       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4443           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4444         Instruction *N =
4445           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4446         return BinaryOperator::createAnd(N, Op1);
4447       }
4448     }
4449   }
4450   
4451   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4452   if (Op0I && Op1I && Op0I->isShift() && 
4453       Op0I->getOpcode() == Op1I->getOpcode() && 
4454       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4455       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4456     Instruction *NewOp =
4457       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4458                                                     Op1I->getOperand(0),
4459                                                     Op0I->getName()), I);
4460     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4461                                   Op1I->getOperand(1));
4462   }
4463     
4464   if (Op0I && Op1I) {
4465     Value *A, *B, *C, *D;
4466     // (A & B)^(A | B) -> A ^ B
4467     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4468         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4469       if ((A == C && B == D) || (A == D && B == C)) 
4470         return BinaryOperator::createXor(A, B);
4471     }
4472     // (A | B)^(A & B) -> A ^ B
4473     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4474         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4475       if ((A == C && B == D) || (A == D && B == C)) 
4476         return BinaryOperator::createXor(A, B);
4477     }
4478     
4479     // (A & B)^(C & D)
4480     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4481         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4482         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4483       // (X & Y)^(X & Y) -> (Y^Z) & X
4484       Value *X = 0, *Y = 0, *Z = 0;
4485       if (A == C)
4486         X = A, Y = B, Z = D;
4487       else if (A == D)
4488         X = A, Y = B, Z = C;
4489       else if (B == C)
4490         X = B, Y = A, Z = D;
4491       else if (B == D)
4492         X = B, Y = A, Z = C;
4493       
4494       if (X) {
4495         Instruction *NewOp =
4496         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4497         return BinaryOperator::createAnd(NewOp, X);
4498       }
4499     }
4500   }
4501     
4502   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4503   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4504     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4505       return R;
4506
4507   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4508   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4509     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4510       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4511         const Type *SrcTy = Op0C->getOperand(0)->getType();
4512         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4513             // Only do this if the casts both really cause code to be generated.
4514             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4515                               I.getType(), TD) &&
4516             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4517                               I.getType(), TD)) {
4518           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4519                                                          Op1C->getOperand(0),
4520                                                          I.getName());
4521           InsertNewInstBefore(NewOp, I);
4522           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4523         }
4524       }
4525   }
4526   return Changed ? &I : 0;
4527 }
4528
4529 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4530 /// overflowed for this type.
4531 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4532                             ConstantInt *In2, bool IsSigned = false) {
4533   Result = cast<ConstantInt>(Add(In1, In2));
4534
4535   if (IsSigned)
4536     if (In2->getValue().isNegative())
4537       return Result->getValue().sgt(In1->getValue());
4538     else
4539       return Result->getValue().slt(In1->getValue());
4540   else
4541     return Result->getValue().ult(In1->getValue());
4542 }
4543
4544 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4545 /// code necessary to compute the offset from the base pointer (without adding
4546 /// in the base pointer).  Return the result as a signed integer of intptr size.
4547 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4548   TargetData &TD = IC.getTargetData();
4549   gep_type_iterator GTI = gep_type_begin(GEP);
4550   const Type *IntPtrTy = TD.getIntPtrType();
4551   Value *Result = Constant::getNullValue(IntPtrTy);
4552
4553   // Build a mask for high order bits.
4554   unsigned IntPtrWidth = TD.getPointerSize()*8;
4555   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4556
4557   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4558     Value *Op = GEP->getOperand(i);
4559     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4560     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4561       if (OpC->isZero()) continue;
4562       
4563       // Handle a struct index, which adds its field offset to the pointer.
4564       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4565         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4566         
4567         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4568           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4569         else
4570           Result = IC.InsertNewInstBefore(
4571                    BinaryOperator::createAdd(Result,
4572                                              ConstantInt::get(IntPtrTy, Size),
4573                                              GEP->getName()+".offs"), I);
4574         continue;
4575       }
4576       
4577       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4578       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4579       Scale = ConstantExpr::getMul(OC, Scale);
4580       if (Constant *RC = dyn_cast<Constant>(Result))
4581         Result = ConstantExpr::getAdd(RC, Scale);
4582       else {
4583         // Emit an add instruction.
4584         Result = IC.InsertNewInstBefore(
4585            BinaryOperator::createAdd(Result, Scale,
4586                                      GEP->getName()+".offs"), I);
4587       }
4588       continue;
4589     }
4590     // Convert to correct type.
4591     if (Op->getType() != IntPtrTy) {
4592       if (Constant *OpC = dyn_cast<Constant>(Op))
4593         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4594       else
4595         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4596                                                  Op->getName()+".c"), I);
4597     }
4598     if (Size != 1) {
4599       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4600       if (Constant *OpC = dyn_cast<Constant>(Op))
4601         Op = ConstantExpr::getMul(OpC, Scale);
4602       else    // We'll let instcombine(mul) convert this to a shl if possible.
4603         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4604                                                   GEP->getName()+".idx"), I);
4605     }
4606
4607     // Emit an add instruction.
4608     if (isa<Constant>(Op) && isa<Constant>(Result))
4609       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4610                                     cast<Constant>(Result));
4611     else
4612       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4613                                                   GEP->getName()+".offs"), I);
4614   }
4615   return Result;
4616 }
4617
4618 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4619 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4620 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4621                                        ICmpInst::Predicate Cond,
4622                                        Instruction &I) {
4623   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4624
4625   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4626     if (isa<PointerType>(CI->getOperand(0)->getType()))
4627       RHS = CI->getOperand(0);
4628
4629   Value *PtrBase = GEPLHS->getOperand(0);
4630   if (PtrBase == RHS) {
4631     // As an optimization, we don't actually have to compute the actual value of
4632     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4633     // each index is zero or not.
4634     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4635       Instruction *InVal = 0;
4636       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4637       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4638         bool EmitIt = true;
4639         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4640           if (isa<UndefValue>(C))  // undef index -> undef.
4641             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4642           if (C->isNullValue())
4643             EmitIt = false;
4644           else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
4645             EmitIt = false;  // This is indexing into a zero sized array?
4646           } else if (isa<ConstantInt>(C))
4647             return ReplaceInstUsesWith(I, // No comparison is needed here.
4648                                  ConstantInt::get(Type::Int1Ty, 
4649                                                   Cond == ICmpInst::ICMP_NE));
4650         }
4651
4652         if (EmitIt) {
4653           Instruction *Comp =
4654             new ICmpInst(Cond, GEPLHS->getOperand(i),
4655                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4656           if (InVal == 0)
4657             InVal = Comp;
4658           else {
4659             InVal = InsertNewInstBefore(InVal, I);
4660             InsertNewInstBefore(Comp, I);
4661             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4662               InVal = BinaryOperator::createOr(InVal, Comp);
4663             else                              // True if all are equal
4664               InVal = BinaryOperator::createAnd(InVal, Comp);
4665           }
4666         }
4667       }
4668
4669       if (InVal)
4670         return InVal;
4671       else
4672         // No comparison is needed here, all indexes = 0
4673         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4674                                                 Cond == ICmpInst::ICMP_EQ));
4675     }
4676
4677     // Only lower this if the icmp is the only user of the GEP or if we expect
4678     // the result to fold to a constant!
4679     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4680       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4681       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4682       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4683                           Constant::getNullValue(Offset->getType()));
4684     }
4685   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4686     // If the base pointers are different, but the indices are the same, just
4687     // compare the base pointer.
4688     if (PtrBase != GEPRHS->getOperand(0)) {
4689       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4690       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4691                         GEPRHS->getOperand(0)->getType();
4692       if (IndicesTheSame)
4693         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4694           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4695             IndicesTheSame = false;
4696             break;
4697           }
4698
4699       // If all indices are the same, just compare the base pointers.
4700       if (IndicesTheSame)
4701         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4702                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4703
4704       // Otherwise, the base pointers are different and the indices are
4705       // different, bail out.
4706       return 0;
4707     }
4708
4709     // If one of the GEPs has all zero indices, recurse.
4710     bool AllZeros = true;
4711     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4712       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4713           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4714         AllZeros = false;
4715         break;
4716       }
4717     if (AllZeros)
4718       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4719                           ICmpInst::getSwappedPredicate(Cond), I);
4720
4721     // If the other GEP has all zero indices, recurse.
4722     AllZeros = true;
4723     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4724       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4725           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4726         AllZeros = false;
4727         break;
4728       }
4729     if (AllZeros)
4730       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4731
4732     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4733       // If the GEPs only differ by one index, compare it.
4734       unsigned NumDifferences = 0;  // Keep track of # differences.
4735       unsigned DiffOperand = 0;     // The operand that differs.
4736       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4737         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4738           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4739                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4740             // Irreconcilable differences.
4741             NumDifferences = 2;
4742             break;
4743           } else {
4744             if (NumDifferences++) break;
4745             DiffOperand = i;
4746           }
4747         }
4748
4749       if (NumDifferences == 0)   // SAME GEP?
4750         return ReplaceInstUsesWith(I, // No comparison is needed here.
4751                                    ConstantInt::get(Type::Int1Ty,
4752                                                     isTrueWhenEqual(Cond)));
4753
4754       else if (NumDifferences == 1) {
4755         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4756         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4757         // Make sure we do a signed comparison here.
4758         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4759       }
4760     }
4761
4762     // Only lower this if the icmp is the only user of the GEP or if we expect
4763     // the result to fold to a constant!
4764     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4765         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4766       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4767       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4768       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4769       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4770     }
4771   }
4772   return 0;
4773 }
4774
4775 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4776   bool Changed = SimplifyCompare(I);
4777   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4778
4779   // Fold trivial predicates.
4780   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4781     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4782   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4783     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4784   
4785   // Simplify 'fcmp pred X, X'
4786   if (Op0 == Op1) {
4787     switch (I.getPredicate()) {
4788     default: assert(0 && "Unknown predicate!");
4789     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4790     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4791     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4792       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4793     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4794     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4795     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4796       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4797       
4798     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4799     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4800     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4801     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4802       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4803       I.setPredicate(FCmpInst::FCMP_UNO);
4804       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4805       return &I;
4806       
4807     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4808     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4809     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4810     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4811       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4812       I.setPredicate(FCmpInst::FCMP_ORD);
4813       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4814       return &I;
4815     }
4816   }
4817     
4818   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4819     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4820
4821   // Handle fcmp with constant RHS
4822   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4823     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4824       switch (LHSI->getOpcode()) {
4825       case Instruction::PHI:
4826         if (Instruction *NV = FoldOpIntoPhi(I))
4827           return NV;
4828         break;
4829       case Instruction::Select:
4830         // If either operand of the select is a constant, we can fold the
4831         // comparison into the select arms, which will cause one to be
4832         // constant folded and the select turned into a bitwise or.
4833         Value *Op1 = 0, *Op2 = 0;
4834         if (LHSI->hasOneUse()) {
4835           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4836             // Fold the known value into the constant operand.
4837             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4838             // Insert a new FCmp of the other select operand.
4839             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4840                                                       LHSI->getOperand(2), RHSC,
4841                                                       I.getName()), I);
4842           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4843             // Fold the known value into the constant operand.
4844             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4845             // Insert a new FCmp of the other select operand.
4846             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4847                                                       LHSI->getOperand(1), RHSC,
4848                                                       I.getName()), I);
4849           }
4850         }
4851
4852         if (Op1)
4853           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4854         break;
4855       }
4856   }
4857
4858   return Changed ? &I : 0;
4859 }
4860
4861 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4862   bool Changed = SimplifyCompare(I);
4863   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4864   const Type *Ty = Op0->getType();
4865
4866   // icmp X, X
4867   if (Op0 == Op1)
4868     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4869                                                    isTrueWhenEqual(I)));
4870
4871   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4872     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4873   
4874   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4875   // addresses never equal each other!  We already know that Op0 != Op1.
4876   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4877        isa<ConstantPointerNull>(Op0)) &&
4878       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4879        isa<ConstantPointerNull>(Op1)))
4880     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4881                                                    !isTrueWhenEqual(I)));
4882
4883   // icmp's with boolean values can always be turned into bitwise operations
4884   if (Ty == Type::Int1Ty) {
4885     switch (I.getPredicate()) {
4886     default: assert(0 && "Invalid icmp instruction!");
4887     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4888       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4889       InsertNewInstBefore(Xor, I);
4890       return BinaryOperator::createNot(Xor);
4891     }
4892     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4893       return BinaryOperator::createXor(Op0, Op1);
4894
4895     case ICmpInst::ICMP_UGT:
4896     case ICmpInst::ICMP_SGT:
4897       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4898       // FALL THROUGH
4899     case ICmpInst::ICMP_ULT:
4900     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4901       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4902       InsertNewInstBefore(Not, I);
4903       return BinaryOperator::createAnd(Not, Op1);
4904     }
4905     case ICmpInst::ICMP_UGE:
4906     case ICmpInst::ICMP_SGE:
4907       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4908       // FALL THROUGH
4909     case ICmpInst::ICMP_ULE:
4910     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4911       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4912       InsertNewInstBefore(Not, I);
4913       return BinaryOperator::createOr(Not, Op1);
4914     }
4915     }
4916   }
4917
4918   // See if we are doing a comparison between a constant and an instruction that
4919   // can be folded into the comparison.
4920   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4921       Value *A, *B;
4922     
4923     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4924     if (I.isEquality() && CI->isNullValue() &&
4925         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4926       // (icmp cond A B) if cond is equality
4927       return new ICmpInst(I.getPredicate(), A, B);
4928     }
4929     
4930     switch (I.getPredicate()) {
4931     default: break;
4932     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4933       if (CI->isMinValue(false))
4934         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4935       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4936         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4937       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4938         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4939       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
4940       if (CI->isMinValue(true))
4941         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4942                             ConstantInt::getAllOnesValue(Op0->getType()));
4943           
4944       break;
4945
4946     case ICmpInst::ICMP_SLT:
4947       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4948         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4949       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4950         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4951       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4952         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4953       break;
4954
4955     case ICmpInst::ICMP_UGT:
4956       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4957         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4958       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4959         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4960       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4961         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4962         
4963       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
4964       if (CI->isMaxValue(true))
4965         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4966                             ConstantInt::getNullValue(Op0->getType()));
4967       break;
4968
4969     case ICmpInst::ICMP_SGT:
4970       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4971         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4972       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4973         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4974       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4975         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4976       break;
4977
4978     case ICmpInst::ICMP_ULE:
4979       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4980         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4981       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4982         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4983       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4984         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4985       break;
4986
4987     case ICmpInst::ICMP_SLE:
4988       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4989         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4990       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4991         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4992       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4993         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4994       break;
4995
4996     case ICmpInst::ICMP_UGE:
4997       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4998         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4999       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5000         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5001       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5002         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5003       break;
5004
5005     case ICmpInst::ICMP_SGE:
5006       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5007         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5008       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5009         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5010       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5011         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5012       break;
5013     }
5014
5015     // If we still have a icmp le or icmp ge instruction, turn it into the
5016     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5017     // already been handled above, this requires little checking.
5018     //
5019     switch (I.getPredicate()) {
5020     default: break;
5021     case ICmpInst::ICMP_ULE: 
5022       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5023     case ICmpInst::ICMP_SLE:
5024       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5025     case ICmpInst::ICMP_UGE:
5026       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5027     case ICmpInst::ICMP_SGE:
5028       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5029     }
5030     
5031     // See if we can fold the comparison based on bits known to be zero or one
5032     // in the input.  If this comparison is a normal comparison, it demands all
5033     // bits, if it is a sign bit comparison, it only demands the sign bit.
5034     
5035     bool UnusedBit;
5036     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5037     
5038     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5039     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5040     if (SimplifyDemandedBits(Op0, 
5041                              isSignBit ? APInt::getSignBit(BitWidth)
5042                                        : APInt::getAllOnesValue(BitWidth),
5043                              KnownZero, KnownOne, 0))
5044       return &I;
5045         
5046     // Given the known and unknown bits, compute a range that the LHS could be
5047     // in.
5048     if ((KnownOne | KnownZero) != 0) {
5049       // Compute the Min, Max and RHS values based on the known bits. For the
5050       // EQ and NE we use unsigned values.
5051       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5052       const APInt& RHSVal = CI->getValue();
5053       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5054         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5055                                                Max);
5056       } else {
5057         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5058                                                  Max);
5059       }
5060       switch (I.getPredicate()) {  // LE/GE have been folded already.
5061       default: assert(0 && "Unknown icmp opcode!");
5062       case ICmpInst::ICMP_EQ:
5063         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5064           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5065         break;
5066       case ICmpInst::ICMP_NE:
5067         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5068           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5069         break;
5070       case ICmpInst::ICMP_ULT:
5071         if (Max.ult(RHSVal))
5072           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5073         if (Min.uge(RHSVal))
5074           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5075         break;
5076       case ICmpInst::ICMP_UGT:
5077         if (Min.ugt(RHSVal))
5078           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5079         if (Max.ule(RHSVal))
5080           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5081         break;
5082       case ICmpInst::ICMP_SLT:
5083         if (Max.slt(RHSVal))
5084           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5085         if (Min.sgt(RHSVal))
5086           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5087         break;
5088       case ICmpInst::ICMP_SGT: 
5089         if (Min.sgt(RHSVal))
5090           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5091         if (Max.sle(RHSVal))
5092           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5093         break;
5094       }
5095     }
5096           
5097     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5098     // instruction, see if that instruction also has constants so that the 
5099     // instruction can be folded into the icmp 
5100     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5101       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5102         return Res;
5103   }
5104
5105   // Handle icmp with constant (but not simple integer constant) RHS
5106   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5107     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5108       switch (LHSI->getOpcode()) {
5109       case Instruction::GetElementPtr:
5110         if (RHSC->isNullValue()) {
5111           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5112           bool isAllZeros = true;
5113           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5114             if (!isa<Constant>(LHSI->getOperand(i)) ||
5115                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5116               isAllZeros = false;
5117               break;
5118             }
5119           if (isAllZeros)
5120             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5121                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5122         }
5123         break;
5124
5125       case Instruction::PHI:
5126         if (Instruction *NV = FoldOpIntoPhi(I))
5127           return NV;
5128         break;
5129       case Instruction::Select: {
5130         // If either operand of the select is a constant, we can fold the
5131         // comparison into the select arms, which will cause one to be
5132         // constant folded and the select turned into a bitwise or.
5133         Value *Op1 = 0, *Op2 = 0;
5134         if (LHSI->hasOneUse()) {
5135           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5136             // Fold the known value into the constant operand.
5137             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5138             // Insert a new ICmp of the other select operand.
5139             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5140                                                    LHSI->getOperand(2), RHSC,
5141                                                    I.getName()), I);
5142           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5143             // Fold the known value into the constant operand.
5144             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5145             // Insert a new ICmp of the other select operand.
5146             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5147                                                    LHSI->getOperand(1), RHSC,
5148                                                    I.getName()), I);
5149           }
5150         }
5151
5152         if (Op1)
5153           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5154         break;
5155       }
5156       case Instruction::Malloc:
5157         // If we have (malloc != null), and if the malloc has a single use, we
5158         // can assume it is successful and remove the malloc.
5159         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5160           AddToWorkList(LHSI);
5161           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5162                                                          !isTrueWhenEqual(I)));
5163         }
5164         break;
5165       }
5166   }
5167
5168   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5169   if (User *GEP = dyn_castGetElementPtr(Op0))
5170     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5171       return NI;
5172   if (User *GEP = dyn_castGetElementPtr(Op1))
5173     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5174                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5175       return NI;
5176
5177   // Test to see if the operands of the icmp are casted versions of other
5178   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5179   // now.
5180   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5181     if (isa<PointerType>(Op0->getType()) && 
5182         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5183       // We keep moving the cast from the left operand over to the right
5184       // operand, where it can often be eliminated completely.
5185       Op0 = CI->getOperand(0);
5186
5187       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5188       // so eliminate it as well.
5189       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5190         Op1 = CI2->getOperand(0);
5191
5192       // If Op1 is a constant, we can fold the cast into the constant.
5193       if (Op0->getType() != Op1->getType())
5194         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5195           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5196         } else {
5197           // Otherwise, cast the RHS right before the icmp
5198           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5199         }
5200       return new ICmpInst(I.getPredicate(), Op0, Op1);
5201     }
5202   }
5203   
5204   if (isa<CastInst>(Op0)) {
5205     // Handle the special case of: icmp (cast bool to X), <cst>
5206     // This comes up when you have code like
5207     //   int X = A < B;
5208     //   if (X) ...
5209     // For generality, we handle any zero-extension of any operand comparison
5210     // with a constant or another cast from the same type.
5211     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5212       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5213         return R;
5214   }
5215   
5216   if (I.isEquality()) {
5217     Value *A, *B, *C, *D;
5218     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5219       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5220         Value *OtherVal = A == Op1 ? B : A;
5221         return new ICmpInst(I.getPredicate(), OtherVal,
5222                             Constant::getNullValue(A->getType()));
5223       }
5224
5225       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5226         // A^c1 == C^c2 --> A == C^(c1^c2)
5227         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5228           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5229             if (Op1->hasOneUse()) {
5230               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5231               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5232               return new ICmpInst(I.getPredicate(), A,
5233                                   InsertNewInstBefore(Xor, I));
5234             }
5235         
5236         // A^B == A^D -> B == D
5237         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5238         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5239         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5240         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5241       }
5242     }
5243     
5244     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5245         (A == Op0 || B == Op0)) {
5246       // A == (A^B)  ->  B == 0
5247       Value *OtherVal = A == Op0 ? B : A;
5248       return new ICmpInst(I.getPredicate(), OtherVal,
5249                           Constant::getNullValue(A->getType()));
5250     }
5251     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5252       // (A-B) == A  ->  B == 0
5253       return new ICmpInst(I.getPredicate(), B,
5254                           Constant::getNullValue(B->getType()));
5255     }
5256     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5257       // A == (A-B)  ->  B == 0
5258       return new ICmpInst(I.getPredicate(), B,
5259                           Constant::getNullValue(B->getType()));
5260     }
5261     
5262     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5263     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5264         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5265         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5266       Value *X = 0, *Y = 0, *Z = 0;
5267       
5268       if (A == C) {
5269         X = B; Y = D; Z = A;
5270       } else if (A == D) {
5271         X = B; Y = C; Z = A;
5272       } else if (B == C) {
5273         X = A; Y = D; Z = B;
5274       } else if (B == D) {
5275         X = A; Y = C; Z = B;
5276       }
5277       
5278       if (X) {   // Build (X^Y) & Z
5279         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5280         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5281         I.setOperand(0, Op1);
5282         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5283         return &I;
5284       }
5285     }
5286   }
5287   return Changed ? &I : 0;
5288 }
5289
5290
5291 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5292 /// and CmpRHS are both known to be integer constants.
5293 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5294                                           ConstantInt *DivRHS) {
5295   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5296   const APInt &CmpRHSV = CmpRHS->getValue();
5297   
5298   // FIXME: If the operand types don't match the type of the divide 
5299   // then don't attempt this transform. The code below doesn't have the
5300   // logic to deal with a signed divide and an unsigned compare (and
5301   // vice versa). This is because (x /s C1) <s C2  produces different 
5302   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5303   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5304   // work. :(  The if statement below tests that condition and bails 
5305   // if it finds it. 
5306   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5307   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5308     return 0;
5309   if (DivRHS->isZero())
5310     return 0; // The ProdOV computation fails on divide by zero.
5311
5312   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5313   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5314   // C2 (CI). By solving for X we can turn this into a range check 
5315   // instead of computing a divide. 
5316   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5317
5318   // Determine if the product overflows by seeing if the product is
5319   // not equal to the divide. Make sure we do the same kind of divide
5320   // as in the LHS instruction that we're folding. 
5321   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5322                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5323
5324   // Get the ICmp opcode
5325   ICmpInst::Predicate Pred = ICI.getPredicate();
5326
5327   // Figure out the interval that is being checked.  For example, a comparison
5328   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5329   // Compute this interval based on the constants involved and the signedness of
5330   // the compare/divide.  This computes a half-open interval, keeping track of
5331   // whether either value in the interval overflows.  After analysis each
5332   // overflow variable is set to 0 if it's corresponding bound variable is valid
5333   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5334   int LoOverflow = 0, HiOverflow = 0;
5335   ConstantInt *LoBound = 0, *HiBound = 0;
5336   
5337   
5338   if (!DivIsSigned) {  // udiv
5339     // e.g. X/5 op 3  --> [15, 20)
5340     LoBound = Prod;
5341     HiOverflow = LoOverflow = ProdOV;
5342     if (!HiOverflow)
5343       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5344   } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5345     if (CmpRHSV == 0) {       // (X / pos) op 0
5346       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5347       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5348       HiBound = DivRHS;
5349     } else if (CmpRHSV.isPositive()) {   // (X / pos) op pos
5350       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5351       HiOverflow = LoOverflow = ProdOV;
5352       if (!HiOverflow)
5353         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5354     } else {                       // (X / pos) op neg
5355       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5356       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5357       LoOverflow = AddWithOverflow(LoBound, Prod,
5358                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5359       HiBound = AddOne(Prod);
5360       HiOverflow = ProdOV ? -1 : 0;
5361     }
5362   } else {                         // Divisor is < 0.
5363     if (CmpRHSV == 0) {       // (X / neg) op 0
5364       // e.g. X/-5 op 0  --> [-4, 5)
5365       LoBound = AddOne(DivRHS);
5366       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5367       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5368         HiOverflow = 1;            // [INTMIN+1, overflow)
5369         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5370       }
5371     } else if (CmpRHSV.isPositive()) {   // (X / neg) op pos
5372       // e.g. X/-5 op 3  --> [-19, -14)
5373       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5374       if (!LoOverflow)
5375         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5376       HiBound = AddOne(Prod);
5377     } else {                       // (X / neg) op neg
5378       // e.g. X/-5 op -3  --> [15, 20)
5379       LoBound = Prod;
5380       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5381       HiBound = Subtract(Prod, DivRHS);
5382     }
5383     
5384     // Dividing by a negative swaps the condition.  LT <-> GT
5385     Pred = ICmpInst::getSwappedPredicate(Pred);
5386   }
5387
5388   Value *X = DivI->getOperand(0);
5389   switch (Pred) {
5390   default: assert(0 && "Unhandled icmp opcode!");
5391   case ICmpInst::ICMP_EQ:
5392     if (LoOverflow && HiOverflow)
5393       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5394     else if (HiOverflow)
5395       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5396                           ICmpInst::ICMP_UGE, X, LoBound);
5397     else if (LoOverflow)
5398       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5399                           ICmpInst::ICMP_ULT, X, HiBound);
5400     else
5401       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5402   case ICmpInst::ICMP_NE:
5403     if (LoOverflow && HiOverflow)
5404       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5405     else if (HiOverflow)
5406       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5407                           ICmpInst::ICMP_ULT, X, LoBound);
5408     else if (LoOverflow)
5409       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5410                           ICmpInst::ICMP_UGE, X, HiBound);
5411     else
5412       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5413   case ICmpInst::ICMP_ULT:
5414   case ICmpInst::ICMP_SLT:
5415     if (LoOverflow == +1)   // Low bound is greater than input range.
5416       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5417     if (LoOverflow == -1)   // Low bound is less than input range.
5418       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5419     return new ICmpInst(Pred, X, LoBound);
5420   case ICmpInst::ICMP_UGT:
5421   case ICmpInst::ICMP_SGT:
5422     if (HiOverflow == +1)       // High bound greater than input range.
5423       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5424     else if (HiOverflow == -1)  // High bound less than input range.
5425       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5426     if (Pred == ICmpInst::ICMP_UGT)
5427       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5428     else
5429       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5430   }
5431 }
5432
5433
5434 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5435 ///
5436 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5437                                                           Instruction *LHSI,
5438                                                           ConstantInt *RHS) {
5439   const APInt &RHSV = RHS->getValue();
5440   
5441   switch (LHSI->getOpcode()) {
5442   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5443     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5444       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5445       // fold the xor.
5446       if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5447           ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5448         Value *CompareVal = LHSI->getOperand(0);
5449         
5450         // If the sign bit of the XorCST is not set, there is no change to
5451         // the operation, just stop using the Xor.
5452         if (!XorCST->getValue().isNegative()) {
5453           ICI.setOperand(0, CompareVal);
5454           AddToWorkList(LHSI);
5455           return &ICI;
5456         }
5457         
5458         // Was the old condition true if the operand is positive?
5459         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5460         
5461         // If so, the new one isn't.
5462         isTrueIfPositive ^= true;
5463         
5464         if (isTrueIfPositive)
5465           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5466         else
5467           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5468       }
5469     }
5470     break;
5471   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5472     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5473         LHSI->getOperand(0)->hasOneUse()) {
5474       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5475       
5476       // If the LHS is an AND of a truncating cast, we can widen the
5477       // and/compare to be the input width without changing the value
5478       // produced, eliminating a cast.
5479       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5480         // We can do this transformation if either the AND constant does not
5481         // have its sign bit set or if it is an equality comparison. 
5482         // Extending a relational comparison when we're checking the sign
5483         // bit would not work.
5484         if (Cast->hasOneUse() &&
5485             (ICI.isEquality() || AndCST->getValue().isPositive() && 
5486              RHSV.isPositive())) {
5487           uint32_t BitWidth = 
5488             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5489           APInt NewCST = AndCST->getValue();
5490           NewCST.zext(BitWidth);
5491           APInt NewCI = RHSV;
5492           NewCI.zext(BitWidth);
5493           Instruction *NewAnd = 
5494             BinaryOperator::createAnd(Cast->getOperand(0),
5495                                       ConstantInt::get(NewCST),LHSI->getName());
5496           InsertNewInstBefore(NewAnd, ICI);
5497           return new ICmpInst(ICI.getPredicate(), NewAnd,
5498                               ConstantInt::get(NewCI));
5499         }
5500       }
5501       
5502       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5503       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5504       // happens a LOT in code produced by the C front-end, for bitfield
5505       // access.
5506       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5507       if (Shift && !Shift->isShift())
5508         Shift = 0;
5509       
5510       ConstantInt *ShAmt;
5511       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5512       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5513       const Type *AndTy = AndCST->getType();          // Type of the and.
5514       
5515       // We can fold this as long as we can't shift unknown bits
5516       // into the mask.  This can only happen with signed shift
5517       // rights, as they sign-extend.
5518       if (ShAmt) {
5519         bool CanFold = Shift->isLogicalShift();
5520         if (!CanFold) {
5521           // To test for the bad case of the signed shr, see if any
5522           // of the bits shifted in could be tested after the mask.
5523           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5524           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5525           
5526           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5527           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5528                AndCST->getValue()) == 0)
5529             CanFold = true;
5530         }
5531         
5532         if (CanFold) {
5533           Constant *NewCst;
5534           if (Shift->getOpcode() == Instruction::Shl)
5535             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5536           else
5537             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5538           
5539           // Check to see if we are shifting out any of the bits being
5540           // compared.
5541           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5542             // If we shifted bits out, the fold is not going to work out.
5543             // As a special case, check to see if this means that the
5544             // result is always true or false now.
5545             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5546               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5547             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5548               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5549           } else {
5550             ICI.setOperand(1, NewCst);
5551             Constant *NewAndCST;
5552             if (Shift->getOpcode() == Instruction::Shl)
5553               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5554             else
5555               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5556             LHSI->setOperand(1, NewAndCST);
5557             LHSI->setOperand(0, Shift->getOperand(0));
5558             AddToWorkList(Shift); // Shift is dead.
5559             AddUsesToWorkList(ICI);
5560             return &ICI;
5561           }
5562         }
5563       }
5564       
5565       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5566       // preferable because it allows the C<<Y expression to be hoisted out
5567       // of a loop if Y is invariant and X is not.
5568       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5569           ICI.isEquality() && !Shift->isArithmeticShift() &&
5570           isa<Instruction>(Shift->getOperand(0))) {
5571         // Compute C << Y.
5572         Value *NS;
5573         if (Shift->getOpcode() == Instruction::LShr) {
5574           NS = BinaryOperator::createShl(AndCST, 
5575                                          Shift->getOperand(1), "tmp");
5576         } else {
5577           // Insert a logical shift.
5578           NS = BinaryOperator::createLShr(AndCST,
5579                                           Shift->getOperand(1), "tmp");
5580         }
5581         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5582         
5583         // Compute X & (C << Y).
5584         Instruction *NewAnd = 
5585           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5586         InsertNewInstBefore(NewAnd, ICI);
5587         
5588         ICI.setOperand(0, NewAnd);
5589         return &ICI;
5590       }
5591     }
5592     break;
5593     
5594   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5595     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5596     if (!ShAmt) break;
5597     
5598     uint32_t TypeBits = RHSV.getBitWidth();
5599     
5600     // Check that the shift amount is in range.  If not, don't perform
5601     // undefined shifts.  When the shift is visited it will be
5602     // simplified.
5603     if (ShAmt->uge(TypeBits))
5604       break;
5605     
5606     if (ICI.isEquality()) {
5607       // If we are comparing against bits always shifted out, the
5608       // comparison cannot succeed.
5609       Constant *Comp =
5610         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5611       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5612         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5613         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5614         return ReplaceInstUsesWith(ICI, Cst);
5615       }
5616       
5617       if (LHSI->hasOneUse()) {
5618         // Otherwise strength reduce the shift into an and.
5619         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5620         Constant *Mask =
5621           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5622         
5623         Instruction *AndI =
5624           BinaryOperator::createAnd(LHSI->getOperand(0),
5625                                     Mask, LHSI->getName()+".mask");
5626         Value *And = InsertNewInstBefore(AndI, ICI);
5627         return new ICmpInst(ICI.getPredicate(), And,
5628                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5629       }
5630     }
5631     
5632     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5633     bool TrueIfSigned = false;
5634     if (LHSI->hasOneUse() &&
5635         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5636       // (X << 31) <s 0  --> (X&1) != 0
5637       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5638                                            (TypeBits-ShAmt->getZExtValue()-1));
5639       Instruction *AndI =
5640         BinaryOperator::createAnd(LHSI->getOperand(0),
5641                                   Mask, LHSI->getName()+".mask");
5642       Value *And = InsertNewInstBefore(AndI, ICI);
5643       
5644       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5645                           And, Constant::getNullValue(And->getType()));
5646     }
5647     break;
5648   }
5649     
5650   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5651   case Instruction::AShr: {
5652     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5653     if (!ShAmt) break;
5654
5655     if (ICI.isEquality()) {
5656       // Check that the shift amount is in range.  If not, don't perform
5657       // undefined shifts.  When the shift is visited it will be
5658       // simplified.
5659       uint32_t TypeBits = RHSV.getBitWidth();
5660       if (ShAmt->uge(TypeBits))
5661         break;
5662       uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5663       
5664       // If we are comparing against bits always shifted out, the
5665       // comparison cannot succeed.
5666       APInt Comp = RHSV << ShAmtVal;
5667       if (LHSI->getOpcode() == Instruction::LShr)
5668         Comp = Comp.lshr(ShAmtVal);
5669       else
5670         Comp = Comp.ashr(ShAmtVal);
5671       
5672       if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5673         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5674         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5675         return ReplaceInstUsesWith(ICI, Cst);
5676       }
5677       
5678       if (LHSI->hasOneUse() || RHSV == 0) {
5679         // Otherwise strength reduce the shift into an and.
5680         APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5681         Constant *Mask = ConstantInt::get(Val);
5682         
5683         Instruction *AndI =
5684           BinaryOperator::createAnd(LHSI->getOperand(0),
5685                                     Mask, LHSI->getName()+".mask");
5686         Value *And = InsertNewInstBefore(AndI, ICI);
5687         return new ICmpInst(ICI.getPredicate(), And,
5688                             ConstantExpr::getShl(RHS, ShAmt));
5689       }
5690     }
5691     break;
5692   }
5693     
5694   case Instruction::SDiv:
5695   case Instruction::UDiv:
5696     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5697     // Fold this div into the comparison, producing a range check. 
5698     // Determine, based on the divide type, what the range is being 
5699     // checked.  If there is an overflow on the low or high side, remember 
5700     // it, otherwise compute the range [low, hi) bounding the new value.
5701     // See: InsertRangeTest above for the kinds of replacements possible.
5702     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5703       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5704                                           DivRHS))
5705         return R;
5706     break;
5707   }
5708   
5709   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5710   if (ICI.isEquality()) {
5711     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5712     
5713     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5714     // the second operand is a constant, simplify a bit.
5715     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5716       switch (BO->getOpcode()) {
5717       case Instruction::SRem:
5718         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5719         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5720           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5721           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5722             Instruction *NewRem =
5723               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5724                                          BO->getName());
5725             InsertNewInstBefore(NewRem, ICI);
5726             return new ICmpInst(ICI.getPredicate(), NewRem, 
5727                                 Constant::getNullValue(BO->getType()));
5728           }
5729         }
5730         break;
5731       case Instruction::Add:
5732         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5733         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5734           if (BO->hasOneUse())
5735             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5736                                 Subtract(RHS, BOp1C));
5737         } else if (RHSV == 0) {
5738           // Replace ((add A, B) != 0) with (A != -B) if A or B is
5739           // efficiently invertible, or if the add has just this one use.
5740           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5741           
5742           if (Value *NegVal = dyn_castNegVal(BOp1))
5743             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5744           else if (Value *NegVal = dyn_castNegVal(BOp0))
5745             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5746           else if (BO->hasOneUse()) {
5747             Instruction *Neg = BinaryOperator::createNeg(BOp1);
5748             InsertNewInstBefore(Neg, ICI);
5749             Neg->takeName(BO);
5750             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5751           }
5752         }
5753         break;
5754       case Instruction::Xor:
5755         // For the xor case, we can xor two constants together, eliminating
5756         // the explicit xor.
5757         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5758           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
5759                               ConstantExpr::getXor(RHS, BOC));
5760         
5761         // FALLTHROUGH
5762       case Instruction::Sub:
5763         // Replace (([sub|xor] A, B) != 0) with (A != B)
5764         if (RHSV == 0)
5765           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5766                               BO->getOperand(1));
5767         break;
5768         
5769       case Instruction::Or:
5770         // If bits are being or'd in that are not present in the constant we
5771         // are comparing against, then the comparison could never succeed!
5772         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5773           Constant *NotCI = ConstantExpr::getNot(RHS);
5774           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5775             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
5776                                                              isICMP_NE));
5777         }
5778         break;
5779         
5780       case Instruction::And:
5781         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5782           // If bits are being compared against that are and'd out, then the
5783           // comparison can never succeed!
5784           if ((RHSV & ~BOC->getValue()) != 0)
5785             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5786                                                              isICMP_NE));
5787           
5788           // If we have ((X & C) == C), turn it into ((X & C) != 0).
5789           if (RHS == BOC && RHSV.isPowerOf2())
5790             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5791                                 ICmpInst::ICMP_NE, LHSI,
5792                                 Constant::getNullValue(RHS->getType()));
5793           
5794           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5795           if (isSignBit(BOC)) {
5796             Value *X = BO->getOperand(0);
5797             Constant *Zero = Constant::getNullValue(X->getType());
5798             ICmpInst::Predicate pred = isICMP_NE ? 
5799               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5800             return new ICmpInst(pred, X, Zero);
5801           }
5802           
5803           // ((X & ~7) == 0) --> X < 8
5804           if (RHSV == 0 && isHighOnes(BOC)) {
5805             Value *X = BO->getOperand(0);
5806             Constant *NegX = ConstantExpr::getNeg(BOC);
5807             ICmpInst::Predicate pred = isICMP_NE ? 
5808               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5809             return new ICmpInst(pred, X, NegX);
5810           }
5811         }
5812       default: break;
5813       }
5814     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5815       // Handle icmp {eq|ne} <intrinsic>, intcst.
5816       if (II->getIntrinsicID() == Intrinsic::bswap) {
5817         AddToWorkList(II);
5818         ICI.setOperand(0, II->getOperand(1));
5819         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5820         return &ICI;
5821       }
5822     }
5823   } else {  // Not a ICMP_EQ/ICMP_NE
5824             // If the LHS is a cast from an integral value of the same size, 
5825             // then since we know the RHS is a constant, try to simlify.
5826     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5827       Value *CastOp = Cast->getOperand(0);
5828       const Type *SrcTy = CastOp->getType();
5829       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5830       if (SrcTy->isInteger() && 
5831           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5832         // If this is an unsigned comparison, try to make the comparison use
5833         // smaller constant values.
5834         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5835           // X u< 128 => X s> -1
5836           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5837                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5838         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5839                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5840           // X u> 127 => X s< 0
5841           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5842                               Constant::getNullValue(SrcTy));
5843         }
5844       }
5845     }
5846   }
5847   return 0;
5848 }
5849
5850 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5851 /// We only handle extending casts so far.
5852 ///
5853 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5854   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5855   Value *LHSCIOp        = LHSCI->getOperand(0);
5856   const Type *SrcTy     = LHSCIOp->getType();
5857   const Type *DestTy    = LHSCI->getType();
5858   Value *RHSCIOp;
5859
5860   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
5861   // integer type is the same size as the pointer type.
5862   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5863       getTargetData().getPointerSizeInBits() == 
5864          cast<IntegerType>(DestTy)->getBitWidth()) {
5865     Value *RHSOp = 0;
5866     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5867       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5868     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5869       RHSOp = RHSC->getOperand(0);
5870       // If the pointer types don't match, insert a bitcast.
5871       if (LHSCIOp->getType() != RHSOp->getType())
5872         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
5873     }
5874
5875     if (RHSOp)
5876       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5877   }
5878   
5879   // The code below only handles extension cast instructions, so far.
5880   // Enforce this.
5881   if (LHSCI->getOpcode() != Instruction::ZExt &&
5882       LHSCI->getOpcode() != Instruction::SExt)
5883     return 0;
5884
5885   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5886   bool isSignedCmp = ICI.isSignedPredicate();
5887
5888   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5889     // Not an extension from the same type?
5890     RHSCIOp = CI->getOperand(0);
5891     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5892       return 0;
5893     
5894     // If the signedness of the two casts doesn't agree (i.e. one is a sext
5895     // and the other is a zext), then we can't handle this.
5896     if (CI->getOpcode() != LHSCI->getOpcode())
5897       return 0;
5898
5899     // Deal with equality cases early.
5900     if (ICI.isEquality())
5901       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5902
5903     // A signed comparison of sign extended values simplifies into a
5904     // signed comparison.
5905     if (isSignedCmp && isSignedExt)
5906       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5907
5908     // The other three cases all fold into an unsigned comparison.
5909     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
5910   }
5911
5912   // If we aren't dealing with a constant on the RHS, exit early
5913   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5914   if (!CI)
5915     return 0;
5916
5917   // Compute the constant that would happen if we truncated to SrcTy then
5918   // reextended to DestTy.
5919   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5920   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5921
5922   // If the re-extended constant didn't change...
5923   if (Res2 == CI) {
5924     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5925     // For example, we might have:
5926     //    %A = sext short %X to uint
5927     //    %B = icmp ugt uint %A, 1330
5928     // It is incorrect to transform this into 
5929     //    %B = icmp ugt short %X, 1330 
5930     // because %A may have negative value. 
5931     //
5932     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5933     // OR operation is EQ/NE.
5934     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5935       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5936     else
5937       return 0;
5938   }
5939
5940   // The re-extended constant changed so the constant cannot be represented 
5941   // in the shorter type. Consequently, we cannot emit a simple comparison.
5942
5943   // First, handle some easy cases. We know the result cannot be equal at this
5944   // point so handle the ICI.isEquality() cases
5945   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5946     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5947   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5948     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5949
5950   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5951   // should have been folded away previously and not enter in here.
5952   Value *Result;
5953   if (isSignedCmp) {
5954     // We're performing a signed comparison.
5955     if (cast<ConstantInt>(CI)->getValue().isNegative())
5956       Result = ConstantInt::getFalse();          // X < (small) --> false
5957     else
5958       Result = ConstantInt::getTrue();           // X < (large) --> true
5959   } else {
5960     // We're performing an unsigned comparison.
5961     if (isSignedExt) {
5962       // We're performing an unsigned comp with a sign extended value.
5963       // This is true if the input is >= 0. [aka >s -1]
5964       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5965       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5966                                    NegOne, ICI.getName()), ICI);
5967     } else {
5968       // Unsigned extend & unsigned compare -> always true.
5969       Result = ConstantInt::getTrue();
5970     }
5971   }
5972
5973   // Finally, return the value computed.
5974   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5975       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5976     return ReplaceInstUsesWith(ICI, Result);
5977   } else {
5978     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5979             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5980            "ICmp should be folded!");
5981     if (Constant *CI = dyn_cast<Constant>(Result))
5982       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5983     else
5984       return BinaryOperator::createNot(Result);
5985   }
5986 }
5987
5988 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5989   return commonShiftTransforms(I);
5990 }
5991
5992 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5993   return commonShiftTransforms(I);
5994 }
5995
5996 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5997   if (Instruction *R = commonShiftTransforms(I))
5998     return R;
5999   
6000   Value *Op0 = I.getOperand(0);
6001   
6002   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6003   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6004     if (CSI->isAllOnesValue())
6005       return ReplaceInstUsesWith(I, CSI);
6006   
6007   // See if we can turn a signed shr into an unsigned shr.
6008   if (MaskedValueIsZero(Op0, 
6009                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6010     return BinaryOperator::createLShr(Op0, I.getOperand(1));
6011   
6012   return 0;
6013 }
6014
6015 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6016   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6017   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6018
6019   // shl X, 0 == X and shr X, 0 == X
6020   // shl 0, X == 0 and shr 0, X == 0
6021   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6022       Op0 == Constant::getNullValue(Op0->getType()))
6023     return ReplaceInstUsesWith(I, Op0);
6024   
6025   if (isa<UndefValue>(Op0)) {            
6026     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6027       return ReplaceInstUsesWith(I, Op0);
6028     else                                    // undef << X -> 0, undef >>u X -> 0
6029       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6030   }
6031   if (isa<UndefValue>(Op1)) {
6032     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6033       return ReplaceInstUsesWith(I, Op0);          
6034     else                                     // X << undef, X >>u undef -> 0
6035       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6036   }
6037
6038   // Try to fold constant and into select arguments.
6039   if (isa<Constant>(Op0))
6040     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6041       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6042         return R;
6043
6044   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6045     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6046       return Res;
6047   return 0;
6048 }
6049
6050 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6051                                                BinaryOperator &I) {
6052   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6053
6054   // See if we can simplify any instructions used by the instruction whose sole 
6055   // purpose is to compute bits we don't care about.
6056   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6057   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6058   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6059                            KnownZero, KnownOne))
6060     return &I;
6061   
6062   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6063   // of a signed value.
6064   //
6065   if (Op1->uge(TypeBits)) {
6066     if (I.getOpcode() != Instruction::AShr)
6067       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6068     else {
6069       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6070       return &I;
6071     }
6072   }
6073   
6074   // ((X*C1) << C2) == (X * (C1 << C2))
6075   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6076     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6077       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6078         return BinaryOperator::createMul(BO->getOperand(0),
6079                                          ConstantExpr::getShl(BOOp, Op1));
6080   
6081   // Try to fold constant and into select arguments.
6082   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6083     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6084       return R;
6085   if (isa<PHINode>(Op0))
6086     if (Instruction *NV = FoldOpIntoPhi(I))
6087       return NV;
6088   
6089   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6090   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6091     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6092     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6093     // place.  Don't try to do this transformation in this case.  Also, we
6094     // require that the input operand is a shift-by-constant so that we have
6095     // confidence that the shifts will get folded together.  We could do this
6096     // xform in more cases, but it is unlikely to be profitable.
6097     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6098         isa<ConstantInt>(TrOp->getOperand(1))) {
6099       // Okay, we'll do this xform.  Make the shift of shift.
6100       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6101       Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6102                                                 I.getName());
6103       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6104
6105       // For logical shifts, the truncation has the effect of making the high
6106       // part of the register be zeros.  Emulate this by inserting an AND to
6107       // clear the top bits as needed.  This 'and' will usually be zapped by
6108       // other xforms later if dead.
6109       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6110       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6111       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6112       
6113       // The mask we constructed says what the trunc would do if occurring
6114       // between the shifts.  We want to know the effect *after* the second
6115       // shift.  We know that it is a logical shift by a constant, so adjust the
6116       // mask as appropriate.
6117       if (I.getOpcode() == Instruction::Shl)
6118         MaskV <<= Op1->getZExtValue();
6119       else {
6120         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6121         MaskV = MaskV.lshr(Op1->getZExtValue());
6122       }
6123
6124       Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6125                                                    TI->getName());
6126       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6127
6128       // Return the value truncated to the interesting size.
6129       return new TruncInst(And, I.getType());
6130     }
6131   }
6132   
6133   if (Op0->hasOneUse()) {
6134     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6135       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6136       Value *V1, *V2;
6137       ConstantInt *CC;
6138       switch (Op0BO->getOpcode()) {
6139         default: break;
6140         case Instruction::Add:
6141         case Instruction::And:
6142         case Instruction::Or:
6143         case Instruction::Xor: {
6144           // These operators commute.
6145           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6146           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6147               match(Op0BO->getOperand(1),
6148                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6149             Instruction *YS = BinaryOperator::createShl(
6150                                             Op0BO->getOperand(0), Op1,
6151                                             Op0BO->getName());
6152             InsertNewInstBefore(YS, I); // (Y << C)
6153             Instruction *X = 
6154               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6155                                      Op0BO->getOperand(1)->getName());
6156             InsertNewInstBefore(X, I);  // (X + (Y << C))
6157             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6158             return BinaryOperator::createAnd(X, ConstantInt::get(
6159                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6160           }
6161           
6162           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6163           Value *Op0BOOp1 = Op0BO->getOperand(1);
6164           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6165               match(Op0BOOp1, 
6166                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6167               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6168               V2 == Op1) {
6169             Instruction *YS = BinaryOperator::createShl(
6170                                                      Op0BO->getOperand(0), Op1,
6171                                                      Op0BO->getName());
6172             InsertNewInstBefore(YS, I); // (Y << C)
6173             Instruction *XM =
6174               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6175                                         V1->getName()+".mask");
6176             InsertNewInstBefore(XM, I); // X & (CC << C)
6177             
6178             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6179           }
6180         }
6181           
6182         // FALL THROUGH.
6183         case Instruction::Sub: {
6184           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6185           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6186               match(Op0BO->getOperand(0),
6187                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6188             Instruction *YS = BinaryOperator::createShl(
6189                                                      Op0BO->getOperand(1), Op1,
6190                                                      Op0BO->getName());
6191             InsertNewInstBefore(YS, I); // (Y << C)
6192             Instruction *X =
6193               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6194                                      Op0BO->getOperand(0)->getName());
6195             InsertNewInstBefore(X, I);  // (X + (Y << C))
6196             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6197             return BinaryOperator::createAnd(X, ConstantInt::get(
6198                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6199           }
6200           
6201           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6202           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6203               match(Op0BO->getOperand(0),
6204                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6205                           m_ConstantInt(CC))) && V2 == Op1 &&
6206               cast<BinaryOperator>(Op0BO->getOperand(0))
6207                   ->getOperand(0)->hasOneUse()) {
6208             Instruction *YS = BinaryOperator::createShl(
6209                                                      Op0BO->getOperand(1), Op1,
6210                                                      Op0BO->getName());
6211             InsertNewInstBefore(YS, I); // (Y << C)
6212             Instruction *XM =
6213               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6214                                         V1->getName()+".mask");
6215             InsertNewInstBefore(XM, I); // X & (CC << C)
6216             
6217             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6218           }
6219           
6220           break;
6221         }
6222       }
6223       
6224       
6225       // If the operand is an bitwise operator with a constant RHS, and the
6226       // shift is the only use, we can pull it out of the shift.
6227       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6228         bool isValid = true;     // Valid only for And, Or, Xor
6229         bool highBitSet = false; // Transform if high bit of constant set?
6230         
6231         switch (Op0BO->getOpcode()) {
6232           default: isValid = false; break;   // Do not perform transform!
6233           case Instruction::Add:
6234             isValid = isLeftShift;
6235             break;
6236           case Instruction::Or:
6237           case Instruction::Xor:
6238             highBitSet = false;
6239             break;
6240           case Instruction::And:
6241             highBitSet = true;
6242             break;
6243         }
6244         
6245         // If this is a signed shift right, and the high bit is modified
6246         // by the logical operation, do not perform the transformation.
6247         // The highBitSet boolean indicates the value of the high bit of
6248         // the constant which would cause it to be modified for this
6249         // operation.
6250         //
6251         if (isValid && I.getOpcode() == Instruction::AShr)
6252           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6253         
6254         if (isValid) {
6255           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6256           
6257           Instruction *NewShift =
6258             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6259           InsertNewInstBefore(NewShift, I);
6260           NewShift->takeName(Op0BO);
6261           
6262           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6263                                         NewRHS);
6264         }
6265       }
6266     }
6267   }
6268   
6269   // Find out if this is a shift of a shift by a constant.
6270   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6271   if (ShiftOp && !ShiftOp->isShift())
6272     ShiftOp = 0;
6273   
6274   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6275     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6276     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6277     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6278     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6279     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6280     Value *X = ShiftOp->getOperand(0);
6281     
6282     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6283     if (AmtSum > TypeBits)
6284       AmtSum = TypeBits;
6285     
6286     const IntegerType *Ty = cast<IntegerType>(I.getType());
6287     
6288     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6289     if (I.getOpcode() == ShiftOp->getOpcode()) {
6290       return BinaryOperator::create(I.getOpcode(), X,
6291                                     ConstantInt::get(Ty, AmtSum));
6292     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6293                I.getOpcode() == Instruction::AShr) {
6294       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6295       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6296     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6297                I.getOpcode() == Instruction::LShr) {
6298       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6299       Instruction *Shift =
6300         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6301       InsertNewInstBefore(Shift, I);
6302
6303       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6304       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6305     }
6306     
6307     // Okay, if we get here, one shift must be left, and the other shift must be
6308     // right.  See if the amounts are equal.
6309     if (ShiftAmt1 == ShiftAmt2) {
6310       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6311       if (I.getOpcode() == Instruction::Shl) {
6312         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6313         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6314       }
6315       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6316       if (I.getOpcode() == Instruction::LShr) {
6317         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6318         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6319       }
6320       // We can simplify ((X << C) >>s C) into a trunc + sext.
6321       // NOTE: we could do this for any C, but that would make 'unusual' integer
6322       // types.  For now, just stick to ones well-supported by the code
6323       // generators.
6324       const Type *SExtType = 0;
6325       switch (Ty->getBitWidth() - ShiftAmt1) {
6326       case 1  :
6327       case 8  :
6328       case 16 :
6329       case 32 :
6330       case 64 :
6331       case 128:
6332         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6333         break;
6334       default: break;
6335       }
6336       if (SExtType) {
6337         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6338         InsertNewInstBefore(NewTrunc, I);
6339         return new SExtInst(NewTrunc, Ty);
6340       }
6341       // Otherwise, we can't handle it yet.
6342     } else if (ShiftAmt1 < ShiftAmt2) {
6343       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6344       
6345       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6346       if (I.getOpcode() == Instruction::Shl) {
6347         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6348                ShiftOp->getOpcode() == Instruction::AShr);
6349         Instruction *Shift =
6350           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6351         InsertNewInstBefore(Shift, I);
6352         
6353         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6354         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6355       }
6356       
6357       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6358       if (I.getOpcode() == Instruction::LShr) {
6359         assert(ShiftOp->getOpcode() == Instruction::Shl);
6360         Instruction *Shift =
6361           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6362         InsertNewInstBefore(Shift, I);
6363         
6364         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6365         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6366       }
6367       
6368       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6369     } else {
6370       assert(ShiftAmt2 < ShiftAmt1);
6371       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6372
6373       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6374       if (I.getOpcode() == Instruction::Shl) {
6375         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6376                ShiftOp->getOpcode() == Instruction::AShr);
6377         Instruction *Shift =
6378           BinaryOperator::create(ShiftOp->getOpcode(), X,
6379                                  ConstantInt::get(Ty, ShiftDiff));
6380         InsertNewInstBefore(Shift, I);
6381         
6382         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6383         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6384       }
6385       
6386       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6387       if (I.getOpcode() == Instruction::LShr) {
6388         assert(ShiftOp->getOpcode() == Instruction::Shl);
6389         Instruction *Shift =
6390           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6391         InsertNewInstBefore(Shift, I);
6392         
6393         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6394         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6395       }
6396       
6397       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6398     }
6399   }
6400   return 0;
6401 }
6402
6403
6404 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6405 /// expression.  If so, decompose it, returning some value X, such that Val is
6406 /// X*Scale+Offset.
6407 ///
6408 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6409                                         int &Offset) {
6410   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6411   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6412     Offset = CI->getZExtValue();
6413     Scale  = 0;
6414     return ConstantInt::get(Type::Int32Ty, 0);
6415   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6416     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6417       if (I->getOpcode() == Instruction::Shl) {
6418         // This is a value scaled by '1 << the shift amt'.
6419         Scale = 1U << RHS->getZExtValue();
6420         Offset = 0;
6421         return I->getOperand(0);
6422       } else if (I->getOpcode() == Instruction::Mul) {
6423         // This value is scaled by 'RHS'.
6424         Scale = RHS->getZExtValue();
6425         Offset = 0;
6426         return I->getOperand(0);
6427       } else if (I->getOpcode() == Instruction::Add) {
6428         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6429         // where C1 is divisible by C2.
6430         unsigned SubScale;
6431         Value *SubVal = 
6432           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6433         Offset += RHS->getZExtValue();
6434         Scale = SubScale;
6435         return SubVal;
6436       }
6437     }
6438   }
6439
6440   // Otherwise, we can't look past this.
6441   Scale = 1;
6442   Offset = 0;
6443   return Val;
6444 }
6445
6446
6447 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6448 /// try to eliminate the cast by moving the type information into the alloc.
6449 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6450                                                    AllocationInst &AI) {
6451   const PointerType *PTy = cast<PointerType>(CI.getType());
6452   
6453   // Remove any uses of AI that are dead.
6454   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6455   
6456   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6457     Instruction *User = cast<Instruction>(*UI++);
6458     if (isInstructionTriviallyDead(User)) {
6459       while (UI != E && *UI == User)
6460         ++UI; // If this instruction uses AI more than once, don't break UI.
6461       
6462       ++NumDeadInst;
6463       DOUT << "IC: DCE: " << *User;
6464       EraseInstFromFunction(*User);
6465     }
6466   }
6467   
6468   // Get the type really allocated and the type casted to.
6469   const Type *AllocElTy = AI.getAllocatedType();
6470   const Type *CastElTy = PTy->getElementType();
6471   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6472
6473   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6474   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6475   if (CastElTyAlign < AllocElTyAlign) return 0;
6476
6477   // If the allocation has multiple uses, only promote it if we are strictly
6478   // increasing the alignment of the resultant allocation.  If we keep it the
6479   // same, we open the door to infinite loops of various kinds.
6480   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6481
6482   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6483   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6484   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6485
6486   // See if we can satisfy the modulus by pulling a scale out of the array
6487   // size argument.
6488   unsigned ArraySizeScale;
6489   int ArrayOffset;
6490   Value *NumElements = // See if the array size is a decomposable linear expr.
6491     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6492  
6493   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6494   // do the xform.
6495   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6496       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6497
6498   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6499   Value *Amt = 0;
6500   if (Scale == 1) {
6501     Amt = NumElements;
6502   } else {
6503     // If the allocation size is constant, form a constant mul expression
6504     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6505     if (isa<ConstantInt>(NumElements))
6506       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6507     // otherwise multiply the amount and the number of elements
6508     else if (Scale != 1) {
6509       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6510       Amt = InsertNewInstBefore(Tmp, AI);
6511     }
6512   }
6513   
6514   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6515     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6516     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6517     Amt = InsertNewInstBefore(Tmp, AI);
6518   }
6519   
6520   AllocationInst *New;
6521   if (isa<MallocInst>(AI))
6522     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6523   else
6524     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6525   InsertNewInstBefore(New, AI);
6526   New->takeName(&AI);
6527   
6528   // If the allocation has multiple uses, insert a cast and change all things
6529   // that used it to use the new cast.  This will also hack on CI, but it will
6530   // die soon.
6531   if (!AI.hasOneUse()) {
6532     AddUsesToWorkList(AI);
6533     // New is the allocation instruction, pointer typed. AI is the original
6534     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6535     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6536     InsertNewInstBefore(NewCast, AI);
6537     AI.replaceAllUsesWith(NewCast);
6538   }
6539   return ReplaceInstUsesWith(CI, New);
6540 }
6541
6542 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6543 /// and return it as type Ty without inserting any new casts and without
6544 /// changing the computed value.  This is used by code that tries to decide
6545 /// whether promoting or shrinking integer operations to wider or smaller types
6546 /// will allow us to eliminate a truncate or extend.
6547 ///
6548 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6549 /// extension operation if Ty is larger.
6550 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6551                                        unsigned CastOpc, int &NumCastsRemoved) {
6552   // We can always evaluate constants in another type.
6553   if (isa<ConstantInt>(V))
6554     return true;
6555   
6556   Instruction *I = dyn_cast<Instruction>(V);
6557   if (!I) return false;
6558   
6559   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6560   
6561   // If this is an extension or truncate, we can often eliminate it.
6562   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6563     // If this is a cast from the destination type, we can trivially eliminate
6564     // it, and this will remove a cast overall.
6565     if (I->getOperand(0)->getType() == Ty) {
6566       // If the first operand is itself a cast, and is eliminable, do not count
6567       // this as an eliminable cast.  We would prefer to eliminate those two
6568       // casts first.
6569       if (!isa<CastInst>(I->getOperand(0)))
6570         ++NumCastsRemoved;
6571       return true;
6572     }
6573   }
6574
6575   // We can't extend or shrink something that has multiple uses: doing so would
6576   // require duplicating the instruction in general, which isn't profitable.
6577   if (!I->hasOneUse()) return false;
6578
6579   switch (I->getOpcode()) {
6580   case Instruction::Add:
6581   case Instruction::Sub:
6582   case Instruction::And:
6583   case Instruction::Or:
6584   case Instruction::Xor:
6585     // These operators can all arbitrarily be extended or truncated.
6586     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6587                                       NumCastsRemoved) &&
6588            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6589                                       NumCastsRemoved);
6590
6591   case Instruction::Mul:
6592     // A multiply can be truncated by truncating its operands.
6593     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
6594            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6595                                       NumCastsRemoved) &&
6596            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6597                                       NumCastsRemoved);
6598
6599   case Instruction::Shl:
6600     // If we are truncating the result of this SHL, and if it's a shift of a
6601     // constant amount, we can always perform a SHL in a smaller type.
6602     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6603       uint32_t BitWidth = Ty->getBitWidth();
6604       if (BitWidth < OrigTy->getBitWidth() && 
6605           CI->getLimitedValue(BitWidth) < BitWidth)
6606         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6607                                           NumCastsRemoved);
6608     }
6609     break;
6610   case Instruction::LShr:
6611     // If this is a truncate of a logical shr, we can truncate it to a smaller
6612     // lshr iff we know that the bits we would otherwise be shifting in are
6613     // already zeros.
6614     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6615       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6616       uint32_t BitWidth = Ty->getBitWidth();
6617       if (BitWidth < OrigBitWidth &&
6618           MaskedValueIsZero(I->getOperand(0),
6619             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6620           CI->getLimitedValue(BitWidth) < BitWidth) {
6621         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6622                                           NumCastsRemoved);
6623       }
6624     }
6625     break;
6626   case Instruction::ZExt:
6627   case Instruction::SExt:
6628   case Instruction::Trunc:
6629     // If this is the same kind of case as our original (e.g. zext+zext), we
6630     // can safely replace it.  Note that replacing it does not reduce the number
6631     // of casts in the input.
6632     if (I->getOpcode() == CastOpc)
6633       return true;
6634     
6635     break;
6636   default:
6637     // TODO: Can handle more cases here.
6638     break;
6639   }
6640   
6641   return false;
6642 }
6643
6644 /// EvaluateInDifferentType - Given an expression that 
6645 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6646 /// evaluate the expression.
6647 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6648                                              bool isSigned) {
6649   if (Constant *C = dyn_cast<Constant>(V))
6650     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6651
6652   // Otherwise, it must be an instruction.
6653   Instruction *I = cast<Instruction>(V);
6654   Instruction *Res = 0;
6655   switch (I->getOpcode()) {
6656   case Instruction::Add:
6657   case Instruction::Sub:
6658   case Instruction::Mul:
6659   case Instruction::And:
6660   case Instruction::Or:
6661   case Instruction::Xor:
6662   case Instruction::AShr:
6663   case Instruction::LShr:
6664   case Instruction::Shl: {
6665     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6666     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6667     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6668                                  LHS, RHS, I->getName());
6669     break;
6670   }    
6671   case Instruction::Trunc:
6672   case Instruction::ZExt:
6673   case Instruction::SExt:
6674     // If the source type of the cast is the type we're trying for then we can
6675     // just return the source.  There's no need to insert it because it is not
6676     // new.
6677     if (I->getOperand(0)->getType() == Ty)
6678       return I->getOperand(0);
6679     
6680     // Otherwise, must be the same type of case, so just reinsert a new one.
6681     Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6682                            Ty, I->getName());
6683     break;
6684   default: 
6685     // TODO: Can handle more cases here.
6686     assert(0 && "Unreachable!");
6687     break;
6688   }
6689   
6690   return InsertNewInstBefore(Res, *I);
6691 }
6692
6693 /// @brief Implement the transforms common to all CastInst visitors.
6694 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6695   Value *Src = CI.getOperand(0);
6696
6697   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6698   // eliminate it now.
6699   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6700     if (Instruction::CastOps opc = 
6701         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6702       // The first cast (CSrc) is eliminable so we need to fix up or replace
6703       // the second cast (CI). CSrc will then have a good chance of being dead.
6704       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6705     }
6706   }
6707
6708   // If we are casting a select then fold the cast into the select
6709   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6710     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6711       return NV;
6712
6713   // If we are casting a PHI then fold the cast into the PHI
6714   if (isa<PHINode>(Src))
6715     if (Instruction *NV = FoldOpIntoPhi(CI))
6716       return NV;
6717   
6718   return 0;
6719 }
6720
6721 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6722 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6723   Value *Src = CI.getOperand(0);
6724   
6725   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6726     // If casting the result of a getelementptr instruction with no offset, turn
6727     // this into a cast of the original pointer!
6728     if (GEP->hasAllZeroIndices()) {
6729       // Changing the cast operand is usually not a good idea but it is safe
6730       // here because the pointer operand is being replaced with another 
6731       // pointer operand so the opcode doesn't need to change.
6732       AddToWorkList(GEP);
6733       CI.setOperand(0, GEP->getOperand(0));
6734       return &CI;
6735     }
6736     
6737     // If the GEP has a single use, and the base pointer is a bitcast, and the
6738     // GEP computes a constant offset, see if we can convert these three
6739     // instructions into fewer.  This typically happens with unions and other
6740     // non-type-safe code.
6741     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6742       if (GEP->hasAllConstantIndices()) {
6743         // We are guaranteed to get a constant from EmitGEPOffset.
6744         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6745         int64_t Offset = OffsetV->getSExtValue();
6746         
6747         // Get the base pointer input of the bitcast, and the type it points to.
6748         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6749         const Type *GEPIdxTy =
6750           cast<PointerType>(OrigBase->getType())->getElementType();
6751         if (GEPIdxTy->isSized()) {
6752           SmallVector<Value*, 8> NewIndices;
6753           
6754           // Start with the index over the outer type.  Note that the type size
6755           // might be zero (even if the offset isn't zero) if the indexed type
6756           // is something like [0 x {int, int}]
6757           const Type *IntPtrTy = TD->getIntPtrType();
6758           int64_t FirstIdx = 0;
6759           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
6760             FirstIdx = Offset/TySize;
6761             Offset %= TySize;
6762           
6763             // Handle silly modulus not returning values values [0..TySize).
6764             if (Offset < 0) {
6765               --FirstIdx;
6766               Offset += TySize;
6767               assert(Offset >= 0);
6768             }
6769             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6770           }
6771           
6772           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6773
6774           // Index into the types.  If we fail, set OrigBase to null.
6775           while (Offset) {
6776             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6777               const StructLayout *SL = TD->getStructLayout(STy);
6778               if (Offset < (int64_t)SL->getSizeInBytes()) {
6779                 unsigned Elt = SL->getElementContainingOffset(Offset);
6780                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6781               
6782                 Offset -= SL->getElementOffset(Elt);
6783                 GEPIdxTy = STy->getElementType(Elt);
6784               } else {
6785                 // Otherwise, we can't index into this, bail out.
6786                 Offset = 0;
6787                 OrigBase = 0;
6788               }
6789             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6790               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6791               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
6792                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6793                 Offset %= EltSize;
6794               } else {
6795                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6796               }
6797               GEPIdxTy = STy->getElementType();
6798             } else {
6799               // Otherwise, we can't index into this, bail out.
6800               Offset = 0;
6801               OrigBase = 0;
6802             }
6803           }
6804           if (OrigBase) {
6805             // If we were able to index down into an element, create the GEP
6806             // and bitcast the result.  This eliminates one bitcast, potentially
6807             // two.
6808             Instruction *NGEP = new GetElementPtrInst(OrigBase, 
6809                                                       NewIndices.begin(),
6810                                                       NewIndices.end(), "");
6811             InsertNewInstBefore(NGEP, CI);
6812             NGEP->takeName(GEP);
6813             
6814             if (isa<BitCastInst>(CI))
6815               return new BitCastInst(NGEP, CI.getType());
6816             assert(isa<PtrToIntInst>(CI));
6817             return new PtrToIntInst(NGEP, CI.getType());
6818           }
6819         }
6820       }      
6821     }
6822   }
6823     
6824   return commonCastTransforms(CI);
6825 }
6826
6827
6828
6829 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6830 /// integer types. This function implements the common transforms for all those
6831 /// cases.
6832 /// @brief Implement the transforms common to CastInst with integer operands
6833 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6834   if (Instruction *Result = commonCastTransforms(CI))
6835     return Result;
6836
6837   Value *Src = CI.getOperand(0);
6838   const Type *SrcTy = Src->getType();
6839   const Type *DestTy = CI.getType();
6840   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6841   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6842
6843   // See if we can simplify any instructions used by the LHS whose sole 
6844   // purpose is to compute bits we don't care about.
6845   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6846   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6847                            KnownZero, KnownOne))
6848     return &CI;
6849
6850   // If the source isn't an instruction or has more than one use then we
6851   // can't do anything more. 
6852   Instruction *SrcI = dyn_cast<Instruction>(Src);
6853   if (!SrcI || !Src->hasOneUse())
6854     return 0;
6855
6856   // Attempt to propagate the cast into the instruction for int->int casts.
6857   int NumCastsRemoved = 0;
6858   if (!isa<BitCastInst>(CI) &&
6859       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6860                                  CI.getOpcode(), NumCastsRemoved)) {
6861     // If this cast is a truncate, evaluting in a different type always
6862     // eliminates the cast, so it is always a win.  If this is a zero-extension,
6863     // we need to do an AND to maintain the clear top-part of the computation,
6864     // so we require that the input have eliminated at least one cast.  If this
6865     // is a sign extension, we insert two new casts (to do the extension) so we
6866     // require that two casts have been eliminated.
6867     bool DoXForm;
6868     switch (CI.getOpcode()) {
6869     default:
6870       // All the others use floating point so we shouldn't actually 
6871       // get here because of the check above.
6872       assert(0 && "Unknown cast type");
6873     case Instruction::Trunc:
6874       DoXForm = true;
6875       break;
6876     case Instruction::ZExt:
6877       DoXForm = NumCastsRemoved >= 1;
6878       break;
6879     case Instruction::SExt:
6880       DoXForm = NumCastsRemoved >= 2;
6881       break;
6882     }
6883     
6884     if (DoXForm) {
6885       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6886                                            CI.getOpcode() == Instruction::SExt);
6887       assert(Res->getType() == DestTy);
6888       switch (CI.getOpcode()) {
6889       default: assert(0 && "Unknown cast type!");
6890       case Instruction::Trunc:
6891       case Instruction::BitCast:
6892         // Just replace this cast with the result.
6893         return ReplaceInstUsesWith(CI, Res);
6894       case Instruction::ZExt: {
6895         // We need to emit an AND to clear the high bits.
6896         assert(SrcBitSize < DestBitSize && "Not a zext?");
6897         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6898                                                             SrcBitSize));
6899         return BinaryOperator::createAnd(Res, C);
6900       }
6901       case Instruction::SExt:
6902         // We need to emit a cast to truncate, then a cast to sext.
6903         return CastInst::create(Instruction::SExt,
6904             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6905                              CI), DestTy);
6906       }
6907     }
6908   }
6909   
6910   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6911   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6912
6913   switch (SrcI->getOpcode()) {
6914   case Instruction::Add:
6915   case Instruction::Mul:
6916   case Instruction::And:
6917   case Instruction::Or:
6918   case Instruction::Xor:
6919     // If we are discarding information, rewrite.
6920     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6921       // Don't insert two casts if they cannot be eliminated.  We allow 
6922       // two casts to be inserted if the sizes are the same.  This could 
6923       // only be converting signedness, which is a noop.
6924       if (DestBitSize == SrcBitSize || 
6925           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6926           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6927         Instruction::CastOps opcode = CI.getOpcode();
6928         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6929         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6930         return BinaryOperator::create(
6931             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6932       }
6933     }
6934
6935     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6936     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6937         SrcI->getOpcode() == Instruction::Xor &&
6938         Op1 == ConstantInt::getTrue() &&
6939         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6940       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6941       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6942     }
6943     break;
6944   case Instruction::SDiv:
6945   case Instruction::UDiv:
6946   case Instruction::SRem:
6947   case Instruction::URem:
6948     // If we are just changing the sign, rewrite.
6949     if (DestBitSize == SrcBitSize) {
6950       // Don't insert two casts if they cannot be eliminated.  We allow 
6951       // two casts to be inserted if the sizes are the same.  This could 
6952       // only be converting signedness, which is a noop.
6953       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6954           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6955         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6956                                               Op0, DestTy, SrcI);
6957         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6958                                               Op1, DestTy, SrcI);
6959         return BinaryOperator::create(
6960           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6961       }
6962     }
6963     break;
6964
6965   case Instruction::Shl:
6966     // Allow changing the sign of the source operand.  Do not allow 
6967     // changing the size of the shift, UNLESS the shift amount is a 
6968     // constant.  We must not change variable sized shifts to a smaller 
6969     // size, because it is undefined to shift more bits out than exist 
6970     // in the value.
6971     if (DestBitSize == SrcBitSize ||
6972         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6973       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6974           Instruction::BitCast : Instruction::Trunc);
6975       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6976       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6977       return BinaryOperator::createShl(Op0c, Op1c);
6978     }
6979     break;
6980   case Instruction::AShr:
6981     // If this is a signed shr, and if all bits shifted in are about to be
6982     // truncated off, turn it into an unsigned shr to allow greater
6983     // simplifications.
6984     if (DestBitSize < SrcBitSize &&
6985         isa<ConstantInt>(Op1)) {
6986       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6987       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6988         // Insert the new logical shift right.
6989         return BinaryOperator::createLShr(Op0, Op1);
6990       }
6991     }
6992     break;
6993   }
6994   return 0;
6995 }
6996
6997 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6998   if (Instruction *Result = commonIntCastTransforms(CI))
6999     return Result;
7000   
7001   Value *Src = CI.getOperand(0);
7002   const Type *Ty = CI.getType();
7003   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7004   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7005   
7006   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7007     switch (SrcI->getOpcode()) {
7008     default: break;
7009     case Instruction::LShr:
7010       // We can shrink lshr to something smaller if we know the bits shifted in
7011       // are already zeros.
7012       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7013         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7014         
7015         // Get a mask for the bits shifting in.
7016         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7017         Value* SrcIOp0 = SrcI->getOperand(0);
7018         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7019           if (ShAmt >= DestBitWidth)        // All zeros.
7020             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7021
7022           // Okay, we can shrink this.  Truncate the input, then return a new
7023           // shift.
7024           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7025           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7026                                        Ty, CI);
7027           return BinaryOperator::createLShr(V1, V2);
7028         }
7029       } else {     // This is a variable shr.
7030         
7031         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7032         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7033         // loop-invariant and CSE'd.
7034         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7035           Value *One = ConstantInt::get(SrcI->getType(), 1);
7036
7037           Value *V = InsertNewInstBefore(
7038               BinaryOperator::createShl(One, SrcI->getOperand(1),
7039                                      "tmp"), CI);
7040           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7041                                                             SrcI->getOperand(0),
7042                                                             "tmp"), CI);
7043           Value *Zero = Constant::getNullValue(V->getType());
7044           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7045         }
7046       }
7047       break;
7048     }
7049   }
7050   
7051   return 0;
7052 }
7053
7054 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7055   // If one of the common conversion will work ..
7056   if (Instruction *Result = commonIntCastTransforms(CI))
7057     return Result;
7058
7059   Value *Src = CI.getOperand(0);
7060
7061   // If this is a cast of a cast
7062   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7063     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7064     // types and if the sizes are just right we can convert this into a logical
7065     // 'and' which will be much cheaper than the pair of casts.
7066     if (isa<TruncInst>(CSrc)) {
7067       // Get the sizes of the types involved
7068       Value *A = CSrc->getOperand(0);
7069       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7070       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7071       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7072       // If we're actually extending zero bits and the trunc is a no-op
7073       if (MidSize < DstSize && SrcSize == DstSize) {
7074         // Replace both of the casts with an And of the type mask.
7075         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7076         Constant *AndConst = ConstantInt::get(AndValue);
7077         Instruction *And = 
7078           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7079         // Unfortunately, if the type changed, we need to cast it back.
7080         if (And->getType() != CI.getType()) {
7081           And->setName(CSrc->getName()+".mask");
7082           InsertNewInstBefore(And, CI);
7083           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7084         }
7085         return And;
7086       }
7087     }
7088   }
7089
7090   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7091     // If we are just checking for a icmp eq of a single bit and zext'ing it
7092     // to an integer, then shift the bit to the appropriate place and then
7093     // cast to integer to avoid the comparison.
7094     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7095       const APInt &Op1CV = Op1C->getValue();
7096       
7097       // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7098       // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7099       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7100           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7101         Value *In = ICI->getOperand(0);
7102         Value *Sh = ConstantInt::get(In->getType(),
7103                                     In->getType()->getPrimitiveSizeInBits()-1);
7104         In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7105                                                         In->getName()+".lobit"),
7106                                  CI);
7107         if (In->getType() != CI.getType())
7108           In = CastInst::createIntegerCast(In, CI.getType(),
7109                                            false/*ZExt*/, "tmp", &CI);
7110
7111         if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7112           Constant *One = ConstantInt::get(In->getType(), 1);
7113           In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7114                                                           In->getName()+".not"),
7115                                    CI);
7116         }
7117
7118         return ReplaceInstUsesWith(CI, In);
7119       }
7120       
7121       
7122       
7123       // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7124       // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7125       // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7126       // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7127       // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7128       // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7129       // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7130       // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7131       if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7132           // This only works for EQ and NE
7133           ICI->isEquality()) {
7134         // If Op1C some other power of two, convert:
7135         uint32_t BitWidth = Op1C->getType()->getBitWidth();
7136         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7137         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7138         ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7139         
7140         APInt KnownZeroMask(~KnownZero);
7141         if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7142           bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7143           if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7144             // (X&4) == 2 --> false
7145             // (X&4) != 2 --> true
7146             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7147             Res = ConstantExpr::getZExt(Res, CI.getType());
7148             return ReplaceInstUsesWith(CI, Res);
7149           }
7150           
7151           uint32_t ShiftAmt = KnownZeroMask.logBase2();
7152           Value *In = ICI->getOperand(0);
7153           if (ShiftAmt) {
7154             // Perform a logical shr by shiftamt.
7155             // Insert the shift to put the result in the low bit.
7156             In = InsertNewInstBefore(
7157                    BinaryOperator::createLShr(In,
7158                                      ConstantInt::get(In->getType(), ShiftAmt),
7159                                               In->getName()+".lobit"), CI);
7160           }
7161           
7162           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7163             Constant *One = ConstantInt::get(In->getType(), 1);
7164             In = BinaryOperator::createXor(In, One, "tmp");
7165             InsertNewInstBefore(cast<Instruction>(In), CI);
7166           }
7167           
7168           if (CI.getType() == In->getType())
7169             return ReplaceInstUsesWith(CI, In);
7170           else
7171             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7172         }
7173       }
7174     }
7175   }    
7176   return 0;
7177 }
7178
7179 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7180   if (Instruction *I = commonIntCastTransforms(CI))
7181     return I;
7182   
7183   Value *Src = CI.getOperand(0);
7184   
7185   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7186   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7187   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7188     // If we are just checking for a icmp eq of a single bit and zext'ing it
7189     // to an integer, then shift the bit to the appropriate place and then
7190     // cast to integer to avoid the comparison.
7191     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7192       const APInt &Op1CV = Op1C->getValue();
7193       
7194       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7195       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7196       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7197           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7198         Value *In = ICI->getOperand(0);
7199         Value *Sh = ConstantInt::get(In->getType(),
7200                                      In->getType()->getPrimitiveSizeInBits()-1);
7201         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7202                                                         In->getName()+".lobit"),
7203                                  CI);
7204         if (In->getType() != CI.getType())
7205           In = CastInst::createIntegerCast(In, CI.getType(),
7206                                            true/*SExt*/, "tmp", &CI);
7207         
7208         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7209           In = InsertNewInstBefore(BinaryOperator::createNot(In,
7210                                      In->getName()+".not"), CI);
7211         
7212         return ReplaceInstUsesWith(CI, In);
7213       }
7214     }
7215   }
7216       
7217   return 0;
7218 }
7219
7220 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7221 /// in the specified FP type without changing its value.
7222 static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy, 
7223                               const fltSemantics &Sem) {
7224   APFloat F = CFP->getValueAPF();
7225   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7226     return ConstantFP::get(FPTy, F);
7227   return 0;
7228 }
7229
7230 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7231 /// through it until we get the source value.
7232 static Value *LookThroughFPExtensions(Value *V) {
7233   if (Instruction *I = dyn_cast<Instruction>(V))
7234     if (I->getOpcode() == Instruction::FPExt)
7235       return LookThroughFPExtensions(I->getOperand(0));
7236   
7237   // If this value is a constant, return the constant in the smallest FP type
7238   // that can accurately represent it.  This allows us to turn
7239   // (float)((double)X+2.0) into x+2.0f.
7240   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7241     if (CFP->getType() == Type::PPC_FP128Ty)
7242       return V;  // No constant folding of this.
7243     // See if the value can be truncated to float and then reextended.
7244     if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7245       return V;
7246     if (CFP->getType() == Type::DoubleTy)
7247       return V;  // Won't shrink.
7248     if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7249       return V;
7250     // Don't try to shrink to various long double types.
7251   }
7252   
7253   return V;
7254 }
7255
7256 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7257   if (Instruction *I = commonCastTransforms(CI))
7258     return I;
7259   
7260   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7261   // smaller than the destination type, we can eliminate the truncate by doing
7262   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7263   // many builtins (sqrt, etc).
7264   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7265   if (OpI && OpI->hasOneUse()) {
7266     switch (OpI->getOpcode()) {
7267     default: break;
7268     case Instruction::Add:
7269     case Instruction::Sub:
7270     case Instruction::Mul:
7271     case Instruction::FDiv:
7272     case Instruction::FRem:
7273       const Type *SrcTy = OpI->getType();
7274       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7275       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7276       if (LHSTrunc->getType() != SrcTy && 
7277           RHSTrunc->getType() != SrcTy) {
7278         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7279         // If the source types were both smaller than the destination type of
7280         // the cast, do this xform.
7281         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7282             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7283           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7284                                       CI.getType(), CI);
7285           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7286                                       CI.getType(), CI);
7287           return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7288         }
7289       }
7290       break;  
7291     }
7292   }
7293   return 0;
7294 }
7295
7296 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7297   return commonCastTransforms(CI);
7298 }
7299
7300 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7301   return commonCastTransforms(CI);
7302 }
7303
7304 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7305   return commonCastTransforms(CI);
7306 }
7307
7308 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7309   return commonCastTransforms(CI);
7310 }
7311
7312 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7313   return commonCastTransforms(CI);
7314 }
7315
7316 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7317   return commonPointerCastTransforms(CI);
7318 }
7319
7320 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7321   if (Instruction *I = commonCastTransforms(CI))
7322     return I;
7323   
7324   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7325   if (!DestPointee->isSized()) return 0;
7326
7327   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7328   ConstantInt *Cst;
7329   Value *X;
7330   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7331                                     m_ConstantInt(Cst)))) {
7332     // If the source and destination operands have the same type, see if this
7333     // is a single-index GEP.
7334     if (X->getType() == CI.getType()) {
7335       // Get the size of the pointee type.
7336       uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7337
7338       // Convert the constant to intptr type.
7339       APInt Offset = Cst->getValue();
7340       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7341
7342       // If Offset is evenly divisible by Size, we can do this xform.
7343       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7344         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7345         return new GetElementPtrInst(X, ConstantInt::get(Offset));
7346       }
7347     }
7348     // TODO: Could handle other cases, e.g. where add is indexing into field of
7349     // struct etc.
7350   } else if (CI.getOperand(0)->hasOneUse() &&
7351              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7352     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7353     // "inttoptr+GEP" instead of "add+intptr".
7354     
7355     // Get the size of the pointee type.
7356     uint64_t Size = TD->getABITypeSize(DestPointee);
7357     
7358     // Convert the constant to intptr type.
7359     APInt Offset = Cst->getValue();
7360     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7361     
7362     // If Offset is evenly divisible by Size, we can do this xform.
7363     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7364       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7365       
7366       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7367                                                             "tmp"), CI);
7368       return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7369     }
7370   }
7371   return 0;
7372 }
7373
7374 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7375   // If the operands are integer typed then apply the integer transforms,
7376   // otherwise just apply the common ones.
7377   Value *Src = CI.getOperand(0);
7378   const Type *SrcTy = Src->getType();
7379   const Type *DestTy = CI.getType();
7380
7381   if (SrcTy->isInteger() && DestTy->isInteger()) {
7382     if (Instruction *Result = commonIntCastTransforms(CI))
7383       return Result;
7384   } else if (isa<PointerType>(SrcTy)) {
7385     if (Instruction *I = commonPointerCastTransforms(CI))
7386       return I;
7387   } else {
7388     if (Instruction *Result = commonCastTransforms(CI))
7389       return Result;
7390   }
7391
7392
7393   // Get rid of casts from one type to the same type. These are useless and can
7394   // be replaced by the operand.
7395   if (DestTy == Src->getType())
7396     return ReplaceInstUsesWith(CI, Src);
7397
7398   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7399     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7400     const Type *DstElTy = DstPTy->getElementType();
7401     const Type *SrcElTy = SrcPTy->getElementType();
7402     
7403     // If we are casting a malloc or alloca to a pointer to a type of the same
7404     // size, rewrite the allocation instruction to allocate the "right" type.
7405     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7406       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7407         return V;
7408     
7409     // If the source and destination are pointers, and this cast is equivalent
7410     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7411     // This can enhance SROA and other transforms that want type-safe pointers.
7412     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7413     unsigned NumZeros = 0;
7414     while (SrcElTy != DstElTy && 
7415            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7416            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7417       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7418       ++NumZeros;
7419     }
7420
7421     // If we found a path from the src to dest, create the getelementptr now.
7422     if (SrcElTy == DstElTy) {
7423       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7424       return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "", 
7425                                    ((Instruction*) NULL));
7426     }
7427   }
7428
7429   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7430     if (SVI->hasOneUse()) {
7431       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7432       // a bitconvert to a vector with the same # elts.
7433       if (isa<VectorType>(DestTy) && 
7434           cast<VectorType>(DestTy)->getNumElements() == 
7435                 SVI->getType()->getNumElements()) {
7436         CastInst *Tmp;
7437         // If either of the operands is a cast from CI.getType(), then
7438         // evaluating the shuffle in the casted destination's type will allow
7439         // us to eliminate at least one cast.
7440         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7441              Tmp->getOperand(0)->getType() == DestTy) ||
7442             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7443              Tmp->getOperand(0)->getType() == DestTy)) {
7444           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7445                                                SVI->getOperand(0), DestTy, &CI);
7446           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7447                                                SVI->getOperand(1), DestTy, &CI);
7448           // Return a new shuffle vector.  Use the same element ID's, as we
7449           // know the vector types match #elts.
7450           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7451         }
7452       }
7453     }
7454   }
7455   return 0;
7456 }
7457
7458 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7459 ///   %C = or %A, %B
7460 ///   %D = select %cond, %C, %A
7461 /// into:
7462 ///   %C = select %cond, %B, 0
7463 ///   %D = or %A, %C
7464 ///
7465 /// Assuming that the specified instruction is an operand to the select, return
7466 /// a bitmask indicating which operands of this instruction are foldable if they
7467 /// equal the other incoming value of the select.
7468 ///
7469 static unsigned GetSelectFoldableOperands(Instruction *I) {
7470   switch (I->getOpcode()) {
7471   case Instruction::Add:
7472   case Instruction::Mul:
7473   case Instruction::And:
7474   case Instruction::Or:
7475   case Instruction::Xor:
7476     return 3;              // Can fold through either operand.
7477   case Instruction::Sub:   // Can only fold on the amount subtracted.
7478   case Instruction::Shl:   // Can only fold on the shift amount.
7479   case Instruction::LShr:
7480   case Instruction::AShr:
7481     return 1;
7482   default:
7483     return 0;              // Cannot fold
7484   }
7485 }
7486
7487 /// GetSelectFoldableConstant - For the same transformation as the previous
7488 /// function, return the identity constant that goes into the select.
7489 static Constant *GetSelectFoldableConstant(Instruction *I) {
7490   switch (I->getOpcode()) {
7491   default: assert(0 && "This cannot happen!"); abort();
7492   case Instruction::Add:
7493   case Instruction::Sub:
7494   case Instruction::Or:
7495   case Instruction::Xor:
7496   case Instruction::Shl:
7497   case Instruction::LShr:
7498   case Instruction::AShr:
7499     return Constant::getNullValue(I->getType());
7500   case Instruction::And:
7501     return Constant::getAllOnesValue(I->getType());
7502   case Instruction::Mul:
7503     return ConstantInt::get(I->getType(), 1);
7504   }
7505 }
7506
7507 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7508 /// have the same opcode and only one use each.  Try to simplify this.
7509 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7510                                           Instruction *FI) {
7511   if (TI->getNumOperands() == 1) {
7512     // If this is a non-volatile load or a cast from the same type,
7513     // merge.
7514     if (TI->isCast()) {
7515       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7516         return 0;
7517     } else {
7518       return 0;  // unknown unary op.
7519     }
7520
7521     // Fold this by inserting a select from the input values.
7522     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7523                                        FI->getOperand(0), SI.getName()+".v");
7524     InsertNewInstBefore(NewSI, SI);
7525     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7526                             TI->getType());
7527   }
7528
7529   // Only handle binary operators here.
7530   if (!isa<BinaryOperator>(TI))
7531     return 0;
7532
7533   // Figure out if the operations have any operands in common.
7534   Value *MatchOp, *OtherOpT, *OtherOpF;
7535   bool MatchIsOpZero;
7536   if (TI->getOperand(0) == FI->getOperand(0)) {
7537     MatchOp  = TI->getOperand(0);
7538     OtherOpT = TI->getOperand(1);
7539     OtherOpF = FI->getOperand(1);
7540     MatchIsOpZero = true;
7541   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7542     MatchOp  = TI->getOperand(1);
7543     OtherOpT = TI->getOperand(0);
7544     OtherOpF = FI->getOperand(0);
7545     MatchIsOpZero = false;
7546   } else if (!TI->isCommutative()) {
7547     return 0;
7548   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7549     MatchOp  = TI->getOperand(0);
7550     OtherOpT = TI->getOperand(1);
7551     OtherOpF = FI->getOperand(0);
7552     MatchIsOpZero = true;
7553   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7554     MatchOp  = TI->getOperand(1);
7555     OtherOpT = TI->getOperand(0);
7556     OtherOpF = FI->getOperand(1);
7557     MatchIsOpZero = true;
7558   } else {
7559     return 0;
7560   }
7561
7562   // If we reach here, they do have operations in common.
7563   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7564                                      OtherOpF, SI.getName()+".v");
7565   InsertNewInstBefore(NewSI, SI);
7566
7567   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7568     if (MatchIsOpZero)
7569       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7570     else
7571       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7572   }
7573   assert(0 && "Shouldn't get here");
7574   return 0;
7575 }
7576
7577 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7578   Value *CondVal = SI.getCondition();
7579   Value *TrueVal = SI.getTrueValue();
7580   Value *FalseVal = SI.getFalseValue();
7581
7582   // select true, X, Y  -> X
7583   // select false, X, Y -> Y
7584   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7585     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7586
7587   // select C, X, X -> X
7588   if (TrueVal == FalseVal)
7589     return ReplaceInstUsesWith(SI, TrueVal);
7590
7591   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7592     return ReplaceInstUsesWith(SI, FalseVal);
7593   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7594     return ReplaceInstUsesWith(SI, TrueVal);
7595   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7596     if (isa<Constant>(TrueVal))
7597       return ReplaceInstUsesWith(SI, TrueVal);
7598     else
7599       return ReplaceInstUsesWith(SI, FalseVal);
7600   }
7601
7602   if (SI.getType() == Type::Int1Ty) {
7603     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7604       if (C->getZExtValue()) {
7605         // Change: A = select B, true, C --> A = or B, C
7606         return BinaryOperator::createOr(CondVal, FalseVal);
7607       } else {
7608         // Change: A = select B, false, C --> A = and !B, C
7609         Value *NotCond =
7610           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7611                                              "not."+CondVal->getName()), SI);
7612         return BinaryOperator::createAnd(NotCond, FalseVal);
7613       }
7614     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7615       if (C->getZExtValue() == false) {
7616         // Change: A = select B, C, false --> A = and B, C
7617         return BinaryOperator::createAnd(CondVal, TrueVal);
7618       } else {
7619         // Change: A = select B, C, true --> A = or !B, C
7620         Value *NotCond =
7621           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7622                                              "not."+CondVal->getName()), SI);
7623         return BinaryOperator::createOr(NotCond, TrueVal);
7624       }
7625     }
7626     
7627     // select a, b, a  -> a&b
7628     // select a, a, b  -> a|b
7629     if (CondVal == TrueVal)
7630       return BinaryOperator::createOr(CondVal, FalseVal);
7631     else if (CondVal == FalseVal)
7632       return BinaryOperator::createAnd(CondVal, TrueVal);
7633   }
7634
7635   // Selecting between two integer constants?
7636   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7637     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7638       // select C, 1, 0 -> zext C to int
7639       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7640         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7641       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7642         // select C, 0, 1 -> zext !C to int
7643         Value *NotCond =
7644           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7645                                                "not."+CondVal->getName()), SI);
7646         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7647       }
7648       
7649       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7650
7651       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7652
7653         // (x <s 0) ? -1 : 0 -> ashr x, 31
7654         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7655           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7656             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7657               // The comparison constant and the result are not neccessarily the
7658               // same width. Make an all-ones value by inserting a AShr.
7659               Value *X = IC->getOperand(0);
7660               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7661               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7662               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7663                                                         ShAmt, "ones");
7664               InsertNewInstBefore(SRA, SI);
7665               
7666               // Finally, convert to the type of the select RHS.  We figure out
7667               // if this requires a SExt, Trunc or BitCast based on the sizes.
7668               Instruction::CastOps opc = Instruction::BitCast;
7669               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7670               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
7671               if (SRASize < SISize)
7672                 opc = Instruction::SExt;
7673               else if (SRASize > SISize)
7674                 opc = Instruction::Trunc;
7675               return CastInst::create(opc, SRA, SI.getType());
7676             }
7677           }
7678
7679
7680         // If one of the constants is zero (we know they can't both be) and we
7681         // have an icmp instruction with zero, and we have an 'and' with the
7682         // non-constant value, eliminate this whole mess.  This corresponds to
7683         // cases like this: ((X & 27) ? 27 : 0)
7684         if (TrueValC->isZero() || FalseValC->isZero())
7685           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7686               cast<Constant>(IC->getOperand(1))->isNullValue())
7687             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7688               if (ICA->getOpcode() == Instruction::And &&
7689                   isa<ConstantInt>(ICA->getOperand(1)) &&
7690                   (ICA->getOperand(1) == TrueValC ||
7691                    ICA->getOperand(1) == FalseValC) &&
7692                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7693                 // Okay, now we know that everything is set up, we just don't
7694                 // know whether we have a icmp_ne or icmp_eq and whether the 
7695                 // true or false val is the zero.
7696                 bool ShouldNotVal = !TrueValC->isZero();
7697                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7698                 Value *V = ICA;
7699                 if (ShouldNotVal)
7700                   V = InsertNewInstBefore(BinaryOperator::create(
7701                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7702                 return ReplaceInstUsesWith(SI, V);
7703               }
7704       }
7705     }
7706
7707   // See if we are selecting two values based on a comparison of the two values.
7708   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7709     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7710       // Transform (X == Y) ? X : Y  -> Y
7711       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7712         // This is not safe in general for floating point:  
7713         // consider X== -0, Y== +0.
7714         // It becomes safe if either operand is a nonzero constant.
7715         ConstantFP *CFPt, *CFPf;
7716         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7717               !CFPt->getValueAPF().isZero()) ||
7718             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7719              !CFPf->getValueAPF().isZero()))
7720         return ReplaceInstUsesWith(SI, FalseVal);
7721       }
7722       // Transform (X != Y) ? X : Y  -> X
7723       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7724         return ReplaceInstUsesWith(SI, TrueVal);
7725       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7726
7727     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7728       // Transform (X == Y) ? Y : X  -> X
7729       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7730         // This is not safe in general for floating point:  
7731         // consider X== -0, Y== +0.
7732         // It becomes safe if either operand is a nonzero constant.
7733         ConstantFP *CFPt, *CFPf;
7734         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7735               !CFPt->getValueAPF().isZero()) ||
7736             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7737              !CFPf->getValueAPF().isZero()))
7738           return ReplaceInstUsesWith(SI, FalseVal);
7739       }
7740       // Transform (X != Y) ? Y : X  -> Y
7741       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7742         return ReplaceInstUsesWith(SI, TrueVal);
7743       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7744     }
7745   }
7746
7747   // See if we are selecting two values based on a comparison of the two values.
7748   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7749     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7750       // Transform (X == Y) ? X : Y  -> Y
7751       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7752         return ReplaceInstUsesWith(SI, FalseVal);
7753       // Transform (X != Y) ? X : Y  -> X
7754       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7755         return ReplaceInstUsesWith(SI, TrueVal);
7756       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7757
7758     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7759       // Transform (X == Y) ? Y : X  -> X
7760       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7761         return ReplaceInstUsesWith(SI, FalseVal);
7762       // Transform (X != Y) ? Y : X  -> Y
7763       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7764         return ReplaceInstUsesWith(SI, TrueVal);
7765       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7766     }
7767   }
7768
7769   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7770     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7771       if (TI->hasOneUse() && FI->hasOneUse()) {
7772         Instruction *AddOp = 0, *SubOp = 0;
7773
7774         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7775         if (TI->getOpcode() == FI->getOpcode())
7776           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7777             return IV;
7778
7779         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7780         // even legal for FP.
7781         if (TI->getOpcode() == Instruction::Sub &&
7782             FI->getOpcode() == Instruction::Add) {
7783           AddOp = FI; SubOp = TI;
7784         } else if (FI->getOpcode() == Instruction::Sub &&
7785                    TI->getOpcode() == Instruction::Add) {
7786           AddOp = TI; SubOp = FI;
7787         }
7788
7789         if (AddOp) {
7790           Value *OtherAddOp = 0;
7791           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7792             OtherAddOp = AddOp->getOperand(1);
7793           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7794             OtherAddOp = AddOp->getOperand(0);
7795           }
7796
7797           if (OtherAddOp) {
7798             // So at this point we know we have (Y -> OtherAddOp):
7799             //        select C, (add X, Y), (sub X, Z)
7800             Value *NegVal;  // Compute -Z
7801             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7802               NegVal = ConstantExpr::getNeg(C);
7803             } else {
7804               NegVal = InsertNewInstBefore(
7805                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7806             }
7807
7808             Value *NewTrueOp = OtherAddOp;
7809             Value *NewFalseOp = NegVal;
7810             if (AddOp != TI)
7811               std::swap(NewTrueOp, NewFalseOp);
7812             Instruction *NewSel =
7813               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7814
7815             NewSel = InsertNewInstBefore(NewSel, SI);
7816             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7817           }
7818         }
7819       }
7820
7821   // See if we can fold the select into one of our operands.
7822   if (SI.getType()->isInteger()) {
7823     // See the comment above GetSelectFoldableOperands for a description of the
7824     // transformation we are doing here.
7825     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7826       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7827           !isa<Constant>(FalseVal))
7828         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7829           unsigned OpToFold = 0;
7830           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7831             OpToFold = 1;
7832           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7833             OpToFold = 2;
7834           }
7835
7836           if (OpToFold) {
7837             Constant *C = GetSelectFoldableConstant(TVI);
7838             Instruction *NewSel =
7839               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7840             InsertNewInstBefore(NewSel, SI);
7841             NewSel->takeName(TVI);
7842             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7843               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7844             else {
7845               assert(0 && "Unknown instruction!!");
7846             }
7847           }
7848         }
7849
7850     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7851       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7852           !isa<Constant>(TrueVal))
7853         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7854           unsigned OpToFold = 0;
7855           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7856             OpToFold = 1;
7857           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7858             OpToFold = 2;
7859           }
7860
7861           if (OpToFold) {
7862             Constant *C = GetSelectFoldableConstant(FVI);
7863             Instruction *NewSel =
7864               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7865             InsertNewInstBefore(NewSel, SI);
7866             NewSel->takeName(FVI);
7867             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7868               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7869             else
7870               assert(0 && "Unknown instruction!!");
7871           }
7872         }
7873   }
7874
7875   if (BinaryOperator::isNot(CondVal)) {
7876     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7877     SI.setOperand(1, FalseVal);
7878     SI.setOperand(2, TrueVal);
7879     return &SI;
7880   }
7881
7882   return 0;
7883 }
7884
7885 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7886 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
7887 /// and it is more than the alignment of the ultimate object, see if we can
7888 /// increase the alignment of the ultimate object, making this check succeed.
7889 static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7890                                            unsigned PrefAlign = 0) {
7891   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7892     unsigned Align = GV->getAlignment();
7893     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
7894       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7895
7896     // If there is a large requested alignment and we can, bump up the alignment
7897     // of the global.
7898     if (PrefAlign > Align && GV->hasInitializer()) {
7899       GV->setAlignment(PrefAlign);
7900       Align = PrefAlign;
7901     }
7902     return Align;
7903   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7904     unsigned Align = AI->getAlignment();
7905     if (Align == 0 && TD) {
7906       if (isa<AllocaInst>(AI))
7907         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7908       else if (isa<MallocInst>(AI)) {
7909         // Malloc returns maximally aligned memory.
7910         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7911         Align =
7912           std::max(Align,
7913                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7914         Align =
7915           std::max(Align,
7916                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7917       }
7918     }
7919     
7920     // If there is a requested alignment and if this is an alloca, round up.  We
7921     // don't do this for malloc, because some systems can't respect the request.
7922     if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7923       AI->setAlignment(PrefAlign);
7924       Align = PrefAlign;
7925     }
7926     return Align;
7927   } else if (isa<BitCastInst>(V) ||
7928              (isa<ConstantExpr>(V) && 
7929               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7930     return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7931                                       TD, PrefAlign);
7932   } else if (User *GEPI = dyn_castGetElementPtr(V)) {
7933     // If all indexes are zero, it is just the alignment of the base pointer.
7934     bool AllZeroOperands = true;
7935     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7936       if (!isa<Constant>(GEPI->getOperand(i)) ||
7937           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7938         AllZeroOperands = false;
7939         break;
7940       }
7941
7942     if (AllZeroOperands) {
7943       // Treat this like a bitcast.
7944       return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7945     }
7946
7947     unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7948     if (BaseAlignment == 0) return 0;
7949
7950     // Otherwise, if the base alignment is >= the alignment we expect for the
7951     // base pointer type, then we know that the resultant pointer is aligned at
7952     // least as much as its type requires.
7953     if (!TD) return 0;
7954
7955     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7956     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7957     unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7958     if (Align <= BaseAlignment) {
7959       const Type *GEPTy = GEPI->getType();
7960       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7961       Align = std::min(Align, (unsigned)
7962                        TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7963       return Align;
7964     }
7965     return 0;
7966   }
7967   return 0;
7968 }
7969
7970 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7971   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7972   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7973   unsigned MinAlign = std::min(DstAlign, SrcAlign);
7974   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
7975
7976   if (CopyAlign < MinAlign) {
7977     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
7978     return MI;
7979   }
7980   
7981   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7982   // load/store.
7983   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
7984   if (MemOpLength == 0) return 0;
7985   
7986   // Source and destination pointer types are always "i8*" for intrinsic.  See
7987   // if the size is something we can handle with a single primitive load/store.
7988   // A single load+store correctly handles overlapping memory in the memmove
7989   // case.
7990   unsigned Size = MemOpLength->getZExtValue();
7991   if (Size == 0 || Size > 8 || (Size&(Size-1)))
7992     return 0;  // If not 1/2/4/8 bytes, exit.
7993   
7994   // Use an integer load+store unless we can find something better.
7995   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
7996   
7997   // Memcpy forces the use of i8* for the source and destination.  That means
7998   // that if you're using memcpy to move one double around, you'll get a cast
7999   // from double* to i8*.  We'd much rather use a double load+store rather than
8000   // an i64 load+store, here because this improves the odds that the source or
8001   // dest address will be promotable.  See if we can find a better type than the
8002   // integer datatype.
8003   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8004     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8005     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8006       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8007       // down through these levels if so.
8008       while (!SrcETy->isFirstClassType()) {
8009         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8010           if (STy->getNumElements() == 1)
8011             SrcETy = STy->getElementType(0);
8012           else
8013             break;
8014         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8015           if (ATy->getNumElements() == 1)
8016             SrcETy = ATy->getElementType();
8017           else
8018             break;
8019         } else
8020           break;
8021       }
8022       
8023       if (SrcETy->isFirstClassType())
8024         NewPtrTy = PointerType::getUnqual(SrcETy);
8025     }
8026   }
8027   
8028   
8029   // If the memcpy/memmove provides better alignment info than we can
8030   // infer, use it.
8031   SrcAlign = std::max(SrcAlign, CopyAlign);
8032   DstAlign = std::max(DstAlign, CopyAlign);
8033   
8034   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8035   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8036   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8037   InsertNewInstBefore(L, *MI);
8038   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8039
8040   // Set the size of the copy to 0, it will be deleted on the next iteration.
8041   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8042   return MI;
8043 }
8044
8045 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8046 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8047 /// the heavy lifting.
8048 ///
8049 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8050   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8051   if (!II) return visitCallSite(&CI);
8052   
8053   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8054   // visitCallSite.
8055   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8056     bool Changed = false;
8057
8058     // memmove/cpy/set of zero bytes is a noop.
8059     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8060       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8061
8062       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8063         if (CI->getZExtValue() == 1) {
8064           // Replace the instruction with just byte operations.  We would
8065           // transform other cases to loads/stores, but we don't know if
8066           // alignment is sufficient.
8067         }
8068     }
8069
8070     // If we have a memmove and the source operation is a constant global,
8071     // then the source and dest pointers can't alias, so we can change this
8072     // into a call to memcpy.
8073     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8074       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8075         if (GVSrc->isConstant()) {
8076           Module *M = CI.getParent()->getParent()->getParent();
8077           Intrinsic::ID MemCpyID;
8078           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8079             MemCpyID = Intrinsic::memcpy_i32;
8080           else
8081             MemCpyID = Intrinsic::memcpy_i64;
8082           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8083           Changed = true;
8084         }
8085     }
8086
8087     // If we can determine a pointer alignment that is bigger than currently
8088     // set, update the alignment.
8089     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8090       if (Instruction *I = SimplifyMemTransfer(MI))
8091         return I;
8092     } else if (isa<MemSetInst>(MI)) {
8093       unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
8094       if (MI->getAlignment()->getZExtValue() < Alignment) {
8095         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8096         Changed = true;
8097       }
8098     }
8099           
8100     if (Changed) return II;
8101   } else {
8102     switch (II->getIntrinsicID()) {
8103     default: break;
8104     case Intrinsic::ppc_altivec_lvx:
8105     case Intrinsic::ppc_altivec_lvxl:
8106     case Intrinsic::x86_sse_loadu_ps:
8107     case Intrinsic::x86_sse2_loadu_pd:
8108     case Intrinsic::x86_sse2_loadu_dq:
8109       // Turn PPC lvx     -> load if the pointer is known aligned.
8110       // Turn X86 loadups -> load if the pointer is known aligned.
8111       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8112         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8113                                          PointerType::getUnqual(II->getType()),
8114                                          CI);
8115         return new LoadInst(Ptr);
8116       }
8117       break;
8118     case Intrinsic::ppc_altivec_stvx:
8119     case Intrinsic::ppc_altivec_stvxl:
8120       // Turn stvx -> store if the pointer is known aligned.
8121       if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
8122         const Type *OpPtrTy = 
8123           PointerType::getUnqual(II->getOperand(1)->getType());
8124         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8125         return new StoreInst(II->getOperand(1), Ptr);
8126       }
8127       break;
8128     case Intrinsic::x86_sse_storeu_ps:
8129     case Intrinsic::x86_sse2_storeu_pd:
8130     case Intrinsic::x86_sse2_storeu_dq:
8131     case Intrinsic::x86_sse2_storel_dq:
8132       // Turn X86 storeu -> store if the pointer is known aligned.
8133       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8134         const Type *OpPtrTy = 
8135           PointerType::getUnqual(II->getOperand(2)->getType());
8136         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8137         return new StoreInst(II->getOperand(2), Ptr);
8138       }
8139       break;
8140       
8141     case Intrinsic::x86_sse_cvttss2si: {
8142       // These intrinsics only demands the 0th element of its input vector.  If
8143       // we can simplify the input based on that, do so now.
8144       uint64_t UndefElts;
8145       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8146                                                 UndefElts)) {
8147         II->setOperand(1, V);
8148         return II;
8149       }
8150       break;
8151     }
8152       
8153     case Intrinsic::ppc_altivec_vperm:
8154       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8155       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8156         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8157         
8158         // Check that all of the elements are integer constants or undefs.
8159         bool AllEltsOk = true;
8160         for (unsigned i = 0; i != 16; ++i) {
8161           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8162               !isa<UndefValue>(Mask->getOperand(i))) {
8163             AllEltsOk = false;
8164             break;
8165           }
8166         }
8167         
8168         if (AllEltsOk) {
8169           // Cast the input vectors to byte vectors.
8170           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8171           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8172           Value *Result = UndefValue::get(Op0->getType());
8173           
8174           // Only extract each element once.
8175           Value *ExtractedElts[32];
8176           memset(ExtractedElts, 0, sizeof(ExtractedElts));
8177           
8178           for (unsigned i = 0; i != 16; ++i) {
8179             if (isa<UndefValue>(Mask->getOperand(i)))
8180               continue;
8181             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8182             Idx &= 31;  // Match the hardware behavior.
8183             
8184             if (ExtractedElts[Idx] == 0) {
8185               Instruction *Elt = 
8186                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8187               InsertNewInstBefore(Elt, CI);
8188               ExtractedElts[Idx] = Elt;
8189             }
8190           
8191             // Insert this value into the result vector.
8192             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8193             InsertNewInstBefore(cast<Instruction>(Result), CI);
8194           }
8195           return CastInst::create(Instruction::BitCast, Result, CI.getType());
8196         }
8197       }
8198       break;
8199
8200     case Intrinsic::stackrestore: {
8201       // If the save is right next to the restore, remove the restore.  This can
8202       // happen when variable allocas are DCE'd.
8203       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8204         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8205           BasicBlock::iterator BI = SS;
8206           if (&*++BI == II)
8207             return EraseInstFromFunction(CI);
8208         }
8209       }
8210       
8211       // If the stack restore is in a return/unwind block and if there are no
8212       // allocas or calls between the restore and the return, nuke the restore.
8213       TerminatorInst *TI = II->getParent()->getTerminator();
8214       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8215         BasicBlock::iterator BI = II;
8216         bool CannotRemove = false;
8217         for (++BI; &*BI != TI; ++BI) {
8218           if (isa<AllocaInst>(BI) ||
8219               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8220             CannotRemove = true;
8221             break;
8222           }
8223         }
8224         if (!CannotRemove)
8225           return EraseInstFromFunction(CI);
8226       }
8227       break;
8228     }
8229     }
8230   }
8231
8232   return visitCallSite(II);
8233 }
8234
8235 // InvokeInst simplification
8236 //
8237 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8238   return visitCallSite(&II);
8239 }
8240
8241 // visitCallSite - Improvements for call and invoke instructions.
8242 //
8243 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8244   bool Changed = false;
8245
8246   // If the callee is a constexpr cast of a function, attempt to move the cast
8247   // to the arguments of the call/invoke.
8248   if (transformConstExprCastCall(CS)) return 0;
8249
8250   Value *Callee = CS.getCalledValue();
8251
8252   if (Function *CalleeF = dyn_cast<Function>(Callee))
8253     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8254       Instruction *OldCall = CS.getInstruction();
8255       // If the call and callee calling conventions don't match, this call must
8256       // be unreachable, as the call is undefined.
8257       new StoreInst(ConstantInt::getTrue(),
8258                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8259                                     OldCall);
8260       if (!OldCall->use_empty())
8261         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8262       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8263         return EraseInstFromFunction(*OldCall);
8264       return 0;
8265     }
8266
8267   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8268     // This instruction is not reachable, just remove it.  We insert a store to
8269     // undef so that we know that this code is not reachable, despite the fact
8270     // that we can't modify the CFG here.
8271     new StoreInst(ConstantInt::getTrue(),
8272                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8273                   CS.getInstruction());
8274
8275     if (!CS.getInstruction()->use_empty())
8276       CS.getInstruction()->
8277         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8278
8279     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8280       // Don't break the CFG, insert a dummy cond branch.
8281       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8282                      ConstantInt::getTrue(), II);
8283     }
8284     return EraseInstFromFunction(*CS.getInstruction());
8285   }
8286
8287   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8288     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8289       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8290         return transformCallThroughTrampoline(CS);
8291
8292   const PointerType *PTy = cast<PointerType>(Callee->getType());
8293   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8294   if (FTy->isVarArg()) {
8295     // See if we can optimize any arguments passed through the varargs area of
8296     // the call.
8297     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8298            E = CS.arg_end(); I != E; ++I)
8299       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8300         // If this cast does not effect the value passed through the varargs
8301         // area, we can eliminate the use of the cast.
8302         Value *Op = CI->getOperand(0);
8303         if (CI->isLosslessCast()) {
8304           *I = Op;
8305           Changed = true;
8306         }
8307       }
8308   }
8309
8310   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8311     // Inline asm calls cannot throw - mark them 'nounwind'.
8312     CS.setDoesNotThrow();
8313     Changed = true;
8314   }
8315
8316   return Changed ? CS.getInstruction() : 0;
8317 }
8318
8319 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8320 // attempt to move the cast to the arguments of the call/invoke.
8321 //
8322 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8323   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8324   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8325   if (CE->getOpcode() != Instruction::BitCast || 
8326       !isa<Function>(CE->getOperand(0)))
8327     return false;
8328   Function *Callee = cast<Function>(CE->getOperand(0));
8329   Instruction *Caller = CS.getInstruction();
8330   const ParamAttrsList* CallerPAL = CS.getParamAttrs();
8331
8332   // Okay, this is a cast from a function to a different type.  Unless doing so
8333   // would cause a type conversion of one of our arguments, change this call to
8334   // be a direct call with arguments casted to the appropriate types.
8335   //
8336   const FunctionType *FT = Callee->getFunctionType();
8337   const Type *OldRetTy = Caller->getType();
8338
8339   // Check to see if we are changing the return type...
8340   if (OldRetTy != FT->getReturnType()) {
8341     if (Callee->isDeclaration() && !Caller->use_empty() && 
8342         // Conversion is ok if changing from pointer to int of same size.
8343         !(isa<PointerType>(FT->getReturnType()) &&
8344           TD->getIntPtrType() == OldRetTy))
8345       return false;   // Cannot transform this return value.
8346
8347     if (!Caller->use_empty() &&
8348         // void -> non-void is handled specially
8349         FT->getReturnType() != Type::VoidTy &&
8350         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
8351       return false;   // Cannot transform this return value.
8352
8353     if (CallerPAL && !Caller->use_empty()) {
8354       uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8355       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8356         return false;   // Attribute not compatible with transformed value.
8357     }
8358
8359     // If the callsite is an invoke instruction, and the return value is used by
8360     // a PHI node in a successor, we cannot change the return type of the call
8361     // because there is no place to put the cast instruction (without breaking
8362     // the critical edge).  Bail out in this case.
8363     if (!Caller->use_empty())
8364       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8365         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8366              UI != E; ++UI)
8367           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8368             if (PN->getParent() == II->getNormalDest() ||
8369                 PN->getParent() == II->getUnwindDest())
8370               return false;
8371   }
8372
8373   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8374   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8375
8376   CallSite::arg_iterator AI = CS.arg_begin();
8377   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8378     const Type *ParamTy = FT->getParamType(i);
8379     const Type *ActTy = (*AI)->getType();
8380
8381     if (!CastInst::isCastable(ActTy, ParamTy))
8382       return false;   // Cannot transform this parameter value.
8383
8384     if (CallerPAL) {
8385       uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8386       if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8387         return false;   // Attribute not compatible with transformed value.
8388     }
8389
8390     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8391     // Some conversions are safe even if we do not have a body.
8392     // Either we can cast directly, or we can upconvert the argument
8393     bool isConvertible = ActTy == ParamTy ||
8394       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8395       (ParamTy->isInteger() && ActTy->isInteger() &&
8396        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8397       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8398        && c->getValue().isStrictlyPositive());
8399     if (Callee->isDeclaration() && !isConvertible) return false;
8400   }
8401
8402   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8403       Callee->isDeclaration())
8404     return false;   // Do not delete arguments unless we have a function body...
8405
8406   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
8407     // In this case we have more arguments than the new function type, but we
8408     // won't be dropping them.  Check that these extra arguments have attributes
8409     // that are compatible with being a vararg call argument.
8410     for (unsigned i = CallerPAL->size(); i; --i) {
8411       if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8412         break;
8413       uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8414       if (PAttrs & ParamAttr::VarArgsIncompatible)
8415         return false;
8416     }
8417
8418   // Okay, we decided that this is a safe thing to do: go ahead and start
8419   // inserting cast instructions as necessary...
8420   std::vector<Value*> Args;
8421   Args.reserve(NumActualArgs);
8422   ParamAttrsVector attrVec;
8423   attrVec.reserve(NumCommonArgs);
8424
8425   // Get any return attributes.
8426   uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8427
8428   // If the return value is not being used, the type may not be compatible
8429   // with the existing attributes.  Wipe out any problematic attributes.
8430   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
8431
8432   // Add the new return attributes.
8433   if (RAttrs)
8434     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8435
8436   AI = CS.arg_begin();
8437   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8438     const Type *ParamTy = FT->getParamType(i);
8439     if ((*AI)->getType() == ParamTy) {
8440       Args.push_back(*AI);
8441     } else {
8442       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8443           false, ParamTy, false);
8444       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8445       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8446     }
8447
8448     // Add any parameter attributes.
8449     uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8450     if (PAttrs)
8451       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8452   }
8453
8454   // If the function takes more arguments than the call was taking, add them
8455   // now...
8456   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8457     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8458
8459   // If we are removing arguments to the function, emit an obnoxious warning...
8460   if (FT->getNumParams() < NumActualArgs)
8461     if (!FT->isVarArg()) {
8462       cerr << "WARNING: While resolving call to function '"
8463            << Callee->getName() << "' arguments were dropped!\n";
8464     } else {
8465       // Add all of the arguments in their promoted form to the arg list...
8466       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8467         const Type *PTy = getPromotedType((*AI)->getType());
8468         if (PTy != (*AI)->getType()) {
8469           // Must promote to pass through va_arg area!
8470           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8471                                                                 PTy, false);
8472           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8473           InsertNewInstBefore(Cast, *Caller);
8474           Args.push_back(Cast);
8475         } else {
8476           Args.push_back(*AI);
8477         }
8478
8479         // Add any parameter attributes.
8480         uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8481         if (PAttrs)
8482           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8483       }
8484     }
8485
8486   if (FT->getReturnType() == Type::VoidTy)
8487     Caller->setName("");   // Void type should not have a name.
8488
8489   const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8490
8491   Instruction *NC;
8492   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8493     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8494                         Args.begin(), Args.end(), Caller->getName(), Caller);
8495     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8496     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
8497   } else {
8498     NC = new CallInst(Callee, Args.begin(), Args.end(),
8499                       Caller->getName(), Caller);
8500     CallInst *CI = cast<CallInst>(Caller);
8501     if (CI->isTailCall())
8502       cast<CallInst>(NC)->setTailCall();
8503     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8504     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
8505   }
8506
8507   // Insert a cast of the return type as necessary.
8508   Value *NV = NC;
8509   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
8510     if (NV->getType() != Type::VoidTy) {
8511       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8512                                                             OldRetTy, false);
8513       NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
8514
8515       // If this is an invoke instruction, we should insert it after the first
8516       // non-phi, instruction in the normal successor block.
8517       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8518         BasicBlock::iterator I = II->getNormalDest()->begin();
8519         while (isa<PHINode>(I)) ++I;
8520         InsertNewInstBefore(NC, *I);
8521       } else {
8522         // Otherwise, it's a call, just insert cast right after the call instr
8523         InsertNewInstBefore(NC, *Caller);
8524       }
8525       AddUsersToWorkList(*Caller);
8526     } else {
8527       NV = UndefValue::get(Caller->getType());
8528     }
8529   }
8530
8531   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8532     Caller->replaceAllUsesWith(NV);
8533   Caller->eraseFromParent();
8534   RemoveFromWorkList(Caller);
8535   return true;
8536 }
8537
8538 // transformCallThroughTrampoline - Turn a call to a function created by the
8539 // init_trampoline intrinsic into a direct call to the underlying function.
8540 //
8541 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8542   Value *Callee = CS.getCalledValue();
8543   const PointerType *PTy = cast<PointerType>(Callee->getType());
8544   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8545   const ParamAttrsList *Attrs = CS.getParamAttrs();
8546
8547   // If the call already has the 'nest' attribute somewhere then give up -
8548   // otherwise 'nest' would occur twice after splicing in the chain.
8549   if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8550     return 0;
8551
8552   IntrinsicInst *Tramp =
8553     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8554
8555   Function *NestF =
8556     cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8557   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8558   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8559
8560   if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
8561     unsigned NestIdx = 1;
8562     const Type *NestTy = 0;
8563     uint16_t NestAttr = 0;
8564
8565     // Look for a parameter marked with the 'nest' attribute.
8566     for (FunctionType::param_iterator I = NestFTy->param_begin(),
8567          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8568       if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8569         // Record the parameter type and any other attributes.
8570         NestTy = *I;
8571         NestAttr = NestAttrs->getParamAttrs(NestIdx);
8572         break;
8573       }
8574
8575     if (NestTy) {
8576       Instruction *Caller = CS.getInstruction();
8577       std::vector<Value*> NewArgs;
8578       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8579
8580       ParamAttrsVector NewAttrs;
8581       NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8582
8583       // Insert the nest argument into the call argument list, which may
8584       // mean appending it.  Likewise for attributes.
8585
8586       // Add any function result attributes.
8587       uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8588       if (Attr)
8589         NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8590
8591       {
8592         unsigned Idx = 1;
8593         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8594         do {
8595           if (Idx == NestIdx) {
8596             // Add the chain argument and attributes.
8597             Value *NestVal = Tramp->getOperand(3);
8598             if (NestVal->getType() != NestTy)
8599               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8600             NewArgs.push_back(NestVal);
8601             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8602           }
8603
8604           if (I == E)
8605             break;
8606
8607           // Add the original argument and attributes.
8608           NewArgs.push_back(*I);
8609           Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8610           if (Attr)
8611             NewAttrs.push_back
8612               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8613
8614           ++Idx, ++I;
8615         } while (1);
8616       }
8617
8618       // The trampoline may have been bitcast to a bogus type (FTy).
8619       // Handle this by synthesizing a new function type, equal to FTy
8620       // with the chain parameter inserted.
8621
8622       std::vector<const Type*> NewTypes;
8623       NewTypes.reserve(FTy->getNumParams()+1);
8624
8625       // Insert the chain's type into the list of parameter types, which may
8626       // mean appending it.
8627       {
8628         unsigned Idx = 1;
8629         FunctionType::param_iterator I = FTy->param_begin(),
8630           E = FTy->param_end();
8631
8632         do {
8633           if (Idx == NestIdx)
8634             // Add the chain's type.
8635             NewTypes.push_back(NestTy);
8636
8637           if (I == E)
8638             break;
8639
8640           // Add the original type.
8641           NewTypes.push_back(*I);
8642
8643           ++Idx, ++I;
8644         } while (1);
8645       }
8646
8647       // Replace the trampoline call with a direct call.  Let the generic
8648       // code sort out any function type mismatches.
8649       FunctionType *NewFTy =
8650         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
8651       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8652         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
8653       const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
8654
8655       Instruction *NewCaller;
8656       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8657         NewCaller = new InvokeInst(NewCallee,
8658                                    II->getNormalDest(), II->getUnwindDest(),
8659                                    NewArgs.begin(), NewArgs.end(),
8660                                    Caller->getName(), Caller);
8661         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
8662         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
8663       } else {
8664         NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8665                                  Caller->getName(), Caller);
8666         if (cast<CallInst>(Caller)->isTailCall())
8667           cast<CallInst>(NewCaller)->setTailCall();
8668         cast<CallInst>(NewCaller)->
8669           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8670         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
8671       }
8672       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8673         Caller->replaceAllUsesWith(NewCaller);
8674       Caller->eraseFromParent();
8675       RemoveFromWorkList(Caller);
8676       return 0;
8677     }
8678   }
8679
8680   // Replace the trampoline call with a direct call.  Since there is no 'nest'
8681   // parameter, there is no need to adjust the argument list.  Let the generic
8682   // code sort out any function type mismatches.
8683   Constant *NewCallee =
8684     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8685   CS.setCalledFunction(NewCallee);
8686   return CS.getInstruction();
8687 }
8688
8689 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8690 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8691 /// and a single binop.
8692 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8693   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8694   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8695          isa<CmpInst>(FirstInst));
8696   unsigned Opc = FirstInst->getOpcode();
8697   Value *LHSVal = FirstInst->getOperand(0);
8698   Value *RHSVal = FirstInst->getOperand(1);
8699     
8700   const Type *LHSType = LHSVal->getType();
8701   const Type *RHSType = RHSVal->getType();
8702   
8703   // Scan to see if all operands are the same opcode, all have one use, and all
8704   // kill their operands (i.e. the operands have one use).
8705   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8706     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8707     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8708         // Verify type of the LHS matches so we don't fold cmp's of different
8709         // types or GEP's with different index types.
8710         I->getOperand(0)->getType() != LHSType ||
8711         I->getOperand(1)->getType() != RHSType)
8712       return 0;
8713
8714     // If they are CmpInst instructions, check their predicates
8715     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8716       if (cast<CmpInst>(I)->getPredicate() !=
8717           cast<CmpInst>(FirstInst)->getPredicate())
8718         return 0;
8719     
8720     // Keep track of which operand needs a phi node.
8721     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8722     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8723   }
8724   
8725   // Otherwise, this is safe to transform, determine if it is profitable.
8726
8727   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8728   // Indexes are often folded into load/store instructions, so we don't want to
8729   // hide them behind a phi.
8730   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8731     return 0;
8732   
8733   Value *InLHS = FirstInst->getOperand(0);
8734   Value *InRHS = FirstInst->getOperand(1);
8735   PHINode *NewLHS = 0, *NewRHS = 0;
8736   if (LHSVal == 0) {
8737     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8738     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8739     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8740     InsertNewInstBefore(NewLHS, PN);
8741     LHSVal = NewLHS;
8742   }
8743   
8744   if (RHSVal == 0) {
8745     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8746     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8747     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8748     InsertNewInstBefore(NewRHS, PN);
8749     RHSVal = NewRHS;
8750   }
8751   
8752   // Add all operands to the new PHIs.
8753   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8754     if (NewLHS) {
8755       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8756       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8757     }
8758     if (NewRHS) {
8759       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8760       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8761     }
8762   }
8763     
8764   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8765     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8766   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8767     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8768                            RHSVal);
8769   else {
8770     assert(isa<GetElementPtrInst>(FirstInst));
8771     return new GetElementPtrInst(LHSVal, RHSVal);
8772   }
8773 }
8774
8775 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8776 /// of the block that defines it.  This means that it must be obvious the value
8777 /// of the load is not changed from the point of the load to the end of the
8778 /// block it is in.
8779 ///
8780 /// Finally, it is safe, but not profitable, to sink a load targetting a
8781 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8782 /// to a register.
8783 static bool isSafeToSinkLoad(LoadInst *L) {
8784   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8785   
8786   for (++BBI; BBI != E; ++BBI)
8787     if (BBI->mayWriteToMemory())
8788       return false;
8789   
8790   // Check for non-address taken alloca.  If not address-taken already, it isn't
8791   // profitable to do this xform.
8792   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8793     bool isAddressTaken = false;
8794     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8795          UI != E; ++UI) {
8796       if (isa<LoadInst>(UI)) continue;
8797       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8798         // If storing TO the alloca, then the address isn't taken.
8799         if (SI->getOperand(1) == AI) continue;
8800       }
8801       isAddressTaken = true;
8802       break;
8803     }
8804     
8805     if (!isAddressTaken)
8806       return false;
8807   }
8808   
8809   return true;
8810 }
8811
8812
8813 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8814 // operator and they all are only used by the PHI, PHI together their
8815 // inputs, and do the operation once, to the result of the PHI.
8816 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8817   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8818
8819   // Scan the instruction, looking for input operations that can be folded away.
8820   // If all input operands to the phi are the same instruction (e.g. a cast from
8821   // the same type or "+42") we can pull the operation through the PHI, reducing
8822   // code size and simplifying code.
8823   Constant *ConstantOp = 0;
8824   const Type *CastSrcTy = 0;
8825   bool isVolatile = false;
8826   if (isa<CastInst>(FirstInst)) {
8827     CastSrcTy = FirstInst->getOperand(0)->getType();
8828   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8829     // Can fold binop, compare or shift here if the RHS is a constant, 
8830     // otherwise call FoldPHIArgBinOpIntoPHI.
8831     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8832     if (ConstantOp == 0)
8833       return FoldPHIArgBinOpIntoPHI(PN);
8834   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8835     isVolatile = LI->isVolatile();
8836     // We can't sink the load if the loaded value could be modified between the
8837     // load and the PHI.
8838     if (LI->getParent() != PN.getIncomingBlock(0) ||
8839         !isSafeToSinkLoad(LI))
8840       return 0;
8841   } else if (isa<GetElementPtrInst>(FirstInst)) {
8842     if (FirstInst->getNumOperands() == 2)
8843       return FoldPHIArgBinOpIntoPHI(PN);
8844     // Can't handle general GEPs yet.
8845     return 0;
8846   } else {
8847     return 0;  // Cannot fold this operation.
8848   }
8849
8850   // Check to see if all arguments are the same operation.
8851   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8852     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8853     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8854     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8855       return 0;
8856     if (CastSrcTy) {
8857       if (I->getOperand(0)->getType() != CastSrcTy)
8858         return 0;  // Cast operation must match.
8859     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8860       // We can't sink the load if the loaded value could be modified between 
8861       // the load and the PHI.
8862       if (LI->isVolatile() != isVolatile ||
8863           LI->getParent() != PN.getIncomingBlock(i) ||
8864           !isSafeToSinkLoad(LI))
8865         return 0;
8866     } else if (I->getOperand(1) != ConstantOp) {
8867       return 0;
8868     }
8869   }
8870
8871   // Okay, they are all the same operation.  Create a new PHI node of the
8872   // correct type, and PHI together all of the LHS's of the instructions.
8873   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8874                                PN.getName()+".in");
8875   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8876
8877   Value *InVal = FirstInst->getOperand(0);
8878   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8879
8880   // Add all operands to the new PHI.
8881   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8882     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8883     if (NewInVal != InVal)
8884       InVal = 0;
8885     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8886   }
8887
8888   Value *PhiVal;
8889   if (InVal) {
8890     // The new PHI unions all of the same values together.  This is really
8891     // common, so we handle it intelligently here for compile-time speed.
8892     PhiVal = InVal;
8893     delete NewPN;
8894   } else {
8895     InsertNewInstBefore(NewPN, PN);
8896     PhiVal = NewPN;
8897   }
8898
8899   // Insert and return the new operation.
8900   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8901     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8902   else if (isa<LoadInst>(FirstInst))
8903     return new LoadInst(PhiVal, "", isVolatile);
8904   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8905     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8906   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8907     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8908                            PhiVal, ConstantOp);
8909   else
8910     assert(0 && "Unknown operation");
8911   return 0;
8912 }
8913
8914 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8915 /// that is dead.
8916 static bool DeadPHICycle(PHINode *PN,
8917                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8918   if (PN->use_empty()) return true;
8919   if (!PN->hasOneUse()) return false;
8920
8921   // Remember this node, and if we find the cycle, return.
8922   if (!PotentiallyDeadPHIs.insert(PN))
8923     return true;
8924   
8925   // Don't scan crazily complex things.
8926   if (PotentiallyDeadPHIs.size() == 16)
8927     return false;
8928
8929   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8930     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8931
8932   return false;
8933 }
8934
8935 /// PHIsEqualValue - Return true if this phi node is always equal to
8936 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
8937 ///   z = some value; x = phi (y, z); y = phi (x, z)
8938 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
8939                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8940   // See if we already saw this PHI node.
8941   if (!ValueEqualPHIs.insert(PN))
8942     return true;
8943   
8944   // Don't scan crazily complex things.
8945   if (ValueEqualPHIs.size() == 16)
8946     return false;
8947  
8948   // Scan the operands to see if they are either phi nodes or are equal to
8949   // the value.
8950   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8951     Value *Op = PN->getIncomingValue(i);
8952     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8953       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8954         return false;
8955     } else if (Op != NonPhiInVal)
8956       return false;
8957   }
8958   
8959   return true;
8960 }
8961
8962
8963 // PHINode simplification
8964 //
8965 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8966   // If LCSSA is around, don't mess with Phi nodes
8967   if (MustPreserveLCSSA) return 0;
8968   
8969   if (Value *V = PN.hasConstantValue())
8970     return ReplaceInstUsesWith(PN, V);
8971
8972   // If all PHI operands are the same operation, pull them through the PHI,
8973   // reducing code size.
8974   if (isa<Instruction>(PN.getIncomingValue(0)) &&
8975       PN.getIncomingValue(0)->hasOneUse())
8976     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8977       return Result;
8978
8979   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
8980   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8981   // PHI)... break the cycle.
8982   if (PN.hasOneUse()) {
8983     Instruction *PHIUser = cast<Instruction>(PN.use_back());
8984     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8985       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8986       PotentiallyDeadPHIs.insert(&PN);
8987       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8988         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8989     }
8990    
8991     // If this phi has a single use, and if that use just computes a value for
8992     // the next iteration of a loop, delete the phi.  This occurs with unused
8993     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
8994     // common case here is good because the only other things that catch this
8995     // are induction variable analysis (sometimes) and ADCE, which is only run
8996     // late.
8997     if (PHIUser->hasOneUse() &&
8998         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8999         PHIUser->use_back() == &PN) {
9000       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9001     }
9002   }
9003
9004   // We sometimes end up with phi cycles that non-obviously end up being the
9005   // same value, for example:
9006   //   z = some value; x = phi (y, z); y = phi (x, z)
9007   // where the phi nodes don't necessarily need to be in the same block.  Do a
9008   // quick check to see if the PHI node only contains a single non-phi value, if
9009   // so, scan to see if the phi cycle is actually equal to that value.
9010   {
9011     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9012     // Scan for the first non-phi operand.
9013     while (InValNo != NumOperandVals && 
9014            isa<PHINode>(PN.getIncomingValue(InValNo)))
9015       ++InValNo;
9016
9017     if (InValNo != NumOperandVals) {
9018       Value *NonPhiInVal = PN.getOperand(InValNo);
9019       
9020       // Scan the rest of the operands to see if there are any conflicts, if so
9021       // there is no need to recursively scan other phis.
9022       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9023         Value *OpVal = PN.getIncomingValue(InValNo);
9024         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9025           break;
9026       }
9027       
9028       // If we scanned over all operands, then we have one unique value plus
9029       // phi values.  Scan PHI nodes to see if they all merge in each other or
9030       // the value.
9031       if (InValNo == NumOperandVals) {
9032         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9033         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9034           return ReplaceInstUsesWith(PN, NonPhiInVal);
9035       }
9036     }
9037   }
9038   return 0;
9039 }
9040
9041 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9042                                    Instruction *InsertPoint,
9043                                    InstCombiner *IC) {
9044   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9045   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9046   // We must cast correctly to the pointer type. Ensure that we
9047   // sign extend the integer value if it is smaller as this is
9048   // used for address computation.
9049   Instruction::CastOps opcode = 
9050      (VTySize < PtrSize ? Instruction::SExt :
9051       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9052   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9053 }
9054
9055
9056 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9057   Value *PtrOp = GEP.getOperand(0);
9058   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9059   // If so, eliminate the noop.
9060   if (GEP.getNumOperands() == 1)
9061     return ReplaceInstUsesWith(GEP, PtrOp);
9062
9063   if (isa<UndefValue>(GEP.getOperand(0)))
9064     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9065
9066   bool HasZeroPointerIndex = false;
9067   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9068     HasZeroPointerIndex = C->isNullValue();
9069
9070   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9071     return ReplaceInstUsesWith(GEP, PtrOp);
9072
9073   // Eliminate unneeded casts for indices.
9074   bool MadeChange = false;
9075   
9076   gep_type_iterator GTI = gep_type_begin(GEP);
9077   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9078     if (isa<SequentialType>(*GTI)) {
9079       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9080         if (CI->getOpcode() == Instruction::ZExt ||
9081             CI->getOpcode() == Instruction::SExt) {
9082           const Type *SrcTy = CI->getOperand(0)->getType();
9083           // We can eliminate a cast from i32 to i64 iff the target 
9084           // is a 32-bit pointer target.
9085           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9086             MadeChange = true;
9087             GEP.setOperand(i, CI->getOperand(0));
9088           }
9089         }
9090       }
9091       // If we are using a wider index than needed for this platform, shrink it
9092       // to what we need.  If the incoming value needs a cast instruction,
9093       // insert it.  This explicit cast can make subsequent optimizations more
9094       // obvious.
9095       Value *Op = GEP.getOperand(i);
9096       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
9097         if (Constant *C = dyn_cast<Constant>(Op)) {
9098           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9099           MadeChange = true;
9100         } else {
9101           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9102                                 GEP);
9103           GEP.setOperand(i, Op);
9104           MadeChange = true;
9105         }
9106     }
9107   }
9108   if (MadeChange) return &GEP;
9109
9110   // If this GEP instruction doesn't move the pointer, and if the input operand
9111   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9112   // real input to the dest type.
9113   if (GEP.hasAllZeroIndices()) {
9114     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9115       // If the bitcast is of an allocation, and the allocation will be
9116       // converted to match the type of the cast, don't touch this.
9117       if (isa<AllocationInst>(BCI->getOperand(0))) {
9118         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9119         if (Instruction *I = visitBitCast(*BCI)) {
9120           if (I != BCI) {
9121             I->takeName(BCI);
9122             BCI->getParent()->getInstList().insert(BCI, I);
9123             ReplaceInstUsesWith(*BCI, I);
9124           }
9125           return &GEP;
9126         }
9127       }
9128       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9129     }
9130   }
9131   
9132   // Combine Indices - If the source pointer to this getelementptr instruction
9133   // is a getelementptr instruction, combine the indices of the two
9134   // getelementptr instructions into a single instruction.
9135   //
9136   SmallVector<Value*, 8> SrcGEPOperands;
9137   if (User *Src = dyn_castGetElementPtr(PtrOp))
9138     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9139
9140   if (!SrcGEPOperands.empty()) {
9141     // Note that if our source is a gep chain itself that we wait for that
9142     // chain to be resolved before we perform this transformation.  This
9143     // avoids us creating a TON of code in some cases.
9144     //
9145     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9146         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9147       return 0;   // Wait until our source is folded to completion.
9148
9149     SmallVector<Value*, 8> Indices;
9150
9151     // Find out whether the last index in the source GEP is a sequential idx.
9152     bool EndsWithSequential = false;
9153     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9154            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9155       EndsWithSequential = !isa<StructType>(*I);
9156
9157     // Can we combine the two pointer arithmetics offsets?
9158     if (EndsWithSequential) {
9159       // Replace: gep (gep %P, long B), long A, ...
9160       // With:    T = long A+B; gep %P, T, ...
9161       //
9162       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9163       if (SO1 == Constant::getNullValue(SO1->getType())) {
9164         Sum = GO1;
9165       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9166         Sum = SO1;
9167       } else {
9168         // If they aren't the same type, convert both to an integer of the
9169         // target's pointer size.
9170         if (SO1->getType() != GO1->getType()) {
9171           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9172             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9173           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9174             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9175           } else {
9176             unsigned PS = TD->getPointerSizeInBits();
9177             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9178               // Convert GO1 to SO1's type.
9179               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9180
9181             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9182               // Convert SO1 to GO1's type.
9183               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9184             } else {
9185               const Type *PT = TD->getIntPtrType();
9186               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9187               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9188             }
9189           }
9190         }
9191         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9192           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9193         else {
9194           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9195           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9196         }
9197       }
9198
9199       // Recycle the GEP we already have if possible.
9200       if (SrcGEPOperands.size() == 2) {
9201         GEP.setOperand(0, SrcGEPOperands[0]);
9202         GEP.setOperand(1, Sum);
9203         return &GEP;
9204       } else {
9205         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9206                        SrcGEPOperands.end()-1);
9207         Indices.push_back(Sum);
9208         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9209       }
9210     } else if (isa<Constant>(*GEP.idx_begin()) &&
9211                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9212                SrcGEPOperands.size() != 1) {
9213       // Otherwise we can do the fold if the first index of the GEP is a zero
9214       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9215                      SrcGEPOperands.end());
9216       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9217     }
9218
9219     if (!Indices.empty())
9220       return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9221                                    Indices.end(), GEP.getName());
9222
9223   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9224     // GEP of global variable.  If all of the indices for this GEP are
9225     // constants, we can promote this to a constexpr instead of an instruction.
9226
9227     // Scan for nonconstants...
9228     SmallVector<Constant*, 8> Indices;
9229     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9230     for (; I != E && isa<Constant>(*I); ++I)
9231       Indices.push_back(cast<Constant>(*I));
9232
9233     if (I == E) {  // If they are all constants...
9234       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9235                                                     &Indices[0],Indices.size());
9236
9237       // Replace all uses of the GEP with the new constexpr...
9238       return ReplaceInstUsesWith(GEP, CE);
9239     }
9240   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9241     if (!isa<PointerType>(X->getType())) {
9242       // Not interesting.  Source pointer must be a cast from pointer.
9243     } else if (HasZeroPointerIndex) {
9244       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9245       // into     : GEP [10 x i8]* X, i32 0, ...
9246       //
9247       // This occurs when the program declares an array extern like "int X[];"
9248       //
9249       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9250       const PointerType *XTy = cast<PointerType>(X->getType());
9251       if (const ArrayType *XATy =
9252           dyn_cast<ArrayType>(XTy->getElementType()))
9253         if (const ArrayType *CATy =
9254             dyn_cast<ArrayType>(CPTy->getElementType()))
9255           if (CATy->getElementType() == XATy->getElementType()) {
9256             // At this point, we know that the cast source type is a pointer
9257             // to an array of the same type as the destination pointer
9258             // array.  Because the array type is never stepped over (there
9259             // is a leading zero) we can fold the cast into this GEP.
9260             GEP.setOperand(0, X);
9261             return &GEP;
9262           }
9263     } else if (GEP.getNumOperands() == 2) {
9264       // Transform things like:
9265       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9266       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9267       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9268       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9269       if (isa<ArrayType>(SrcElTy) &&
9270           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9271           TD->getABITypeSize(ResElTy)) {
9272         Value *Idx[2];
9273         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9274         Idx[1] = GEP.getOperand(1);
9275         Value *V = InsertNewInstBefore(
9276                new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
9277         // V and GEP are both pointer types --> BitCast
9278         return new BitCastInst(V, GEP.getType());
9279       }
9280       
9281       // Transform things like:
9282       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9283       //   (where tmp = 8*tmp2) into:
9284       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9285       
9286       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9287         uint64_t ArrayEltSize =
9288             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9289         
9290         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9291         // allow either a mul, shift, or constant here.
9292         Value *NewIdx = 0;
9293         ConstantInt *Scale = 0;
9294         if (ArrayEltSize == 1) {
9295           NewIdx = GEP.getOperand(1);
9296           Scale = ConstantInt::get(NewIdx->getType(), 1);
9297         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9298           NewIdx = ConstantInt::get(CI->getType(), 1);
9299           Scale = CI;
9300         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9301           if (Inst->getOpcode() == Instruction::Shl &&
9302               isa<ConstantInt>(Inst->getOperand(1))) {
9303             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9304             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9305             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9306             NewIdx = Inst->getOperand(0);
9307           } else if (Inst->getOpcode() == Instruction::Mul &&
9308                      isa<ConstantInt>(Inst->getOperand(1))) {
9309             Scale = cast<ConstantInt>(Inst->getOperand(1));
9310             NewIdx = Inst->getOperand(0);
9311           }
9312         }
9313         
9314         // If the index will be to exactly the right offset with the scale taken
9315         // out, perform the transformation. Note, we don't know whether Scale is
9316         // signed or not. We'll use unsigned version of division/modulo
9317         // operation after making sure Scale doesn't have the sign bit set.
9318         if (Scale && Scale->getSExtValue() >= 0LL &&
9319             Scale->getZExtValue() % ArrayEltSize == 0) {
9320           Scale = ConstantInt::get(Scale->getType(),
9321                                    Scale->getZExtValue() / ArrayEltSize);
9322           if (Scale->getZExtValue() != 1) {
9323             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9324                                                        false /*ZExt*/);
9325             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9326             NewIdx = InsertNewInstBefore(Sc, GEP);
9327           }
9328
9329           // Insert the new GEP instruction.
9330           Value *Idx[2];
9331           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9332           Idx[1] = NewIdx;
9333           Instruction *NewGEP =
9334             new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
9335           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9336           // The NewGEP must be pointer typed, so must the old one -> BitCast
9337           return new BitCastInst(NewGEP, GEP.getType());
9338         }
9339       }
9340     }
9341   }
9342
9343   return 0;
9344 }
9345
9346 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9347   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9348   if (AI.isArrayAllocation())    // Check C != 1
9349     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9350       const Type *NewTy = 
9351         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9352       AllocationInst *New = 0;
9353
9354       // Create and insert the replacement instruction...
9355       if (isa<MallocInst>(AI))
9356         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9357       else {
9358         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9359         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9360       }
9361
9362       InsertNewInstBefore(New, AI);
9363
9364       // Scan to the end of the allocation instructions, to skip over a block of
9365       // allocas if possible...
9366       //
9367       BasicBlock::iterator It = New;
9368       while (isa<AllocationInst>(*It)) ++It;
9369
9370       // Now that I is pointing to the first non-allocation-inst in the block,
9371       // insert our getelementptr instruction...
9372       //
9373       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9374       Value *Idx[2];
9375       Idx[0] = NullIdx;
9376       Idx[1] = NullIdx;
9377       Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
9378                                        New->getName()+".sub", It);
9379
9380       // Now make everything use the getelementptr instead of the original
9381       // allocation.
9382       return ReplaceInstUsesWith(AI, V);
9383     } else if (isa<UndefValue>(AI.getArraySize())) {
9384       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9385     }
9386
9387   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9388   // Note that we only do this for alloca's, because malloc should allocate and
9389   // return a unique pointer, even for a zero byte allocation.
9390   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9391       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9392     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9393
9394   return 0;
9395 }
9396
9397 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9398   Value *Op = FI.getOperand(0);
9399
9400   // free undef -> unreachable.
9401   if (isa<UndefValue>(Op)) {
9402     // Insert a new store to null because we cannot modify the CFG here.
9403     new StoreInst(ConstantInt::getTrue(),
9404                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9405     return EraseInstFromFunction(FI);
9406   }
9407   
9408   // If we have 'free null' delete the instruction.  This can happen in stl code
9409   // when lots of inlining happens.
9410   if (isa<ConstantPointerNull>(Op))
9411     return EraseInstFromFunction(FI);
9412   
9413   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9414   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9415     FI.setOperand(0, CI->getOperand(0));
9416     return &FI;
9417   }
9418   
9419   // Change free (gep X, 0,0,0,0) into free(X)
9420   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9421     if (GEPI->hasAllZeroIndices()) {
9422       AddToWorkList(GEPI);
9423       FI.setOperand(0, GEPI->getOperand(0));
9424       return &FI;
9425     }
9426   }
9427   
9428   // Change free(malloc) into nothing, if the malloc has a single use.
9429   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9430     if (MI->hasOneUse()) {
9431       EraseInstFromFunction(FI);
9432       return EraseInstFromFunction(*MI);
9433     }
9434
9435   return 0;
9436 }
9437
9438
9439 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9440 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9441                                         const TargetData *TD) {
9442   User *CI = cast<User>(LI.getOperand(0));
9443   Value *CastOp = CI->getOperand(0);
9444
9445   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9446     // Instead of loading constant c string, use corresponding integer value
9447     // directly if string length is small enough.
9448     const std::string &Str = CE->getOperand(0)->getStringValue();
9449     if (!Str.empty()) {
9450       unsigned len = Str.length();
9451       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9452       unsigned numBits = Ty->getPrimitiveSizeInBits();
9453       // Replace LI with immediate integer store.
9454       if ((numBits >> 3) == len + 1) {
9455         APInt StrVal(numBits, 0);
9456         APInt SingleChar(numBits, 0);
9457         if (TD->isLittleEndian()) {
9458           for (signed i = len-1; i >= 0; i--) {
9459             SingleChar = (uint64_t) Str[i];
9460             StrVal = (StrVal << 8) | SingleChar;
9461           }
9462         } else {
9463           for (unsigned i = 0; i < len; i++) {
9464             SingleChar = (uint64_t) Str[i];
9465                 StrVal = (StrVal << 8) | SingleChar;
9466           }
9467           // Append NULL at the end.
9468           SingleChar = 0;
9469           StrVal = (StrVal << 8) | SingleChar;
9470         }
9471         Value *NL = ConstantInt::get(StrVal);
9472         return IC.ReplaceInstUsesWith(LI, NL);
9473       }
9474     }
9475   }
9476
9477   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9478   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9479     const Type *SrcPTy = SrcTy->getElementType();
9480
9481     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
9482          isa<VectorType>(DestPTy)) {
9483       // If the source is an array, the code below will not succeed.  Check to
9484       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9485       // constants.
9486       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9487         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9488           if (ASrcTy->getNumElements() != 0) {
9489             Value *Idxs[2];
9490             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9491             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9492             SrcTy = cast<PointerType>(CastOp->getType());
9493             SrcPTy = SrcTy->getElementType();
9494           }
9495
9496       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
9497             isa<VectorType>(SrcPTy)) &&
9498           // Do not allow turning this into a load of an integer, which is then
9499           // casted to a pointer, this pessimizes pointer analysis a lot.
9500           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9501           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9502                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9503
9504         // Okay, we are casting from one integer or pointer type to another of
9505         // the same size.  Instead of casting the pointer before the load, cast
9506         // the result of the loaded value.
9507         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9508                                                              CI->getName(),
9509                                                          LI.isVolatile()),LI);
9510         // Now cast the result of the load.
9511         return new BitCastInst(NewLoad, LI.getType());
9512       }
9513     }
9514   }
9515   return 0;
9516 }
9517
9518 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9519 /// from this value cannot trap.  If it is not obviously safe to load from the
9520 /// specified pointer, we do a quick local scan of the basic block containing
9521 /// ScanFrom, to determine if the address is already accessed.
9522 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9523   // If it is an alloca it is always safe to load from.
9524   if (isa<AllocaInst>(V)) return true;
9525
9526   // If it is a global variable it is mostly safe to load from.
9527   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9528     // Don't try to evaluate aliases.  External weak GV can be null.
9529     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9530
9531   // Otherwise, be a little bit agressive by scanning the local block where we
9532   // want to check to see if the pointer is already being loaded or stored
9533   // from/to.  If so, the previous load or store would have already trapped,
9534   // so there is no harm doing an extra load (also, CSE will later eliminate
9535   // the load entirely).
9536   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9537
9538   while (BBI != E) {
9539     --BBI;
9540
9541     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9542       if (LI->getOperand(0) == V) return true;
9543     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9544       if (SI->getOperand(1) == V) return true;
9545
9546   }
9547   return false;
9548 }
9549
9550 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9551 /// until we find the underlying object a pointer is referring to or something
9552 /// we don't understand.  Note that the returned pointer may be offset from the
9553 /// input, because we ignore GEP indices.
9554 static Value *GetUnderlyingObject(Value *Ptr) {
9555   while (1) {
9556     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9557       if (CE->getOpcode() == Instruction::BitCast ||
9558           CE->getOpcode() == Instruction::GetElementPtr)
9559         Ptr = CE->getOperand(0);
9560       else
9561         return Ptr;
9562     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9563       Ptr = BCI->getOperand(0);
9564     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9565       Ptr = GEP->getOperand(0);
9566     } else {
9567       return Ptr;
9568     }
9569   }
9570 }
9571
9572 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9573   Value *Op = LI.getOperand(0);
9574
9575   // Attempt to improve the alignment.
9576   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
9577   if (KnownAlign > LI.getAlignment())
9578     LI.setAlignment(KnownAlign);
9579
9580   // load (cast X) --> cast (load X) iff safe
9581   if (isa<CastInst>(Op))
9582     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9583       return Res;
9584
9585   // None of the following transforms are legal for volatile loads.
9586   if (LI.isVolatile()) return 0;
9587   
9588   if (&LI.getParent()->front() != &LI) {
9589     BasicBlock::iterator BBI = &LI; --BBI;
9590     // If the instruction immediately before this is a store to the same
9591     // address, do a simple form of store->load forwarding.
9592     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9593       if (SI->getOperand(1) == LI.getOperand(0))
9594         return ReplaceInstUsesWith(LI, SI->getOperand(0));
9595     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9596       if (LIB->getOperand(0) == LI.getOperand(0))
9597         return ReplaceInstUsesWith(LI, LIB);
9598   }
9599
9600   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9601     const Value *GEPI0 = GEPI->getOperand(0);
9602     // TODO: Consider a target hook for valid address spaces for this xform.
9603     if (isa<ConstantPointerNull>(GEPI0) &&
9604         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
9605       // Insert a new store to null instruction before the load to indicate
9606       // that this code is not reachable.  We do this instead of inserting
9607       // an unreachable instruction directly because we cannot modify the
9608       // CFG.
9609       new StoreInst(UndefValue::get(LI.getType()),
9610                     Constant::getNullValue(Op->getType()), &LI);
9611       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9612     }
9613   } 
9614
9615   if (Constant *C = dyn_cast<Constant>(Op)) {
9616     // load null/undef -> undef
9617     // TODO: Consider a target hook for valid address spaces for this xform.
9618     if (isa<UndefValue>(C) || (C->isNullValue() && 
9619         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
9620       // Insert a new store to null instruction before the load to indicate that
9621       // this code is not reachable.  We do this instead of inserting an
9622       // unreachable instruction directly because we cannot modify the CFG.
9623       new StoreInst(UndefValue::get(LI.getType()),
9624                     Constant::getNullValue(Op->getType()), &LI);
9625       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9626     }
9627
9628     // Instcombine load (constant global) into the value loaded.
9629     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9630       if (GV->isConstant() && !GV->isDeclaration())
9631         return ReplaceInstUsesWith(LI, GV->getInitializer());
9632
9633     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9634     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9635       if (CE->getOpcode() == Instruction::GetElementPtr) {
9636         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9637           if (GV->isConstant() && !GV->isDeclaration())
9638             if (Constant *V = 
9639                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9640               return ReplaceInstUsesWith(LI, V);
9641         if (CE->getOperand(0)->isNullValue()) {
9642           // Insert a new store to null instruction before the load to indicate
9643           // that this code is not reachable.  We do this instead of inserting
9644           // an unreachable instruction directly because we cannot modify the
9645           // CFG.
9646           new StoreInst(UndefValue::get(LI.getType()),
9647                         Constant::getNullValue(Op->getType()), &LI);
9648           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9649         }
9650
9651       } else if (CE->isCast()) {
9652         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9653           return Res;
9654       }
9655   }
9656     
9657   // If this load comes from anywhere in a constant global, and if the global
9658   // is all undef or zero, we know what it loads.
9659   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9660     if (GV->isConstant() && GV->hasInitializer()) {
9661       if (GV->getInitializer()->isNullValue())
9662         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9663       else if (isa<UndefValue>(GV->getInitializer()))
9664         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9665     }
9666   }
9667
9668   if (Op->hasOneUse()) {
9669     // Change select and PHI nodes to select values instead of addresses: this
9670     // helps alias analysis out a lot, allows many others simplifications, and
9671     // exposes redundancy in the code.
9672     //
9673     // Note that we cannot do the transformation unless we know that the
9674     // introduced loads cannot trap!  Something like this is valid as long as
9675     // the condition is always false: load (select bool %C, int* null, int* %G),
9676     // but it would not be valid if we transformed it to load from null
9677     // unconditionally.
9678     //
9679     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9680       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
9681       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9682           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9683         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9684                                      SI->getOperand(1)->getName()+".val"), LI);
9685         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9686                                      SI->getOperand(2)->getName()+".val"), LI);
9687         return new SelectInst(SI->getCondition(), V1, V2);
9688       }
9689
9690       // load (select (cond, null, P)) -> load P
9691       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9692         if (C->isNullValue()) {
9693           LI.setOperand(0, SI->getOperand(2));
9694           return &LI;
9695         }
9696
9697       // load (select (cond, P, null)) -> load P
9698       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9699         if (C->isNullValue()) {
9700           LI.setOperand(0, SI->getOperand(1));
9701           return &LI;
9702         }
9703     }
9704   }
9705   return 0;
9706 }
9707
9708 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9709 /// when possible.
9710 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9711   User *CI = cast<User>(SI.getOperand(1));
9712   Value *CastOp = CI->getOperand(0);
9713
9714   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9715   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9716     const Type *SrcPTy = SrcTy->getElementType();
9717
9718     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9719       // If the source is an array, the code below will not succeed.  Check to
9720       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9721       // constants.
9722       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9723         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9724           if (ASrcTy->getNumElements() != 0) {
9725             Value* Idxs[2];
9726             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9727             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9728             SrcTy = cast<PointerType>(CastOp->getType());
9729             SrcPTy = SrcTy->getElementType();
9730           }
9731
9732       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9733           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9734                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9735
9736         // Okay, we are casting from one integer or pointer type to another of
9737         // the same size.  Instead of casting the pointer before 
9738         // the store, cast the value to be stored.
9739         Value *NewCast;
9740         Value *SIOp0 = SI.getOperand(0);
9741         Instruction::CastOps opcode = Instruction::BitCast;
9742         const Type* CastSrcTy = SIOp0->getType();
9743         const Type* CastDstTy = SrcPTy;
9744         if (isa<PointerType>(CastDstTy)) {
9745           if (CastSrcTy->isInteger())
9746             opcode = Instruction::IntToPtr;
9747         } else if (isa<IntegerType>(CastDstTy)) {
9748           if (isa<PointerType>(SIOp0->getType()))
9749             opcode = Instruction::PtrToInt;
9750         }
9751         if (Constant *C = dyn_cast<Constant>(SIOp0))
9752           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9753         else
9754           NewCast = IC.InsertNewInstBefore(
9755             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
9756             SI);
9757         return new StoreInst(NewCast, CastOp);
9758       }
9759     }
9760   }
9761   return 0;
9762 }
9763
9764 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9765   Value *Val = SI.getOperand(0);
9766   Value *Ptr = SI.getOperand(1);
9767
9768   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
9769     EraseInstFromFunction(SI);
9770     ++NumCombined;
9771     return 0;
9772   }
9773   
9774   // If the RHS is an alloca with a single use, zapify the store, making the
9775   // alloca dead.
9776   if (Ptr->hasOneUse()) {
9777     if (isa<AllocaInst>(Ptr)) {
9778       EraseInstFromFunction(SI);
9779       ++NumCombined;
9780       return 0;
9781     }
9782     
9783     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9784       if (isa<AllocaInst>(GEP->getOperand(0)) &&
9785           GEP->getOperand(0)->hasOneUse()) {
9786         EraseInstFromFunction(SI);
9787         ++NumCombined;
9788         return 0;
9789       }
9790   }
9791
9792   // Attempt to improve the alignment.
9793   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
9794   if (KnownAlign > SI.getAlignment())
9795     SI.setAlignment(KnownAlign);
9796
9797   // Do really simple DSE, to catch cases where there are several consequtive
9798   // stores to the same location, separated by a few arithmetic operations. This
9799   // situation often occurs with bitfield accesses.
9800   BasicBlock::iterator BBI = &SI;
9801   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9802        --ScanInsts) {
9803     --BBI;
9804     
9805     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9806       // Prev store isn't volatile, and stores to the same location?
9807       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9808         ++NumDeadStore;
9809         ++BBI;
9810         EraseInstFromFunction(*PrevSI);
9811         continue;
9812       }
9813       break;
9814     }
9815     
9816     // If this is a load, we have to stop.  However, if the loaded value is from
9817     // the pointer we're loading and is producing the pointer we're storing,
9818     // then *this* store is dead (X = load P; store X -> P).
9819     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9820       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
9821         EraseInstFromFunction(SI);
9822         ++NumCombined;
9823         return 0;
9824       }
9825       // Otherwise, this is a load from some other location.  Stores before it
9826       // may not be dead.
9827       break;
9828     }
9829     
9830     // Don't skip over loads or things that can modify memory.
9831     if (BBI->mayWriteToMemory())
9832       break;
9833   }
9834   
9835   
9836   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
9837
9838   // store X, null    -> turns into 'unreachable' in SimplifyCFG
9839   if (isa<ConstantPointerNull>(Ptr)) {
9840     if (!isa<UndefValue>(Val)) {
9841       SI.setOperand(0, UndefValue::get(Val->getType()));
9842       if (Instruction *U = dyn_cast<Instruction>(Val))
9843         AddToWorkList(U);  // Dropped a use.
9844       ++NumCombined;
9845     }
9846     return 0;  // Do not modify these!
9847   }
9848
9849   // store undef, Ptr -> noop
9850   if (isa<UndefValue>(Val)) {
9851     EraseInstFromFunction(SI);
9852     ++NumCombined;
9853     return 0;
9854   }
9855
9856   // If the pointer destination is a cast, see if we can fold the cast into the
9857   // source instead.
9858   if (isa<CastInst>(Ptr))
9859     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9860       return Res;
9861   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9862     if (CE->isCast())
9863       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9864         return Res;
9865
9866   
9867   // If this store is the last instruction in the basic block, and if the block
9868   // ends with an unconditional branch, try to move it to the successor block.
9869   BBI = &SI; ++BBI;
9870   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9871     if (BI->isUnconditional())
9872       if (SimplifyStoreAtEndOfBlock(SI))
9873         return 0;  // xform done!
9874   
9875   return 0;
9876 }
9877
9878 /// SimplifyStoreAtEndOfBlock - Turn things like:
9879 ///   if () { *P = v1; } else { *P = v2 }
9880 /// into a phi node with a store in the successor.
9881 ///
9882 /// Simplify things like:
9883 ///   *P = v1; if () { *P = v2; }
9884 /// into a phi node with a store in the successor.
9885 ///
9886 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9887   BasicBlock *StoreBB = SI.getParent();
9888   
9889   // Check to see if the successor block has exactly two incoming edges.  If
9890   // so, see if the other predecessor contains a store to the same location.
9891   // if so, insert a PHI node (if needed) and move the stores down.
9892   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9893   
9894   // Determine whether Dest has exactly two predecessors and, if so, compute
9895   // the other predecessor.
9896   pred_iterator PI = pred_begin(DestBB);
9897   BasicBlock *OtherBB = 0;
9898   if (*PI != StoreBB)
9899     OtherBB = *PI;
9900   ++PI;
9901   if (PI == pred_end(DestBB))
9902     return false;
9903   
9904   if (*PI != StoreBB) {
9905     if (OtherBB)
9906       return false;
9907     OtherBB = *PI;
9908   }
9909   if (++PI != pred_end(DestBB))
9910     return false;
9911   
9912   
9913   // Verify that the other block ends in a branch and is not otherwise empty.
9914   BasicBlock::iterator BBI = OtherBB->getTerminator();
9915   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9916   if (!OtherBr || BBI == OtherBB->begin())
9917     return false;
9918   
9919   // If the other block ends in an unconditional branch, check for the 'if then
9920   // else' case.  there is an instruction before the branch.
9921   StoreInst *OtherStore = 0;
9922   if (OtherBr->isUnconditional()) {
9923     // If this isn't a store, or isn't a store to the same location, bail out.
9924     --BBI;
9925     OtherStore = dyn_cast<StoreInst>(BBI);
9926     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9927       return false;
9928   } else {
9929     // Otherwise, the other block ended with a conditional branch. If one of the
9930     // destinations is StoreBB, then we have the if/then case.
9931     if (OtherBr->getSuccessor(0) != StoreBB && 
9932         OtherBr->getSuccessor(1) != StoreBB)
9933       return false;
9934     
9935     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9936     // if/then triangle.  See if there is a store to the same ptr as SI that
9937     // lives in OtherBB.
9938     for (;; --BBI) {
9939       // Check to see if we find the matching store.
9940       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9941         if (OtherStore->getOperand(1) != SI.getOperand(1))
9942           return false;
9943         break;
9944       }
9945       // If we find something that may be using the stored value, or if we run
9946       // out of instructions, we can't do the xform.
9947       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9948           BBI == OtherBB->begin())
9949         return false;
9950     }
9951     
9952     // In order to eliminate the store in OtherBr, we have to
9953     // make sure nothing reads the stored value in StoreBB.
9954     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9955       // FIXME: This should really be AA driven.
9956       if (isa<LoadInst>(I) || I->mayWriteToMemory())
9957         return false;
9958     }
9959   }
9960   
9961   // Insert a PHI node now if we need it.
9962   Value *MergedVal = OtherStore->getOperand(0);
9963   if (MergedVal != SI.getOperand(0)) {
9964     PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9965     PN->reserveOperandSpace(2);
9966     PN->addIncoming(SI.getOperand(0), SI.getParent());
9967     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9968     MergedVal = InsertNewInstBefore(PN, DestBB->front());
9969   }
9970   
9971   // Advance to a place where it is safe to insert the new store and
9972   // insert it.
9973   BBI = DestBB->begin();
9974   while (isa<PHINode>(BBI)) ++BBI;
9975   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9976                                     OtherStore->isVolatile()), *BBI);
9977   
9978   // Nuke the old stores.
9979   EraseInstFromFunction(SI);
9980   EraseInstFromFunction(*OtherStore);
9981   ++NumCombined;
9982   return true;
9983 }
9984
9985
9986 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9987   // Change br (not X), label True, label False to: br X, label False, True
9988   Value *X = 0;
9989   BasicBlock *TrueDest;
9990   BasicBlock *FalseDest;
9991   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9992       !isa<Constant>(X)) {
9993     // Swap Destinations and condition...
9994     BI.setCondition(X);
9995     BI.setSuccessor(0, FalseDest);
9996     BI.setSuccessor(1, TrueDest);
9997     return &BI;
9998   }
9999
10000   // Cannonicalize fcmp_one -> fcmp_oeq
10001   FCmpInst::Predicate FPred; Value *Y;
10002   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10003                              TrueDest, FalseDest)))
10004     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10005          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10006       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10007       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10008       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10009       NewSCC->takeName(I);
10010       // Swap Destinations and condition...
10011       BI.setCondition(NewSCC);
10012       BI.setSuccessor(0, FalseDest);
10013       BI.setSuccessor(1, TrueDest);
10014       RemoveFromWorkList(I);
10015       I->eraseFromParent();
10016       AddToWorkList(NewSCC);
10017       return &BI;
10018     }
10019
10020   // Cannonicalize icmp_ne -> icmp_eq
10021   ICmpInst::Predicate IPred;
10022   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10023                       TrueDest, FalseDest)))
10024     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10025          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10026          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10027       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10028       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10029       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10030       NewSCC->takeName(I);
10031       // Swap Destinations and condition...
10032       BI.setCondition(NewSCC);
10033       BI.setSuccessor(0, FalseDest);
10034       BI.setSuccessor(1, TrueDest);
10035       RemoveFromWorkList(I);
10036       I->eraseFromParent();;
10037       AddToWorkList(NewSCC);
10038       return &BI;
10039     }
10040
10041   return 0;
10042 }
10043
10044 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10045   Value *Cond = SI.getCondition();
10046   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10047     if (I->getOpcode() == Instruction::Add)
10048       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10049         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10050         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10051           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10052                                                 AddRHS));
10053         SI.setOperand(0, I->getOperand(0));
10054         AddToWorkList(I);
10055         return &SI;
10056       }
10057   }
10058   return 0;
10059 }
10060
10061 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10062 /// is to leave as a vector operation.
10063 static bool CheapToScalarize(Value *V, bool isConstant) {
10064   if (isa<ConstantAggregateZero>(V)) 
10065     return true;
10066   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10067     if (isConstant) return true;
10068     // If all elts are the same, we can extract.
10069     Constant *Op0 = C->getOperand(0);
10070     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10071       if (C->getOperand(i) != Op0)
10072         return false;
10073     return true;
10074   }
10075   Instruction *I = dyn_cast<Instruction>(V);
10076   if (!I) return false;
10077   
10078   // Insert element gets simplified to the inserted element or is deleted if
10079   // this is constant idx extract element and its a constant idx insertelt.
10080   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10081       isa<ConstantInt>(I->getOperand(2)))
10082     return true;
10083   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10084     return true;
10085   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10086     if (BO->hasOneUse() &&
10087         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10088          CheapToScalarize(BO->getOperand(1), isConstant)))
10089       return true;
10090   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10091     if (CI->hasOneUse() &&
10092         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10093          CheapToScalarize(CI->getOperand(1), isConstant)))
10094       return true;
10095   
10096   return false;
10097 }
10098
10099 /// Read and decode a shufflevector mask.
10100 ///
10101 /// It turns undef elements into values that are larger than the number of
10102 /// elements in the input.
10103 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10104   unsigned NElts = SVI->getType()->getNumElements();
10105   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10106     return std::vector<unsigned>(NElts, 0);
10107   if (isa<UndefValue>(SVI->getOperand(2)))
10108     return std::vector<unsigned>(NElts, 2*NElts);
10109
10110   std::vector<unsigned> Result;
10111   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10112   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10113     if (isa<UndefValue>(CP->getOperand(i)))
10114       Result.push_back(NElts*2);  // undef -> 8
10115     else
10116       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10117   return Result;
10118 }
10119
10120 /// FindScalarElement - Given a vector and an element number, see if the scalar
10121 /// value is already around as a register, for example if it were inserted then
10122 /// extracted from the vector.
10123 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10124   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10125   const VectorType *PTy = cast<VectorType>(V->getType());
10126   unsigned Width = PTy->getNumElements();
10127   if (EltNo >= Width)  // Out of range access.
10128     return UndefValue::get(PTy->getElementType());
10129   
10130   if (isa<UndefValue>(V))
10131     return UndefValue::get(PTy->getElementType());
10132   else if (isa<ConstantAggregateZero>(V))
10133     return Constant::getNullValue(PTy->getElementType());
10134   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10135     return CP->getOperand(EltNo);
10136   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10137     // If this is an insert to a variable element, we don't know what it is.
10138     if (!isa<ConstantInt>(III->getOperand(2))) 
10139       return 0;
10140     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10141     
10142     // If this is an insert to the element we are looking for, return the
10143     // inserted value.
10144     if (EltNo == IIElt) 
10145       return III->getOperand(1);
10146     
10147     // Otherwise, the insertelement doesn't modify the value, recurse on its
10148     // vector input.
10149     return FindScalarElement(III->getOperand(0), EltNo);
10150   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10151     unsigned InEl = getShuffleMask(SVI)[EltNo];
10152     if (InEl < Width)
10153       return FindScalarElement(SVI->getOperand(0), InEl);
10154     else if (InEl < Width*2)
10155       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10156     else
10157       return UndefValue::get(PTy->getElementType());
10158   }
10159   
10160   // Otherwise, we don't know.
10161   return 0;
10162 }
10163
10164 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10165
10166   // If vector val is undef, replace extract with scalar undef.
10167   if (isa<UndefValue>(EI.getOperand(0)))
10168     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10169
10170   // If vector val is constant 0, replace extract with scalar 0.
10171   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10172     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10173   
10174   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10175     // If vector val is constant with uniform operands, replace EI
10176     // with that operand
10177     Constant *op0 = C->getOperand(0);
10178     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10179       if (C->getOperand(i) != op0) {
10180         op0 = 0; 
10181         break;
10182       }
10183     if (op0)
10184       return ReplaceInstUsesWith(EI, op0);
10185   }
10186   
10187   // If extracting a specified index from the vector, see if we can recursively
10188   // find a previously computed scalar that was inserted into the vector.
10189   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10190     unsigned IndexVal = IdxC->getZExtValue();
10191     unsigned VectorWidth = 
10192       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10193       
10194     // If this is extracting an invalid index, turn this into undef, to avoid
10195     // crashing the code below.
10196     if (IndexVal >= VectorWidth)
10197       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10198     
10199     // This instruction only demands the single element from the input vector.
10200     // If the input vector has a single use, simplify it based on this use
10201     // property.
10202     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10203       uint64_t UndefElts;
10204       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10205                                                 1 << IndexVal,
10206                                                 UndefElts)) {
10207         EI.setOperand(0, V);
10208         return &EI;
10209       }
10210     }
10211     
10212     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10213       return ReplaceInstUsesWith(EI, Elt);
10214     
10215     // If the this extractelement is directly using a bitcast from a vector of
10216     // the same number of elements, see if we can find the source element from
10217     // it.  In this case, we will end up needing to bitcast the scalars.
10218     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10219       if (const VectorType *VT = 
10220               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10221         if (VT->getNumElements() == VectorWidth)
10222           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10223             return new BitCastInst(Elt, EI.getType());
10224     }
10225   }
10226   
10227   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10228     if (I->hasOneUse()) {
10229       // Push extractelement into predecessor operation if legal and
10230       // profitable to do so
10231       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10232         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10233         if (CheapToScalarize(BO, isConstantElt)) {
10234           ExtractElementInst *newEI0 = 
10235             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10236                                    EI.getName()+".lhs");
10237           ExtractElementInst *newEI1 =
10238             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10239                                    EI.getName()+".rhs");
10240           InsertNewInstBefore(newEI0, EI);
10241           InsertNewInstBefore(newEI1, EI);
10242           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10243         }
10244       } else if (isa<LoadInst>(I)) {
10245         unsigned AS = 
10246           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10247         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10248                                          PointerType::get(EI.getType(), AS),EI);
10249         GetElementPtrInst *GEP = 
10250           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10251         InsertNewInstBefore(GEP, EI);
10252         return new LoadInst(GEP);
10253       }
10254     }
10255     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10256       // Extracting the inserted element?
10257       if (IE->getOperand(2) == EI.getOperand(1))
10258         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10259       // If the inserted and extracted elements are constants, they must not
10260       // be the same value, extract from the pre-inserted value instead.
10261       if (isa<Constant>(IE->getOperand(2)) &&
10262           isa<Constant>(EI.getOperand(1))) {
10263         AddUsesToWorkList(EI);
10264         EI.setOperand(0, IE->getOperand(0));
10265         return &EI;
10266       }
10267     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10268       // If this is extracting an element from a shufflevector, figure out where
10269       // it came from and extract from the appropriate input element instead.
10270       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10271         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10272         Value *Src;
10273         if (SrcIdx < SVI->getType()->getNumElements())
10274           Src = SVI->getOperand(0);
10275         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10276           SrcIdx -= SVI->getType()->getNumElements();
10277           Src = SVI->getOperand(1);
10278         } else {
10279           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10280         }
10281         return new ExtractElementInst(Src, SrcIdx);
10282       }
10283     }
10284   }
10285   return 0;
10286 }
10287
10288 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10289 /// elements from either LHS or RHS, return the shuffle mask and true. 
10290 /// Otherwise, return false.
10291 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10292                                          std::vector<Constant*> &Mask) {
10293   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10294          "Invalid CollectSingleShuffleElements");
10295   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10296
10297   if (isa<UndefValue>(V)) {
10298     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10299     return true;
10300   } else if (V == LHS) {
10301     for (unsigned i = 0; i != NumElts; ++i)
10302       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10303     return true;
10304   } else if (V == RHS) {
10305     for (unsigned i = 0; i != NumElts; ++i)
10306       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10307     return true;
10308   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10309     // If this is an insert of an extract from some other vector, include it.
10310     Value *VecOp    = IEI->getOperand(0);
10311     Value *ScalarOp = IEI->getOperand(1);
10312     Value *IdxOp    = IEI->getOperand(2);
10313     
10314     if (!isa<ConstantInt>(IdxOp))
10315       return false;
10316     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10317     
10318     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10319       // Okay, we can handle this if the vector we are insertinting into is
10320       // transitively ok.
10321       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10322         // If so, update the mask to reflect the inserted undef.
10323         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10324         return true;
10325       }      
10326     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10327       if (isa<ConstantInt>(EI->getOperand(1)) &&
10328           EI->getOperand(0)->getType() == V->getType()) {
10329         unsigned ExtractedIdx =
10330           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10331         
10332         // This must be extracting from either LHS or RHS.
10333         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10334           // Okay, we can handle this if the vector we are insertinting into is
10335           // transitively ok.
10336           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10337             // If so, update the mask to reflect the inserted value.
10338             if (EI->getOperand(0) == LHS) {
10339               Mask[InsertedIdx & (NumElts-1)] = 
10340                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10341             } else {
10342               assert(EI->getOperand(0) == RHS);
10343               Mask[InsertedIdx & (NumElts-1)] = 
10344                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10345               
10346             }
10347             return true;
10348           }
10349         }
10350       }
10351     }
10352   }
10353   // TODO: Handle shufflevector here!
10354   
10355   return false;
10356 }
10357
10358 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10359 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10360 /// that computes V and the LHS value of the shuffle.
10361 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10362                                      Value *&RHS) {
10363   assert(isa<VectorType>(V->getType()) && 
10364          (RHS == 0 || V->getType() == RHS->getType()) &&
10365          "Invalid shuffle!");
10366   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10367
10368   if (isa<UndefValue>(V)) {
10369     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10370     return V;
10371   } else if (isa<ConstantAggregateZero>(V)) {
10372     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10373     return V;
10374   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10375     // If this is an insert of an extract from some other vector, include it.
10376     Value *VecOp    = IEI->getOperand(0);
10377     Value *ScalarOp = IEI->getOperand(1);
10378     Value *IdxOp    = IEI->getOperand(2);
10379     
10380     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10381       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10382           EI->getOperand(0)->getType() == V->getType()) {
10383         unsigned ExtractedIdx =
10384           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10385         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10386         
10387         // Either the extracted from or inserted into vector must be RHSVec,
10388         // otherwise we'd end up with a shuffle of three inputs.
10389         if (EI->getOperand(0) == RHS || RHS == 0) {
10390           RHS = EI->getOperand(0);
10391           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10392           Mask[InsertedIdx & (NumElts-1)] = 
10393             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10394           return V;
10395         }
10396         
10397         if (VecOp == RHS) {
10398           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10399           // Everything but the extracted element is replaced with the RHS.
10400           for (unsigned i = 0; i != NumElts; ++i) {
10401             if (i != InsertedIdx)
10402               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10403           }
10404           return V;
10405         }
10406         
10407         // If this insertelement is a chain that comes from exactly these two
10408         // vectors, return the vector and the effective shuffle.
10409         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10410           return EI->getOperand(0);
10411         
10412       }
10413     }
10414   }
10415   // TODO: Handle shufflevector here!
10416   
10417   // Otherwise, can't do anything fancy.  Return an identity vector.
10418   for (unsigned i = 0; i != NumElts; ++i)
10419     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10420   return V;
10421 }
10422
10423 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10424   Value *VecOp    = IE.getOperand(0);
10425   Value *ScalarOp = IE.getOperand(1);
10426   Value *IdxOp    = IE.getOperand(2);
10427   
10428   // Inserting an undef or into an undefined place, remove this.
10429   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10430     ReplaceInstUsesWith(IE, VecOp);
10431   
10432   // If the inserted element was extracted from some other vector, and if the 
10433   // indexes are constant, try to turn this into a shufflevector operation.
10434   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10435     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10436         EI->getOperand(0)->getType() == IE.getType()) {
10437       unsigned NumVectorElts = IE.getType()->getNumElements();
10438       unsigned ExtractedIdx =
10439         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10440       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10441       
10442       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10443         return ReplaceInstUsesWith(IE, VecOp);
10444       
10445       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10446         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10447       
10448       // If we are extracting a value from a vector, then inserting it right
10449       // back into the same place, just use the input vector.
10450       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10451         return ReplaceInstUsesWith(IE, VecOp);      
10452       
10453       // We could theoretically do this for ANY input.  However, doing so could
10454       // turn chains of insertelement instructions into a chain of shufflevector
10455       // instructions, and right now we do not merge shufflevectors.  As such,
10456       // only do this in a situation where it is clear that there is benefit.
10457       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10458         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
10459         // the values of VecOp, except then one read from EIOp0.
10460         // Build a new shuffle mask.
10461         std::vector<Constant*> Mask;
10462         if (isa<UndefValue>(VecOp))
10463           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10464         else {
10465           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10466           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10467                                                        NumVectorElts));
10468         } 
10469         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10470         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10471                                      ConstantVector::get(Mask));
10472       }
10473       
10474       // If this insertelement isn't used by some other insertelement, turn it
10475       // (and any insertelements it points to), into one big shuffle.
10476       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10477         std::vector<Constant*> Mask;
10478         Value *RHS = 0;
10479         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10480         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10481         // We now have a shuffle of LHS, RHS, Mask.
10482         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10483       }
10484     }
10485   }
10486
10487   return 0;
10488 }
10489
10490
10491 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10492   Value *LHS = SVI.getOperand(0);
10493   Value *RHS = SVI.getOperand(1);
10494   std::vector<unsigned> Mask = getShuffleMask(&SVI);
10495
10496   bool MadeChange = false;
10497   
10498   // Undefined shuffle mask -> undefined value.
10499   if (isa<UndefValue>(SVI.getOperand(2)))
10500     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10501   
10502   // If we have shuffle(x, undef, mask) and any elements of mask refer to
10503   // the undef, change them to undefs.
10504   if (isa<UndefValue>(SVI.getOperand(1))) {
10505     // Scan to see if there are any references to the RHS.  If so, replace them
10506     // with undef element refs and set MadeChange to true.
10507     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10508       if (Mask[i] >= e && Mask[i] != 2*e) {
10509         Mask[i] = 2*e;
10510         MadeChange = true;
10511       }
10512     }
10513     
10514     if (MadeChange) {
10515       // Remap any references to RHS to use LHS.
10516       std::vector<Constant*> Elts;
10517       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10518         if (Mask[i] == 2*e)
10519           Elts.push_back(UndefValue::get(Type::Int32Ty));
10520         else
10521           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10522       }
10523       SVI.setOperand(2, ConstantVector::get(Elts));
10524     }
10525   }
10526   
10527   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
10528   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10529   if (LHS == RHS || isa<UndefValue>(LHS)) {
10530     if (isa<UndefValue>(LHS) && LHS == RHS) {
10531       // shuffle(undef,undef,mask) -> undef.
10532       return ReplaceInstUsesWith(SVI, LHS);
10533     }
10534     
10535     // Remap any references to RHS to use LHS.
10536     std::vector<Constant*> Elts;
10537     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10538       if (Mask[i] >= 2*e)
10539         Elts.push_back(UndefValue::get(Type::Int32Ty));
10540       else {
10541         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10542             (Mask[i] <  e && isa<UndefValue>(LHS)))
10543           Mask[i] = 2*e;     // Turn into undef.
10544         else
10545           Mask[i] &= (e-1);  // Force to LHS.
10546         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10547       }
10548     }
10549     SVI.setOperand(0, SVI.getOperand(1));
10550     SVI.setOperand(1, UndefValue::get(RHS->getType()));
10551     SVI.setOperand(2, ConstantVector::get(Elts));
10552     LHS = SVI.getOperand(0);
10553     RHS = SVI.getOperand(1);
10554     MadeChange = true;
10555   }
10556   
10557   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10558   bool isLHSID = true, isRHSID = true;
10559     
10560   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10561     if (Mask[i] >= e*2) continue;  // Ignore undef values.
10562     // Is this an identity shuffle of the LHS value?
10563     isLHSID &= (Mask[i] == i);
10564       
10565     // Is this an identity shuffle of the RHS value?
10566     isRHSID &= (Mask[i]-e == i);
10567   }
10568
10569   // Eliminate identity shuffles.
10570   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10571   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10572   
10573   // If the LHS is a shufflevector itself, see if we can combine it with this
10574   // one without producing an unusual shuffle.  Here we are really conservative:
10575   // we are absolutely afraid of producing a shuffle mask not in the input
10576   // program, because the code gen may not be smart enough to turn a merged
10577   // shuffle into two specific shuffles: it may produce worse code.  As such,
10578   // we only merge two shuffles if the result is one of the two input shuffle
10579   // masks.  In this case, merging the shuffles just removes one instruction,
10580   // which we know is safe.  This is good for things like turning:
10581   // (splat(splat)) -> splat.
10582   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10583     if (isa<UndefValue>(RHS)) {
10584       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10585
10586       std::vector<unsigned> NewMask;
10587       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10588         if (Mask[i] >= 2*e)
10589           NewMask.push_back(2*e);
10590         else
10591           NewMask.push_back(LHSMask[Mask[i]]);
10592       
10593       // If the result mask is equal to the src shuffle or this shuffle mask, do
10594       // the replacement.
10595       if (NewMask == LHSMask || NewMask == Mask) {
10596         std::vector<Constant*> Elts;
10597         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10598           if (NewMask[i] >= e*2) {
10599             Elts.push_back(UndefValue::get(Type::Int32Ty));
10600           } else {
10601             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10602           }
10603         }
10604         return new ShuffleVectorInst(LHSSVI->getOperand(0),
10605                                      LHSSVI->getOperand(1),
10606                                      ConstantVector::get(Elts));
10607       }
10608     }
10609   }
10610
10611   return MadeChange ? &SVI : 0;
10612 }
10613
10614
10615
10616
10617 /// TryToSinkInstruction - Try to move the specified instruction from its
10618 /// current block into the beginning of DestBlock, which can only happen if it's
10619 /// safe to move the instruction past all of the instructions between it and the
10620 /// end of its block.
10621 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10622   assert(I->hasOneUse() && "Invariants didn't hold!");
10623
10624   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10625   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10626
10627   // Do not sink alloca instructions out of the entry block.
10628   if (isa<AllocaInst>(I) && I->getParent() ==
10629         &DestBlock->getParent()->getEntryBlock())
10630     return false;
10631
10632   // We can only sink load instructions if there is nothing between the load and
10633   // the end of block that could change the value.
10634   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10635     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10636          Scan != E; ++Scan)
10637       if (Scan->mayWriteToMemory())
10638         return false;
10639   }
10640
10641   BasicBlock::iterator InsertPos = DestBlock->begin();
10642   while (isa<PHINode>(InsertPos)) ++InsertPos;
10643
10644   I->moveBefore(InsertPos);
10645   ++NumSunkInst;
10646   return true;
10647 }
10648
10649
10650 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10651 /// all reachable code to the worklist.
10652 ///
10653 /// This has a couple of tricks to make the code faster and more powerful.  In
10654 /// particular, we constant fold and DCE instructions as we go, to avoid adding
10655 /// them to the worklist (this significantly speeds up instcombine on code where
10656 /// many instructions are dead or constant).  Additionally, if we find a branch
10657 /// whose condition is a known constant, we only visit the reachable successors.
10658 ///
10659 static void AddReachableCodeToWorklist(BasicBlock *BB, 
10660                                        SmallPtrSet<BasicBlock*, 64> &Visited,
10661                                        InstCombiner &IC,
10662                                        const TargetData *TD) {
10663   std::vector<BasicBlock*> Worklist;
10664   Worklist.push_back(BB);
10665
10666   while (!Worklist.empty()) {
10667     BB = Worklist.back();
10668     Worklist.pop_back();
10669     
10670     // We have now visited this block!  If we've already been here, ignore it.
10671     if (!Visited.insert(BB)) continue;
10672     
10673     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10674       Instruction *Inst = BBI++;
10675       
10676       // DCE instruction if trivially dead.
10677       if (isInstructionTriviallyDead(Inst)) {
10678         ++NumDeadInst;
10679         DOUT << "IC: DCE: " << *Inst;
10680         Inst->eraseFromParent();
10681         continue;
10682       }
10683       
10684       // ConstantProp instruction if trivially constant.
10685       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10686         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10687         Inst->replaceAllUsesWith(C);
10688         ++NumConstProp;
10689         Inst->eraseFromParent();
10690         continue;
10691       }
10692      
10693       IC.AddToWorkList(Inst);
10694     }
10695
10696     // Recursively visit successors.  If this is a branch or switch on a
10697     // constant, only visit the reachable successor.
10698     TerminatorInst *TI = BB->getTerminator();
10699     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10700       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10701         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10702         Worklist.push_back(BI->getSuccessor(!CondVal));
10703         continue;
10704       }
10705     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10706       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10707         // See if this is an explicit destination.
10708         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10709           if (SI->getCaseValue(i) == Cond) {
10710             Worklist.push_back(SI->getSuccessor(i));
10711             continue;
10712           }
10713         
10714         // Otherwise it is the default destination.
10715         Worklist.push_back(SI->getSuccessor(0));
10716         continue;
10717       }
10718     }
10719     
10720     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10721       Worklist.push_back(TI->getSuccessor(i));
10722   }
10723 }
10724
10725 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10726   bool Changed = false;
10727   TD = &getAnalysis<TargetData>();
10728   
10729   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10730              << F.getNameStr() << "\n");
10731
10732   {
10733     // Do a depth-first traversal of the function, populate the worklist with
10734     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
10735     // track of which blocks we visit.
10736     SmallPtrSet<BasicBlock*, 64> Visited;
10737     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10738
10739     // Do a quick scan over the function.  If we find any blocks that are
10740     // unreachable, remove any instructions inside of them.  This prevents
10741     // the instcombine code from having to deal with some bad special cases.
10742     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10743       if (!Visited.count(BB)) {
10744         Instruction *Term = BB->getTerminator();
10745         while (Term != BB->begin()) {   // Remove instrs bottom-up
10746           BasicBlock::iterator I = Term; --I;
10747
10748           DOUT << "IC: DCE: " << *I;
10749           ++NumDeadInst;
10750
10751           if (!I->use_empty())
10752             I->replaceAllUsesWith(UndefValue::get(I->getType()));
10753           I->eraseFromParent();
10754         }
10755       }
10756   }
10757
10758   while (!Worklist.empty()) {
10759     Instruction *I = RemoveOneFromWorkList();
10760     if (I == 0) continue;  // skip null values.
10761
10762     // Check to see if we can DCE the instruction.
10763     if (isInstructionTriviallyDead(I)) {
10764       // Add operands to the worklist.
10765       if (I->getNumOperands() < 4)
10766         AddUsesToWorkList(*I);
10767       ++NumDeadInst;
10768
10769       DOUT << "IC: DCE: " << *I;
10770
10771       I->eraseFromParent();
10772       RemoveFromWorkList(I);
10773       continue;
10774     }
10775
10776     // Instruction isn't dead, see if we can constant propagate it.
10777     if (Constant *C = ConstantFoldInstruction(I, TD)) {
10778       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10779
10780       // Add operands to the worklist.
10781       AddUsesToWorkList(*I);
10782       ReplaceInstUsesWith(*I, C);
10783
10784       ++NumConstProp;
10785       I->eraseFromParent();
10786       RemoveFromWorkList(I);
10787       continue;
10788     }
10789
10790     // See if we can trivially sink this instruction to a successor basic block.
10791     if (I->hasOneUse()) {
10792       BasicBlock *BB = I->getParent();
10793       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10794       if (UserParent != BB) {
10795         bool UserIsSuccessor = false;
10796         // See if the user is one of our successors.
10797         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10798           if (*SI == UserParent) {
10799             UserIsSuccessor = true;
10800             break;
10801           }
10802
10803         // If the user is one of our immediate successors, and if that successor
10804         // only has us as a predecessors (we'd have to split the critical edge
10805         // otherwise), we can keep going.
10806         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10807             next(pred_begin(UserParent)) == pred_end(UserParent))
10808           // Okay, the CFG is simple enough, try to sink this instruction.
10809           Changed |= TryToSinkInstruction(I, UserParent);
10810       }
10811     }
10812
10813     // Now that we have an instruction, try combining it to simplify it...
10814 #ifndef NDEBUG
10815     std::string OrigI;
10816 #endif
10817     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10818     if (Instruction *Result = visit(*I)) {
10819       ++NumCombined;
10820       // Should we replace the old instruction with a new one?
10821       if (Result != I) {
10822         DOUT << "IC: Old = " << *I
10823              << "    New = " << *Result;
10824
10825         // Everything uses the new instruction now.
10826         I->replaceAllUsesWith(Result);
10827
10828         // Push the new instruction and any users onto the worklist.
10829         AddToWorkList(Result);
10830         AddUsersToWorkList(*Result);
10831
10832         // Move the name to the new instruction first.
10833         Result->takeName(I);
10834
10835         // Insert the new instruction into the basic block...
10836         BasicBlock *InstParent = I->getParent();
10837         BasicBlock::iterator InsertPos = I;
10838
10839         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
10840           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10841             ++InsertPos;
10842
10843         InstParent->getInstList().insert(InsertPos, Result);
10844
10845         // Make sure that we reprocess all operands now that we reduced their
10846         // use counts.
10847         AddUsesToWorkList(*I);
10848
10849         // Instructions can end up on the worklist more than once.  Make sure
10850         // we do not process an instruction that has been deleted.
10851         RemoveFromWorkList(I);
10852
10853         // Erase the old instruction.
10854         InstParent->getInstList().erase(I);
10855       } else {
10856 #ifndef NDEBUG
10857         DOUT << "IC: Mod = " << OrigI
10858              << "    New = " << *I;
10859 #endif
10860
10861         // If the instruction was modified, it's possible that it is now dead.
10862         // if so, remove it.
10863         if (isInstructionTriviallyDead(I)) {
10864           // Make sure we process all operands now that we are reducing their
10865           // use counts.
10866           AddUsesToWorkList(*I);
10867
10868           // Instructions may end up in the worklist more than once.  Erase all
10869           // occurrences of this instruction.
10870           RemoveFromWorkList(I);
10871           I->eraseFromParent();
10872         } else {
10873           AddToWorkList(I);
10874           AddUsersToWorkList(*I);
10875         }
10876       }
10877       Changed = true;
10878     }
10879   }
10880
10881   assert(WorklistMap.empty() && "Worklist empty, but map not?");
10882     
10883   // Do an explicit clear, this shrinks the map if needed.
10884   WorklistMap.clear();
10885   return Changed;
10886 }
10887
10888
10889 bool InstCombiner::runOnFunction(Function &F) {
10890   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10891   
10892   bool EverMadeChange = false;
10893
10894   // Iterate while there is work to do.
10895   unsigned Iteration = 0;
10896   while (DoOneIteration(F, Iteration++)) 
10897     EverMadeChange = true;
10898   return EverMadeChange;
10899 }
10900
10901 FunctionPass *llvm::createInstructionCombiningPass() {
10902   return new InstCombiner();
10903 }
10904